summaryrefslogtreecommitdiff
path: root/graphics/src/render.rs
blob: 499301cec398a2641a5b99f870b43880fe089ef6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! The `render` module contains the structures for displaying
//! the game, with each frame represented by a `Renderer` and
//! frame specific information in `FrameInfo`.

use std::{cell::RefCell, ops::Div, rc::Rc};

use dungeon::{
	Direction, Dungeon, Entity, EntityKind, FPos, Floor, MAP_SIZE, PLAYER_FULL_HEALTH,
	Player, Pos, Tile,
};
use raylib::{
	RaylibThread,
	camera::Camera2D,
	color::Color,
	math::{Rectangle, Vector2},
	prelude::{
		RaylibDraw, RaylibDrawHandle, RaylibHandle, RaylibMode2D, RaylibMode2DExt,
		RaylibTextureModeExt,
	},
	texture::{RaylibTexture2D, RenderTexture2D},
};

use crate::assets::{AtlasTexture, BASE_TILE_SIZE, ImageData, WALL_HEIGHT};

/// The (prefered) view distance of the game
const VIEW_DISTANCE: i32 = 5;

/// Full source rec for any texture
const FULL_SOURCE_REC: Rectangle = Rectangle {
	x: 0.0,
	y: 0.0,
	width: BASE_TILE_SIZE as f32,
	height: BASE_TILE_SIZE as f32,
};

/// The `FrameInfo` struct stores information used during a single frame
#[derive(Clone, Copy, Debug)]
struct FrameInfo {
	/// The last calculated fps
	fps: u32,
	/// The render width of the framebuffer in pixels
	width: i32,
	/// The render height of the framebuffer in pixels
	height: i32,
	/// The tile size in pixels
	tile_size: i32,
}
impl FrameInfo {
	fn new(handle: &RaylibHandle) -> Self {
		let fps = handle.get_fps();
		let width = handle.get_render_width();
		let height = handle.get_render_height();
		let tile_size = {
			let size = width.min(height);
			let dist = VIEW_DISTANCE * 2 + 1;
			let pixels = size.div(dist).max(BASE_TILE_SIZE);
			1 << (i32::BITS - pixels.leading_zeros())
		};

		Self {
			fps,
			width,
			height,
			tile_size,
		}
	}
}

/// The `State` struct stores persistant renderer data used across multiple frames
#[derive(Debug)]
struct State {
	/// Set of sprites to be drawn
	image: ImageData,
	/// Top layer of the tile map (used for back and top sides of walls)
	tiles_tex_fg: RefCell<RenderTexture2D>,
	/// Bottom layer of the tile map (used for most things)
	tiles_tex_bg: RefCell<RenderTexture2D>,
	/// Hash of tiles used to draw the tile textures
	tiles_hash: RefCell<u64>,
}
impl State {
	fn new(
		handle: &mut RaylibHandle,
		thread: &RaylibThread,
		image: ImageData,
	) -> crate::Result<Self> {
		let tex_size = MAP_SIZE as u32 * BASE_TILE_SIZE as u32;
		let tiles_tex_fg = handle.load_render_texture(thread, tex_size, tex_size)?;
		let tiles_tex_bg = handle.load_render_texture(thread, tex_size, tex_size)?;

		Ok(Self {
			image,
			tiles_tex_fg: RefCell::new(tiles_tex_fg),
			tiles_tex_bg: RefCell::new(tiles_tex_bg),
			tiles_hash: RefCell::new(0),
		})
	}
}

/// The `Renderer` struct is the persistant renderer
/// for the duration for the application.
#[derive(Debug)]
pub struct Renderer {
	/// Persistant render state
	state: Rc<State>,
}
impl Renderer {
	pub(crate) fn new(
		handle: &mut RaylibHandle,
		thread: &RaylibThread,
		image: ImageData,
	) -> crate::Result<Self> {
		let state = Rc::new(State::new(handle, thread, image)?);

		Ok(Self { state })
	}

	/// Invokes the renderer for the current frame
	pub(crate) fn invoke<'a>(
		&'a mut self,
		handle: &'a mut RaylibHandle,
		thread: &'a RaylibThread,
	) -> FrameRendererImpl<'a> {
		let info = FrameInfo::new(handle);
		let state = Rc::clone(&self.state);
		FrameRenderer {
			handle: handle.begin_drawing(thread),
			thread,
			info,
			state,
		}
	}
}

