From 3460d889aa2e7af1a60d218a1a8589027b4e4e63 Mon Sep 17 00:00:00 2001 From: salmonik Date: Thu, 9 Jul 2026 23:27:55 +0200 Subject: init --- src/game.rs | 204 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 90 +++++++++++++++++++++++++ src/renderer.rs | 196 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/texture.rs | 102 ++++++++++++++++++++++++++++ 4 files changed, 592 insertions(+) create mode 100644 src/game.rs create mode 100644 src/main.rs create mode 100644 src/renderer.rs create mode 100644 src/texture.rs (limited to 'src') diff --git a/src/game.rs b/src/game.rs new file mode 100644 index 0000000..4bedecc --- /dev/null +++ b/src/game.rs @@ -0,0 +1,204 @@ +use rand::Rng; + +// --------------- maze grid --------------- + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Cell { + Wall, + Passage, + Exit, +} + +pub struct Maze { + cells: Vec, + width: usize, + height: usize, +} + +impl Maze { + /// Recursive-backtracker perfect maze. `room_w × room_h` is the logical + /// room count; the actual grid will be `(room_w*2+1) × (room_h*2+1)`. + pub fn generate(room_w: usize, room_h: usize, rng: &mut impl Rng) -> Self { + let w = room_w * 2 + 1; + let h = room_h * 2 + 1; + + let mut cells = vec![Cell::Wall; w * h]; + cells[1 * w + 1] = Cell::Passage; + + let mut stack = vec![(1usize, 1usize)]; + + while let Some(&(cy, cx)) = stack.last() { + let mut unvisited = Vec::new(); + + for (dy, dx) in [(-2isize, 0isize), (2, 0), (0, -2), (0, 2)] { + let ny = cy as isize + dy; + let nx = cx as isize + dx; + if ny >= 1 && ny < (h - 1) as isize && nx >= 1 && nx < (w - 1) as isize { + if cells[ny as usize * w + nx as usize] == Cell::Wall { + unvisited.push((ny as usize, nx as usize)); + } + } + } + + if unvisited.is_empty() { + stack.pop(); + } else { + let idx = rng.gen_range(0..unvisited.len()); + let (ny, nx) = unvisited[idx]; + + // carve the wall between current cell and chosen neighbour + let wall_y = (cy + ny) / 2; + let wall_x = (cx + nx) / 2; + cells[wall_y * w + wall_x] = Cell::Passage; + cells[ny * w + nx] = Cell::Passage; + + stack.push((ny, nx)); + } + } + + // ---- place exit in a far-away passage ---- + let mut passages: Vec<(f64, usize, usize)> = Vec::new(); + for y in (1..h).step_by(2) { + for x in (1..w).step_by(2) { + if cells[y * w + x] == Cell::Passage && !(y == 1 && x == 1) { + let dist = ((y as f64 - 1.0).powi(2) + (x as f64 - 1.0).powi(2)).sqrt(); + passages.push((dist, y, x)); + } + } + } + + if !passages.is_empty() { + passages.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); + let far_count = (passages.len() / 4).max(1); + let idx = rng.gen_range(0..far_count); + let (_, ey, ex) = passages[idx]; + cells[ey * w + ex] = Cell::Exit; + } + + Self { + cells, + width: w, + height: h, + } + } + + #[inline] + pub fn is_wall(&self, y: usize, x: usize) -> bool { + self.cells + .get(y * self.width + x) + .map_or(true, |&c| c == Cell::Wall) + } + + /// Floating-point query — out-of-bounds is treated as wall. + #[inline] + pub fn is_passage_at_float(&self, x: f64, y: f64) -> bool { + let xi = x as usize; + let yi = y as usize; + if xi >= self.width || yi >= self.height { + return false; + } + self.cells[yi * self.width + xi] != Cell::Wall + } + + #[inline] + pub fn is_exit(&self, x: f64, y: f64) -> bool { + let xi = x as usize; + let yi = y as usize; + if xi >= self.width || yi >= self.height { + return false; + } + self.cells[yi * self.width + xi] == Cell::Exit + } + + pub fn width(&self) -> usize { + self.width + } + pub fn height(&self) -> usize { + self.height + } +} + +// --------------- player --------------- + +pub struct Player { + pub x: f64, + pub y: f64, + pub angle: f64, // radians, 0 = +x (east), π/2 = +y (south) +} + +impl Player { + pub fn new(x: f64, y: f64, angle: f64) -> Self { + Self { x, y, angle } + } + + pub fn rotate(&mut self, delta: f64) { + self.angle = (self.angle + delta).rem_euclid(2.0 * std::f64::consts::PI); + } + + /// Apply a raw (dx, dy) displacement with wall-sliding collision. + /// Checks are done per-axis so the player slides along walls naturally. + pub fn try_move(&mut self, dx: f64, dy: f64, maze: &Maze) { + let m = 0.35; // collision margin — keeps the camera out of walls + + let nx = self.x + dx; + if maze.is_passage_at_float(nx + m, self.y + m) + && maze.is_passage_at_float(nx + m, self.y - m) + && maze.is_passage_at_float(nx - m, self.y + m) + && maze.is_passage_at_float(nx - m, self.y - m) + { + self.x = nx; + } + + let ny = self.y + dy; + if maze.is_passage_at_float(self.x + m, ny + m) + && maze.is_passage_at_float(self.x - m, ny + m) + && maze.is_passage_at_float(self.x + m, ny - m) + && maze.is_passage_at_float(self.x - m, ny - m) + { + self.y = ny; + } + } +} + +// --------------- top-level game --------------- + +pub struct Game { + pub maze: Maze, + pub player: Player, + pub wall_texture: Vec, + pub floor_texture: Vec, +} + +impl Game { + pub fn new() -> Self { + let mut rng = rand::thread_rng(); + let maze = Maze::generate(16, 16, &mut rng); // 33×33 grid + let player = Player::new(1.5, 1.5, 0.0); // start centre of (1,1), facing east + let wall_texture = crate::texture::generate_wall_texture(&mut rng); + let floor_texture = crate::texture::generate_floor_texture(&mut rng); + + Self { + maze, + player, + wall_texture, + floor_texture, + } + } + + pub fn rotate(&mut self, delta: f64) { + self.player.rotate(delta); + } + + /// Apply forward + strafe as a single combined displacement so that + /// diagonal wall-hugging is checked atomically (no two-step clip). + pub fn apply_movement(&mut self, forward: f64, strafe: f64) { + let a = self.player.angle; + let dx = a.cos() * forward + (a + std::f64::consts::FRAC_PI_2).cos() * strafe; + let dy = a.sin() * forward + (a + std::f64::consts::FRAC_PI_2).sin() * strafe; + self.player.try_move(dx, dy, &self.maze); + } + + pub fn check_win(&self) -> bool { + self.maze.is_exit(self.player.x, self.player.y) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..d51fdfd --- /dev/null +++ b/src/main.rs @@ -0,0 +1,90 @@ +mod game; +mod renderer; +mod texture; + +use game::Game; +use minifb::{Key, Window, WindowOptions}; +use renderer::Renderer; +use std::time::Instant; + +const SCREEN_W: usize = 640; +const SCREEN_H: usize = 480; + +fn main() { + println!("=== DOOM-LIKE MAZE ==="); + println!("Find the exit!"); + println!(" W / Up — forward"); + println!(" S / Down — backward"); + println!(" A / D — strafe left / right"); + println!(" ← / → — turn"); + println!(" Esc — quit\n"); + + let mut game = Game::new(); + let renderer = Renderer::new(SCREEN_W, SCREEN_H); + + let mut window = Window::new( + "Maze — Find the Exit!", + SCREEN_W, + SCREEN_H, + WindowOptions::default(), + ) + .expect("Failed to create window"); + + let mut framebuffer = vec![0u32; SCREEN_W * SCREEN_H]; + let mut last = Instant::now(); + let frame_budget = std::time::Duration::from_micros(16600); // ~60 fps + + while window.is_open() && !window.is_key_down(Key::Escape) { + let frame_start = Instant::now(); + let dt = (frame_start - last).as_secs_f64().min(0.1); + last = frame_start; + + // ---- input ---- + let move_speed = 2.8; + let turn_speed = 2.8; + let strafe_speed = 2.2; + + if window.is_key_down(Key::Left) { + game.rotate(-turn_speed * dt); + } + if window.is_key_down(Key::Right) { + game.rotate(turn_speed * dt); + } + // Combine forward + strafe into one displacement (prevents two-step + // wall clipping when pressing W+D / W+A near a wall). + let fwd = if window.is_key_down(Key::W) || window.is_key_down(Key::Up) { + move_speed * dt + } else if window.is_key_down(Key::S) || window.is_key_down(Key::Down) { + -move_speed * dt + } else { + 0.0 + }; + let strf = if window.is_key_down(Key::D) { + strafe_speed * dt + } else if window.is_key_down(Key::A) { + -strafe_speed * dt + } else { + 0.0 + }; + game.apply_movement(fwd, strf); + + // ---- win condition ---- + if game.check_win() { + println!("🎉 You found the exit! Generating a new maze…"); + game = Game::new(); + last = Instant::now(); // avoid huge dt spike + } + + // ---- render ---- + renderer.render(&game, &mut framebuffer); + window + .update_with_buffer(&framebuffer, SCREEN_W, SCREEN_H) + .unwrap(); + + // Sleep the remainder of the frame budget (saves CPU). + let elapsed = frame_start.elapsed(); + if elapsed < frame_budget { + std::thread::sleep(frame_budget - elapsed); + } + } +} diff --git a/src/renderer.rs b/src/renderer.rs new file mode 100644 index 0000000..0792537 --- /dev/null +++ b/src/renderer.rs @@ -0,0 +1,196 @@ +use crate::game::Game; +use crate::texture::TEX_SIZE; + +pub struct Renderer { + screen_w: usize, + screen_h: usize, + /// Precomputed: floor_dist_lut[row] = perpendicular distance to floor at that row. + floor_dist_lut: Vec, + /// Precomputed: floor_bright_lut[row] = brightness × 256 for that row (fixed-point). + floor_bright_lut: Vec, +} + +impl Renderer { + pub fn new(screen_w: usize, screen_h: usize) -> Self { + let half_h = screen_h as f64 / 2.0; + let mut floor_dist_lut = vec![0.0f64; screen_h]; + let mut floor_bright_lut = vec![0u32; screen_h]; + + // Only rows below the horizon have meaningful floor values. + for py in (screen_h / 2 + 1)..screen_h { + let dy = py as f64 - half_h; + let dist = 0.5 * screen_h as f64 / dy; + floor_dist_lut[py] = dist; + let bright = (1.0 / (1.0 + dist * 0.15)).max(0.05); + floor_bright_lut[py] = (bright * 256.0) as u32; + } + + Self { + screen_w, + screen_h, + floor_dist_lut, + floor_bright_lut, + } + } + + /// Produce one frame into `buffer` (packed `0xAARRGGBB`). + pub fn render(&self, game: &Game, buffer: &mut [u32]) { + buffer.fill(0xFF00_0000); // pure-black ceiling + + let half_h = self.screen_h as f64 / 2.0; + let fov = std::f64::consts::PI / 3.0; // 60° + + for sx in 0..self.screen_w { + let cam_x = 2.0 * sx as f64 / self.screen_w as f64 - 1.0; + let ray_angle = game.player.angle + (fov / 2.0) * cam_x; + let rdx = ray_angle.cos(); + let rdy = ray_angle.sin(); + + // ---- DDA setup ------------------------------------------------- + let mut map_x = game.player.x as isize; + let mut map_y = game.player.y as isize; + + let ddx = if rdx == 0.0 { + f64::MAX + } else { + (1.0 / rdx).abs() + }; + let ddy = if rdy == 0.0 { + f64::MAX + } else { + (1.0 / rdy).abs() + }; + + let (step_x, mut side_x) = if rdx < 0.0 { + (-1isize, (game.player.x - map_x as f64) * ddx) + } else { + (1isize, (map_x as f64 + 1.0 - game.player.x) * ddx) + }; + + let (step_y, mut side_y) = if rdy < 0.0 { + (-1isize, (game.player.y - map_y as f64) * ddy) + } else { + (1isize, (map_y as f64 + 1.0 - game.player.y) * ddy) + }; + + let mut hit_side: bool; + let euclidean: f64; + + // ---- DDA loop -------------------------------------------------- + loop { + if side_x < side_y { + side_x += ddx; + map_x += step_x; + hit_side = false; + } else { + side_y += ddy; + map_y += step_y; + hit_side = true; + } + + if map_y < 0 + || map_y >= game.maze.height() as isize + || map_x < 0 + || map_x >= game.maze.width() as isize + { + euclidean = 1.0; + break; + } + + if game.maze.is_wall(map_y as usize, map_x as usize) { + euclidean = if !hit_side { + (map_x as f64 - game.player.x + (1.0 - step_x as f64) / 2.0) / rdx + } else { + (map_y as f64 - game.player.y + (1.0 - step_y as f64) / 2.0) / rdy + }; + break; + } + } + + // Fisheye correction + let perp_dist = (euclidean * (ray_angle - game.player.angle).cos().abs()).max(0.001); + + // ---- wall slice ------------------------------------------------ + let wall_h = (self.screen_h as f64 / perp_dist) as isize; + let draw_start = ((-wall_h / 2) + self.screen_h as isize / 2).max(0) as usize; + let draw_end = ((wall_h / 2) + self.screen_h as isize / 2) + .min(self.screen_h as isize - 1) as usize; + + // Texture x-coordinate (uses Euclidean, not perp) + let wall_x = if !hit_side { + game.player.y + euclidean * rdy + } else { + game.player.x + euclidean * rdx + }; + let wall_x = wall_x - wall_x.floor(); + let tex_x = ((wall_x * TEX_SIZE as f64) as usize).min(TEX_SIZE - 1); + + // Hoist: brightness is identical for every pixel in this column + let wall_bright_fx = { + let b = (1.0 / (1.0 + perp_dist * 0.12)).max(0.08); + (b * 256.0) as u32 + }; + + for py in draw_start..=draw_end { + let tex_y = ((py as f64 - half_h + wall_h as f64 / 2.0) * TEX_SIZE as f64 + / wall_h as f64) as usize; + let tex_y = tex_y.min(TEX_SIZE - 1); + + let color = game.wall_texture[tex_y * TEX_SIZE + tex_x]; + buffer[py * self.screen_w + sx] = darken_fx(color, wall_bright_fx); + } + + // ---- floor below the wall -------------------------------------- + let floor_start = draw_end + 1; + if floor_start < self.screen_h { + for py in floor_start..self.screen_h { + let floor_dist = self.floor_dist_lut[py]; + + if floor_dist > 15.0 { + // Far floor → just a dark pixel, skip texture & world calc. + let gray = darken_fx(0xFF80_8080, self.floor_bright_lut[py]); + buffer[py * self.screen_w + sx] = gray; + } else { + let fx = game.player.x + floor_dist * rdx; + let fy = game.player.y + floor_dist * rdy; + + let ftx = ((fx.fract().abs() * TEX_SIZE as f64) as usize).min(TEX_SIZE - 1); + let fty = ((fy.fract().abs() * TEX_SIZE as f64) as usize).min(TEX_SIZE - 1); + + let color = game.floor_texture[fty * TEX_SIZE + ftx]; + buffer[py * self.screen_w + sx] = + darken_fx(color, self.floor_bright_lut[py]); + } + } + } + } + + // ---- crosshair ----------------------------------------------------- + let cx = self.screen_w / 2; + let cy = self.screen_h / 2; + let cross_color = 0xFF00_FF00; + for i in 0..=4isize { + if cy as isize - i >= 0 { + buffer[(cy - i as usize) * self.screen_w + cx] = cross_color; + } + if (cy + i as usize) < self.screen_h { + buffer[(cy + i as usize) * self.screen_w + cx] = cross_color; + } + if cx as isize - i >= 0 { + buffer[cy * self.screen_w + (cx - i as usize)] = cross_color; + } + if (cx + i as usize) < self.screen_w { + buffer[cy * self.screen_w + (cx + i as usize)] = cross_color; + } + } + } +} + +/// Integer darken: `bright_fx` is brightness × 256 in fixed-point. +#[inline(always)] +fn darken_fx(color: u32, bright_fx: u32) -> u32 { + let r = (((color >> 16) & 0xFF) * bright_fx) >> 8; + let g = (((color >> 8) & 0xFF) * bright_fx) >> 8; + let b = ((color & 0xFF) * bright_fx) >> 8; + 0xFF00_0000 | (r << 16) | (g << 8) | b +} diff --git a/src/texture.rs b/src/texture.rs new file mode 100644 index 0000000..bdbb15c --- /dev/null +++ b/src/texture.rs @@ -0,0 +1,102 @@ +use rand::Rng; + +pub const TEX_SIZE: usize = 64; + +/// Deterministic hash for coherent procedural noise. +fn hash(x: u32, y: u32, seed: u64) -> u64 { + let mut h = (x as u64).wrapping_mul(0x9e3779b9); + h = h.wrapping_add((y as u64).wrapping_mul(0x517cc1b727220a95)); + h = h.wrapping_add(seed); + h = (h ^ (h >> 33)).wrapping_mul(0xc6a4a7935bd1e995); + h = (h ^ (h >> 29)).wrapping_mul(0x5bd1e995); + h +} + +/// Brown cracked wall texture — 64×64, brick pattern with mortar lines and fissures. +pub fn generate_wall_texture(rng: &mut impl Rng) -> Vec { + let seed = rng.gen::(); + let mut tex = vec![0u32; TEX_SIZE * TEX_SIZE]; + + for y in 0..TEX_SIZE { + for x in 0..TEX_SIZE { + let h = hash(x as u32, y as u32, seed); + + let r = 105u8.wrapping_add((h % 50) as u8); + let g = 55u8.wrapping_add(((h >> 8) % 35) as u8); + let b = 22u8.wrapping_add(((h >> 16) % 25) as u8); + + // Brick mortar every 16 pixels + let mortar = y % 16 == 0 || y % 16 == 15; + + let (r, g, b) = if mortar { + (42, 20, 8) + } else { + let crack_hash = hash(x.wrapping_add(1000) as u32, y as u32, seed); + let crack_val = (crack_hash % 100) as u8; + if crack_val < 8 { + // dark crack + let factor = 0.30 + (crack_val as f64 / 8.0) * 0.25; + ( + (r as f64 * factor) as u8, + (g as f64 * factor) as u8, + (b as f64 * factor) as u8, + ) + } else if crack_val < 14 { + // light crack highlight + ( + (r.saturating_add(25)).min(255), + (g.saturating_add(18)).min(255), + (b.saturating_add(10)).min(255), + ) + } else { + (r, g, b) + } + }; + + tex[y * TEX_SIZE + x] = + 0xFF00_0000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32); + } + } + tex +} + +/// Gray stone-tile floor — 64×64, checkerboard with grout and subtle colour tint. +pub fn generate_floor_texture(rng: &mut impl Rng) -> Vec { + let seed = rng.gen::(); + let mut tex = vec![0u32; TEX_SIZE * TEX_SIZE]; + + for y in 0..TEX_SIZE { + for x in 0..TEX_SIZE { + let h = hash(x as u32, y as u32, seed); + let h2 = hash(x.wrapping_add(2000) as u32, y.wrapping_add(2000) as u32, seed); + + let tile_x = x / 16; + let tile_y = y / 16; + let is_light_tile = (tile_x + tile_y) % 2 == 0; + + let local_x = x % 16; + let local_y = y % 16; + let is_grout = local_x == 0 || local_y == 0; + + let base_gray: u8 = if is_light_tile { 115 } else { 95 }; + let noise = (h % 15) as u8; + + let tint_r = (h2 % 8) as i16 - 4i16; + let tint_b = ((h2 >> 8) % 8) as i16 - 4i16; + + let gray = if is_grout { + base_gray.saturating_sub(30).saturating_add(noise / 3) + } else { + base_gray.saturating_add(noise / 2) + }; + + let r = (gray as i16 + tint_r).clamp(0, 255) as u8; + let g = gray; + let b = (gray as i16 + tint_b).clamp(0, 255) as u8; + + tex[y * TEX_SIZE + x] = + 0xFF00_0000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32); + } + } + tex +} -- cgit v1.2.3