From d4892e33bdb61e9bd87a4a099cfa6c7bc3f286ac Mon Sep 17 00:00:00 2001 From: kjuulh Date: Sun, 30 Jan 2022 15:50:36 +0100 Subject: [PATCH] Add cellular automata --- .idea/workspace.xml | 14 ++- src/components.rs | 9 +- src/map_builders/bsp/mod.rs | 2 +- src/map_builders/bsp_dungeon.rs | 2 +- src/map_builders/bsp_interior.rs | 33 ++--- src/map_builders/cellular_automata.rs | 168 ++++++++++++++++++++++++++ src/map_builders/mod.rs | 9 +- src/map_builders/simple_map.rs | 2 +- src/spawner.rs | 112 ++++++++++------- 9 files changed, 275 insertions(+), 76 deletions(-) create mode 100644 src/map_builders/cellular_automata.rs diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 1aa83be..74c7e5c 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -13,12 +13,12 @@ - - - + + + - + @@ -49,6 +49,9 @@ + + + @@ -78,7 +82,7 @@ diff --git a/src/components.rs b/src/components.rs index 3f7b416..cbdee50 100644 --- a/src/components.rs +++ b/src/components.rs @@ -13,18 +13,13 @@ pub struct Position { impl Position { pub fn new(x: i32, y: i32) -> Self { - Self { - x, y - } + Self { x, y } } } impl Default for Position { fn default() -> Self { - Self { - x: 0, - y: 0 - } + Self { x: 0, y: 0 } } } diff --git a/src/map_builders/bsp/mod.rs b/src/map_builders/bsp/mod.rs index cc33133..3d6dc3d 100644 --- a/src/map_builders/bsp/mod.rs +++ b/src/map_builders/bsp/mod.rs @@ -19,4 +19,4 @@ pub fn draw_corridor(map: &mut Map, x1: i32, y1: i32, x2: i32, y2: i32) { let idx = map.xy_idx(x, y); map.tiles[idx] = TileType::Floor; } -} \ No newline at end of file +} diff --git a/src/map_builders/bsp_dungeon.rs b/src/map_builders/bsp_dungeon.rs index 7ecf5bc..bad4326 100644 --- a/src/map_builders/bsp_dungeon.rs +++ b/src/map_builders/bsp_dungeon.rs @@ -186,7 +186,7 @@ impl MapBuilder for BspDungeonBuilder { fn spawn_entities(&mut self, ecs: &mut World) { for room in self.rooms.iter().skip(1) { - spawner::spawn_room(ecs, room, self.depth, &self.map); + spawner::spawn_room(ecs, room, self.depth); } } diff --git a/src/map_builders/bsp_interior.rs b/src/map_builders/bsp_interior.rs index c2b77c6..102b783 100644 --- a/src/map_builders/bsp_interior.rs +++ b/src/map_builders/bsp_interior.rs @@ -1,10 +1,10 @@ -use rltk::RandomNumberGenerator; -use crate::{Map, Position, SHOW_MAPGEN_VISUALIZER, spawner, TileType, World}; use crate::map_builders::common::reveal_all; use crate::map_builders::{bsp, MapBuilder}; use crate::rect::Rect; +use crate::{spawner, Map, Position, TileType, World, SHOW_MAPGEN_VISUALIZER}; +use rltk::RandomNumberGenerator; -const MIN_ROOM_SIZE : i32 = 8; +const MIN_ROOM_SIZE: i32 = 8; pub struct BspInteriorBuilder { map: Map, @@ -16,18 +16,17 @@ pub struct BspInteriorBuilder { } impl BspInteriorBuilder { - pub fn new(new_depth: i32) -> Self{ + pub fn new(new_depth: i32) -> Self { Self { map: Map::new(new_depth), rects: Vec::new(), - history:Vec::new(), + history: Vec::new(), depth: new_depth, rooms: Vec::new(), - starting_position: Position::default() + starting_position: Position::default(), } } - fn build(&mut self) { let mut rng = RandomNumberGenerator::new(); @@ -54,8 +53,10 @@ impl BspInteriorBuilder { let next_room = self.rooms[i + 1]; let start_x = room.x1 + (rng.roll_dice(1, i32::abs(room.x1 - room.x2)) - 1); let start_y = room.y1 + (rng.roll_dice(1, i32::abs(room.y1 - room.y2)) - 1); - let end_x = next_room.x1 + (rng.roll_dice(1, i32::abs(next_room.x1 - next_room.x2)) - 1); - let end_y = next_room.y1 + (rng.roll_dice(1, i32::abs(next_room.y1 - next_room.y2)) - 1); + let end_x = + next_room.x1 + (rng.roll_dice(1, i32::abs(next_room.x1 - next_room.x2)) - 1); + let end_y = + next_room.y1 + (rng.roll_dice(1, i32::abs(next_room.y1 - next_room.y2)) - 1); self.draw_corridor(start_x, start_y, end_x, end_y); self.take_snapshot(); } @@ -63,7 +64,8 @@ impl BspInteriorBuilder { fn place_rooms(&mut self, mut rng: &mut RandomNumberGenerator) { self.rects.clear(); - self.rects.push(Rect::new(1, 1, self.map.width - 2, self.map.height - 2)); + self.rects + .push(Rect::new(1, 1, self.map.width - 2, self.map.height - 2)); let first_room = self.rects[0]; self.add_subrects(first_room, &mut rng); @@ -96,7 +98,7 @@ impl BspInteriorBuilder { let split = rng.roll_dice(1, 4); if split <= 2 { - let h1 = Rect::new(rect.x1, rect.y1, half_width -1, height); + let h1 = Rect::new(rect.x1, rect.y1, half_width - 1, height); self.rects.push(h1); if half_width > MIN_ROOM_SIZE { self.add_subrects(h1, rng); @@ -106,13 +108,13 @@ impl BspInteriorBuilder { if half_width > MIN_ROOM_SIZE { self.add_subrects(h2, rng); } - }else { - let v1 = Rect::new(rect.x1, rect.y1, width , half_height - 1); + } else { + let v1 = Rect::new(rect.x1, rect.y1, width, half_height - 1); self.rects.push(v1); if half_height > MIN_ROOM_SIZE { self.add_subrects(v1, rng); } - let v2 = Rect::new(rect.x1 , rect.y1 + half_height, width, half_height); + let v2 = Rect::new(rect.x1, rect.y1 + half_height, width, half_height); self.rects.push(v2); if half_height > MIN_ROOM_SIZE { self.add_subrects(v2, rng); @@ -132,7 +134,7 @@ impl MapBuilder for BspInteriorBuilder { fn spawn_entities(&mut self, ecs: &mut World) { for room in self.rooms.iter().skip(1) { - spawner::spawn_room(ecs, room, self.depth, &self.map); + spawner::spawn_room(ecs, room, self.depth); } } @@ -154,4 +156,3 @@ impl MapBuilder for BspInteriorBuilder { } } } - diff --git a/src/map_builders/cellular_automata.rs b/src/map_builders/cellular_automata.rs new file mode 100644 index 0000000..364a481 --- /dev/null +++ b/src/map_builders/cellular_automata.rs @@ -0,0 +1,168 @@ +use std::collections::HashMap; +use std::process::exit; +use rltk::RandomNumberGenerator; +use crate::map_builders::{common, MapBuilder}; +use crate::{Map, Position, World, SHOW_MAPGEN_VISUALIZER, TileType, spawner}; + +const MIN_ROOM_SIZE: i32 = 8; + +pub struct CellularAutomataBuilder { + map: Map, + starting_position: Position, + depth: i32, + history: Vec, + noise_areas : HashMap> +} + +impl CellularAutomataBuilder { + pub fn new(new_depth: i32) -> Self { + Self { + history: Vec::new(), + map: Map::new(new_depth), + depth: new_depth, + starting_position: Position::default(), + noise_areas: HashMap::new() + } + } + + fn build(&mut self) { + let mut rng = RandomNumberGenerator::new(); + + self.place_random_level(&mut rng); + self.take_snapshot(); + self.process_noise(); + let start_idx = self.place_start(); + self.place_exit(start_idx); + self.take_snapshot(); + self.place_spawn_areas(rng) + } + + fn place_spawn_areas(&mut self, mut rng: RandomNumberGenerator) { + let mut noise = rltk::FastNoise::seeded(rng.roll_dice(1, 65536) as u64); + noise.set_noise_type(rltk::NoiseType::Cellular); + noise.set_frequency(0.08); + noise.set_cellular_distance_function(rltk::CellularDistanceFunction::Manhattan); + + for y in 1..self.map.height - 1 { + for x in 1..self.map.width - 1 { + let idx = self.map.xy_idx(x, y); + if self.map.tiles[idx] == TileType::Floor { + let cell_value_f = noise.get_noise(x as f32, y as f32) * 10240.0; + let cell_value = cell_value_f as i32; + if self.noise_areas.contains_key(&cell_value) { + self.noise_areas.get_mut(&cell_value).unwrap().push(idx); + } else { + self.noise_areas.insert(cell_value, vec![idx]); + } + } + } + } + } + + fn place_exit(&mut self, start_idx: usize) { + let map_starts: Vec = vec![start_idx]; + let dijkstra_map = rltk::DijkstraMap::new(self.map.width, self.map.height, &map_starts, &self.map, 200.0); + let mut exit_tile = (0, 0.0f32); + for (i, tile) in self.map.tiles.iter_mut().enumerate() { + if *tile != TileType::Floor { + continue; + } + + let distance_to_start = dijkstra_map.map[i]; + if distance_to_start == f32::MAX { + *tile = TileType::Wall; + } else { + if distance_to_start > exit_tile.1 { + exit_tile.0 = i; + exit_tile.1 = distance_to_start; + } + } + } + self.take_snapshot(); + self.map.tiles[exit_tile.0] = TileType::DownStairs; + } + + fn place_start(&mut self) -> usize { + self.starting_position = Position::new(self.map.width / 2, self.map.height / 2); + let mut start_idx = self.map.xy_idx(self.starting_position.x, self.starting_position.y); + while self.map.tiles[start_idx] != TileType::Floor { + self.starting_position.x -= 1; + start_idx = self.map.xy_idx(self.starting_position.x, self.starting_position.y); + } + + return start_idx; + } + + fn process_noise(&mut self) { + for _i in 0..15 { + let mut new_tiles = self.map.tiles.clone(); + + for y in 1..self.map.height - 1 { + for x in 1..self.map.width - 1 { + let idx = self.map.xy_idx(x, y); + let mut neighbors = 0; + if self.map.tiles[idx - 1] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx + 1] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx - self.map.width as usize] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx + self.map.width as usize] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx - self.map.width as usize - 1] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx - self.map.width as usize + 1] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx + self.map.width as usize - 1] == TileType::Wall { neighbors += 1; } + if self.map.tiles[idx + self.map.width as usize + 1] == TileType::Wall { neighbors += 1; } + + if neighbors > 4 || neighbors == 0 { + new_tiles[idx] = TileType::Wall; + } else { + new_tiles[idx] = TileType::Floor; + } + } + } + self.map.tiles = new_tiles.clone(); + self.take_snapshot(); + } + } + + fn place_random_level(&mut self, rng: &mut RandomNumberGenerator) { + for y in 1..self.map.height - 1 { + for x in 1..self.map.width - 1 { + let roll = rng.roll_dice(1, 100); + let idx = self.map.xy_idx(x, y); + if roll > 55 { + self.map.tiles[idx] = TileType::Floor + } else { + self.map.tiles[idx] = TileType::Wall + } + } + } + } +} + +impl MapBuilder for CellularAutomataBuilder { + fn build_map(&mut self) { + self.build(); + } + + fn spawn_entities(&mut self, ecs: &mut World) { + for area in self.noise_areas.iter() { + spawner::spawn_region(ecs, area.1, self.depth); + } + } + + fn get_map(&self) -> Map { + self.map.clone() + } + + fn get_starting_position(&self) -> Position { + self.starting_position.clone() + } + + fn get_snapshot_history(&self) -> Vec { + self.history.clone() + } + + fn take_snapshot(&mut self) { + if SHOW_MAPGEN_VISUALIZER { + self.history.push(common::reveal_all(&self.map)) + } + } +} diff --git a/src/map_builders/mod.rs b/src/map_builders/mod.rs index 34a3cdf..079b242 100644 --- a/src/map_builders/mod.rs +++ b/src/map_builders/mod.rs @@ -1,13 +1,15 @@ use specs::World; use crate::map_builders::bsp_dungeon::BspDungeonBuilder; +use crate::map_builders::bsp_interior::BspInteriorBuilder; use crate::map_builders::simple_map::SimpleMapBuilder; use crate::{Map, Position}; -use crate::map_builders::bsp_interior::BspInteriorBuilder; +use crate::map_builders::cellular_automata::CellularAutomataBuilder; mod bsp; mod bsp_dungeon; mod bsp_interior; +mod cellular_automata; mod common; mod simple_map; @@ -22,9 +24,10 @@ pub trait MapBuilder { pub fn new_random_builder(new_depth: i32) -> Box { let mut rng = rltk::RandomNumberGenerator::new(); - //let builder_choice = rng.roll_dice(1, 3); - let builder_choice = 2; + //let builder_choice = rng.roll_dice(1, 4); + let builder_choice = 3; match builder_choice { + 3 => Box::new(CellularAutomataBuilder::new(new_depth)), 2 => Box::new(BspInteriorBuilder::new(new_depth)), 1 => Box::new(SimpleMapBuilder::new(new_depth)), _ => Box::new(BspDungeonBuilder::new(new_depth)), diff --git a/src/map_builders/simple_map.rs b/src/map_builders/simple_map.rs index abf3ec1..47f796c 100644 --- a/src/map_builders/simple_map.rs +++ b/src/map_builders/simple_map.rs @@ -83,7 +83,7 @@ impl MapBuilder for SimpleMapBuilder { fn spawn_entities(&mut self, ecs: &mut World) { for room in self.rooms.iter().skip(1) { - spawner::spawn_room(ecs, room, self.depth, &self.map); + spawner::spawn_room(ecs, room, self.depth); } } diff --git a/src/spawner.rs b/src/spawner.rs index 8ccb8f7..bfb1cdd 100644 --- a/src/spawner.rs +++ b/src/spawner.rs @@ -6,7 +6,12 @@ use specs::saveload::{MarkedBuilder, SimpleMarker}; use crate::random_table::RandomTable; use crate::rect::Rect; -use crate::{AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, DefenseBonus, EntryTrigger, EquipmentSlot, Equippable, Hidden, HungerClock, HungerState, InflictsDamage, Item, MagicMapper, MeleePowerBonus, Monster, Name, Player, Position, ProvidesFood, ProvidesHealing, Ranged, Renderable, SerializeMe, SingleActivation, Viewshed, MAP_WIDTH, MAX_MONSTER, Map, TileType}; +use crate::{ + AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, DefenseBonus, EntryTrigger, + EquipmentSlot, Equippable, Hidden, HungerClock, HungerState, InflictsDamage, Item, MagicMapper, + Map, MeleePowerBonus, Monster, Name, Player, Position, ProvidesFood, ProvidesHealing, Ranged, + Renderable, SerializeMe, SingleActivation, TileType, Viewshed, MAP_WIDTH, MAX_MONSTER, +}; pub fn player(ecs: &mut World, player_x: i32, player_y: i32) -> Entity { ecs.create_entity() @@ -81,55 +86,78 @@ fn monster(ecs: &mut World, x: i32, y: i32, glyph: FontCharType, na } #[allow(clippy::map_entry)] -pub fn spawn_room(ecs: &mut World, room: &Rect, map_depth: i32, map: &Map) { - let spawn_table = room_table(map_depth); - let mut spawn_points: HashMap = HashMap::new(); +pub fn spawn_room(ecs: &mut World, room: &Rect, map_depth: i32) { + let mut possible_targets: Vec = Vec::new(); { - let mut rng = ecs.write_resource::(); - let num_spawns = rng.roll_dice(1, MAX_MONSTER + 3) + (map_depth - 1) - 3; - - for _i in 0..num_spawns { - let mut added = false; - let mut tried = 0; - while !added && tried < 20 { - let x = (room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1))) as usize; - let y = (room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1))) as usize; - let idx = (y * MAP_WIDTH) + x; - if !spawn_points.contains_key(&idx) && map.tiles[idx] != TileType::Wall { - spawn_points.insert(idx, spawn_table.roll(&mut rng)); - added = true; - } else { - tried += 1; + let map = ecs.fetch::(); + for y in room.y1 + 1..room.y2 { + for x in room.x1 + 1..room.x2 { + let idx = map.xy_idx(x, y); + if map.tiles[idx] == TileType::Floor { + possible_targets.push(idx) } } } } - for spawn in spawn_points.iter() { - let x = (*spawn.0 % MAP_WIDTH) as i32; - let y = (*spawn.0 / MAP_WIDTH) as i32; + spawn_region(ecs, &possible_targets, map_depth); +} - match spawn.1.as_ref() { - "Goblin" => goblin(ecs, x, y), - "Orc" => orc(ecs, x, y), - "Health Potion" => health_potion(ecs, x, y), - "Fireball Scroll" => fireball_scroll(ecs, x, y), - "Confusion Scroll" => confusion_scroll(ecs, x, y), - "Magic Missile Scroll" => magic_missile_scroll(ecs, x, y), - "Dagger" => dagger(ecs, x, y), - "Longsword" => longsword(ecs, x, y), - "Shield" => shield(ecs, x, y), - "Tower Shield" => tower_shield(ecs, x, y), - "Helmet" => helmet(ecs, x, y), - "Breastplate" => breastplate(ecs, x, y), - "Leggings" => leggings(ecs, x, y), - "Sabatons" => sabatons(ecs, x, y), - "Rations" => rations(ecs, x, y), - "Magic Mapping Scroll" => magic_mapper_scroll(ecs, x, y), - "Bear Trap" => bear_trap(ecs, x, y), - _ => {} - } +pub(crate) fn spawn_region(ecs: &mut World, area: &[usize], map_depth: i32) { + if let Some(spawn_points) = calculate_spawn_points(ecs, area, map_depth) { + spawn_entities(ecs, spawn_points) + } +} + +fn spawn_entities(ecs: &mut World, spawn_points: HashMap) { + for spawn in spawn_points.iter() { + spawn_entity(ecs, &spawn); + } +} + +fn calculate_spawn_points(ecs: &mut World, area: &[usize], map_depth: i32) -> Option> { + let mut spawn_points: HashMap = HashMap::new(); + let spawn_table = room_table(map_depth); + let mut areas: Vec = Vec::from(area); + let mut rng = ecs.write_resource::(); + + let num_spawns = i32::min(areas.len() as i32, rng.roll_dice(1, MAX_MONSTER + 3)); + if num_spawns == 0 { return None; } + + for _i in 0..num_spawns { + let array_idx = if areas.len() == 1 { 0usize } else { (rng.roll_dice(1, areas.len() as i32 - 1) as usize) }; + let map_idx = areas[array_idx]; + spawn_points.insert(map_idx, spawn_table.roll(&mut rng)); + areas.remove(array_idx); + } + + Some(spawn_points) +} + +fn spawn_entity(ecs: &mut World, spawn: &(&usize, &String)) { + let x = (*spawn.0 % MAP_WIDTH) as i32; + let y = (*spawn.0 / MAP_WIDTH) as i32; + + match spawn.1.as_ref() { + "Goblin" => goblin(ecs, x, y), + "Orc" => orc(ecs, x, y), + "Health Potion" => health_potion(ecs, x, y), + "Fireball Scroll" => fireball_scroll(ecs, x, y), + "Confusion Scroll" => confusion_scroll(ecs, x, y), + "Magic Missile Scroll" => magic_missile_scroll(ecs, x, y), + "Dagger" => dagger(ecs, x, y), + "Longsword" => longsword(ecs, x, y), + "Shield" => shield(ecs, x, y), + "Tower Shield" => tower_shield(ecs, x, y), + "Helmet" => helmet(ecs, x, y), + "Breastplate" => breastplate(ecs, x, y), + "Leggings" => leggings(ecs, x, y), + "Sabatons" => sabatons(ecs, x, y), + "Rations" => rations(ecs, x, y), + "Magic Mapping Scroll" => magic_mapper_scroll(ecs, x, y), + "Bear Trap" => bear_trap(ecs, x, y), + _ => {} } }