pub type FrameRendererImpl<'a> = FrameRenderer<'a, RaylibDrawHandle<'a>>;

macro_rules! tex_renderer {
	($fr:expr, $tex:expr) => {
		FrameRenderer {
			handle: $fr.handle.begin_texture_mode($fr.thread, $tex),
			thread: &$fr.thread,
			info: $fr.info,
			state: Rc::clone(&$fr.state),
		}
	};
}

pub struct FrameRenderer<'a, T>
where
	T: RaylibDraw,
{
	/// The current draw handle for raylib
	handle: T,
	/// The raylib thread
	thread: &'a RaylibThread,
	/// Non drawing information for this current frame
	info: FrameInfo,
	/// Persistant render state
	state: Rc<State>,
}
impl<'a, T> FrameRenderer<'a, T>
where
	T: RaylibDraw + RaylibMode2DExt + RaylibTextureModeExt,
{
	/// Draws an entire frame
	pub fn draw_frame(&mut self, dungeon: &Dungeon) {
		self.clear(Color::BLACK);
		self.draw_dungeon(dungeon);
		self.draw_ui(dungeon);
	}

	/// Draws the dungeon, (tiles and entities)
	pub fn draw_dungeon(&mut self, dungeon: &Dungeon) {
		self.update_tilemaps(&dungeon.floor);
		let camera = dungeon.camera();
		let mut renderer = self.camera_renderer(camera);
		renderer.draw_tiles_bg();
		renderer.draw_entities(dungeon);
		renderer.draw_tiles_fg();
	}
}
impl<'a, T> FrameRenderer<'a, T>
where
	T: RaylibDraw + RaylibMode2DExt,
{
	/// Returns a raylib camera for the given position
	#[must_use]
	fn camera_renderer<'b>(
		&'b mut self,
		cpos: FPos,
	) -> FrameRenderer<'b, RaylibMode2D<'b, T>> {
		let width = self.info.width;
		let height = self.info.height;
		let camera = Camera2D {
			target: Vector2::from(cpos.xy())
				.scale_by(self.info.tile_size as f32)
				.max(Vector2::new(width as f32 / 2.0, height as f32 / 2.0))
				.min(Vector2::new(
					(MAP_SIZE as i32 * self.info.tile_size) as f32 - (width as f32 / 2.0),
					(MAP_SIZE as i32 * self.info.tile_size) as f32 - (height as f32 / 2.0),
				)),
			offset: Vector2::new(width as f32 / 2.0, height as f32 / 2.0),
			rotation: 0.0,
			zoom: 1.0,
		};
		let handle = self.handle.begin_mode2D(camera);
		FrameRenderer {
			handle,
			thread: self.thread,
			info: self.info,
			state: Rc::clone(&self.state),
		}
	}
}
impl<'a, T> FrameRenderer<'a, T>
where
	T: RaylibDraw + RaylibTextureModeExt,
{
	/// Updates all tilemaps
	fn update_tilemaps(&mut self, floor: &Floor) {
		let hash = floor.hash();
		let old_hash = std::mem::replace(&mut *self.state.tiles_hash.borrow_mut(), hash);
		if old_hash == hash {
			// Textures are up to date
			return;
		}

		self.update_fg_tilemap(floor);
		self.update_bg_tilemap(floor);
	}

	/// Draws the foregound tile map
	fn update_fg_tilemap(&mut self, floor: &Floor) {
		let size = BASE_TILE_SIZE as f32;
		let tex = &mut self.state.tiles_tex_fg.borrow_mut();
		let mut renderer = tex_renderer!(self, tex);
		renderer.clear(Color::BLANK);

		for pos in Pos::values() {
			let (fx, fy) = FPos::from(pos).xy();
			let (xs, ys) = (fx * size, fy * size);

			// fg layer only draws a top walls
			if floor.get(pos) != Tile::Wall {
				continue;
			};

			// draw base wall top texture
			renderer.draw_atlas(AtlasTexture::WallBase, xs, ys, size, 0.0);

			// draw top wall borders
			let is_wall =
				|dir| pos.step(dir).map_or(Tile::Wall, |p| floor.get(p)).is_wall();
			if !is_wall(Direction::North) {
				renderer.draw_atlas(AtlasTexture::WallEdgeNorth, xs, ys, size, 0.0);
			}
			if !is_wall(Direction::East) {
				renderer.draw_atlas(AtlasTexture::WallEdgeEast, xs, ys, size, 0.0);
			}
			if !is_wall(Direction::South) {
				renderer.draw_atlas(AtlasTexture::WallEdgeSouth, xs, ys, size, 0.0);
			}
			if !is_wall(Direction::West) {
				renderer.draw_atlas(AtlasTexture::WallEdgeWest, xs, ys, size, 0.0);
			}
		}
	}

	/// Draws the foregound tile map
	fn update_bg_tilemap(&mut self, floor: &Floor) {
		let size = BASE_TILE_SIZE as f32;
		let tex = &mut self.state.tiles_tex_bg.borrow_mut();
		let mut renderer = tex_renderer!(self, tex);
		renderer.clear(Color::BLACK);

		for pos in Pos::values() {
			let (x, y) = pos.xy();
			let tile = floor.get(pos);
			let tex = match tile {
				Tile::Wall => AtlasTexture::Wall,
				Tile::Air if (x + y) % 2 == 0 => AtlasTexture::FloorFull,
				Tile::Air if (x + y) % 2 == 1 => AtlasTexture::FloorEmpty,
				_ => AtlasTexture::Error,
			};
			renderer.draw_atlas(tex, x as f32 * size, y as f32 * size, size, 0.0);
		}
	}
}
impl<'a, T> FrameRenderer<'a, T>
where
	T: RaylibDraw,
{
	/// Clear the screen
	pub fn clear(&mut self, color: Color) {
		self.handle.clear_background(color);
	}

	/// Draws player HP, inventory, and floor number
	pub fn draw_ui(&mut self, dungeon: &Dungeon) {
		// Draw core ui components
		self.draw_health(&dungeon.player);
		self.draw_inventory(&dungeon.player);

		// Draw debug info
		#[cfg(feature = "debug")]
		self.draw_debug_ui(dungeon);
	}

	fn draw_health(&mut self, player: &Player) {
		let health = player.entity.health.unwrap_or(0);
		let hearts = PLAYER_FULL_HEALTH.div_ceil(2);
		let mut full_hearts = health / 2;
		let mut half_hearts = health % 2;
		let mut empty_hearts = hearts.saturating_sub(full_hearts + half_hearts);

		let size = self.info.tile_size.div(2).max(BASE_TILE_SIZE);
		let y = BASE_TILE_SIZE;
		let mut x = BASE_TILE_SIZE;
		loop {
			let tex = if full_hearts > 0 {
				full_hearts -= 1;
				&self.state.image.heart_full
			} else if half_hearts > 0 {
				half_hearts -= 1;
				&self.state.image.heart_half
			} else if empty_hearts > 0 {
				empty_hearts -= 1;
				&self.state.image.heart_empty
			} else {
				break;
			};

			let dest_rec = Rectangle {
				x: x as f32,
				y: y as f32,
				width: size as f32,
				height: size as f32,
			};
			self.handle.draw_texture_pro(
				tex,
				FULL_SOURCE_REC,
				dest_rec,
				Vector2::zero(),
				0.0,
				Color::WHITE,
			);
			x += size;
		}
	}

	fn draw_inventory(&mut self, player: &Player) {
		let len = i32::try_from(player.inventory.len()).unwrap_or(0);

		// size of the inv blocks
		let size = self.info.tile_size.div(2).max(BASE_TILE_SIZE);

		// position of the inv blocks
		let y = self.info.height - size;
		let mut x = self.info.width / 2 - (size * len / 2);

		// size of font for number index
		let font_size = size / 3;
		let font_offset = font_size * 2;

		for (idx, item) in player.inventory.iter().enumerate() {
			let dest_rec = Rectangle {
				x: x as f32,
				y: y as f32,
				width: size as f32,
				height: size as f32,
			};
			self.draw_ui_atlas(
				AtlasTexture::InvBottomLayer,
				x as f32,
				y as f32,
				size as f32,
			);
			let tex = self.state.image.get_item_texture(item);
			self.handle.draw_texture_pro(
				tex,
				FULL_SOURCE_REC,
				dest_rec,
				Vector2::zero(),
				0.0,
				Color::WHITE,
			);
			self.draw_ui_atlas(AtlasTexture::InvTopLayer, x as f32, y as f32, size as f32);
			self.handle.draw_text(
				&format!("{}", idx + 1),
				x + font_offset + font_offset / 5,
				y + font_offset,
				font_size,
				Color::WHITE,
			);
			x += size;
		}
	}

	/// Draws debug information ontop of other UI elements
	/// Called by default if `debug` featue is enabled
	pub fn draw_debug_ui(&mut self, _dungeon: &Dungeon) {
		self.draw_fps();
	}

	/// Draw FPS counter (debug)
	fn draw_fps(&mut self) {
		let fps_str = format!("{}", self.info.fps);
		self.handle.draw_text(&fps_str, 10, 10, 30, Color::YELLOW);
	}

	/// Draws the entities on the map
	fn draw_entities(&mut self, dungeon: &Dungeon) {
		self.draw_entity(&dungeon.player.entity);
	}

	/// Draws an entity
	fn draw_entity(&mut self, entity: &Entity) {
		let size = self.info.tile_size as f32;
		let x = entity.fpos.x();
		let y = entity.fpos.y();
		let tex = match entity.kind {
			EntityKind::Player => AtlasTexture::Player,
			_ => AtlasTexture::Error,
		};
		self.draw_atlas(tex, x * size, y * size, size, 0.0);
	}

	/// Draw dungeon tiles (background layer)
	fn draw_tiles_bg(&mut self) {
		let tex = &*self.state.tiles_tex_bg.borrow();
		let size = self.info.tile_size as f32;
		let offset = 0.0;
		self.handle.draw_tilemap(tex, size, offset);
	}

	/// Draw dungeon tiles (foreground layer)
	fn draw_tiles_fg(&mut self) {
		let tex = &*self.state.tiles_tex_fg.borrow();
		let size = self.info.tile_size as f32;
		let offset = WALL_HEIGHT as f32;
		self.handle.draw_tilemap(tex, size, offset);
	}

	/// Draw an atlas texture index (with ui offset applied)
	fn draw_ui_atlas(&mut self, tex: AtlasTexture, x: f32, y: f32, size: f32) {
		let half_size = size / 2.0;
		self.draw_atlas(tex, x + half_size, y + half_size, size, 0.0);
	}

	/// Draw an atlas texture index
	fn draw_atlas(&mut self, tex: AtlasTexture, x: f32, y: f32, size: f32, rotation: f32) {
		let source_rec = Rectangle {
			x: (tex.x() * BASE_TILE_SIZE) as f32,
			y: (tex.y() * BASE_TILE_SIZE) as f32,
			width: BASE_TILE_SIZE as f32,
			height: BASE_TILE_SIZE as f32,
		};
		let dest_rec = Rectangle {
			x,
			y,
			width: size,
			height: size,
		};
		let origin = Vector2 {
			x: dest_rec.width / 2.0,
			y: dest_rec.height / 2.0,
		};
		self.handle.draw_texture_pro(
			&self.state.image.atlas,
			source_rec,
			dest_rec,
			origin,
			rotation,
			Color::WHITE,
		);
	}
}

trait Vector2Ext {
	fn min(self, other: Self) -> Self;
	fn max(self, other: Self) -> Self;
}
impl Vector2Ext for Vector2 {
	fn min(self, other: Self) -> Self {
		Self::new(self.x.min(other.x), self.y.min(other.y))
	}

	fn max(self, other: Self) -> Self {
		Self::new(self.x.max(other.x), self.y.max(other.y))
	}
}

trait RaylibDrawExt: RaylibDraw {
	/// Draw dungeon tiles helper function
	fn draw_tilemap(&mut self, tex: &RenderTexture2D, size: f32, offset: f32) {
		let scale = size / BASE_TILE_SIZE as f32;
		let width = tex.width() as f32;
		let height = tex.height() as f32;
		let source_rec = Rectangle {
			x: 0.0,
			y: 0.0,
			width,
			height: -height,
		};
		let dest_rec = Rectangle {
			x: 0.0,
			y: -(offset * scale),
			width: width * scale,
			height: height * scale,
		};
		let origin = Vector2::zero();
		self.draw_texture_pro(tex, source_rec, dest_rec, origin, 0.0, Color::WHITE);
	}
}
impl<T: RaylibDraw> RaylibDrawExt for T {}