Add cellular automata

This commit is contained in:
Kasper Juul Hermansen 2022-01-30 15:50:36 +01:00
parent 5a00ebf1f1
commit d4892e33bd
Signed by: kjuulh
GPG Key ID: 0F95C140730F2F23
9 changed files with 275 additions and 76 deletions

View File

@ -13,12 +13,12 @@
</component>
<component name="ChangeListManager">
<list default="true" id="a9f5cad0-d253-42e8-a38a-89dfec417dbc" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/src/map_builders/bsp/mod.rs" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/map_builders/bsp_interior.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/.gitignore" beforeDir="false" />
<change afterPath="$PROJECT_DIR$/src/map_builders/cellular_automata.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/components.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/components.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/bsp/mod.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/bsp/mod.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/bsp_dungeon.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/bsp_dungeon.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/common.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/common.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/bsp_interior.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/bsp_interior.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/mod.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/mod.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/map_builders/simple_map.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/map_builders/simple_map.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/spawner.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/spawner.rs" afterDir="false" />
@ -49,6 +49,9 @@
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="24PyiDwZbQQQ0gzNvMewyQ4Zryi" />
<component name="ProjectLevelVcsManager">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
@ -64,6 +67,7 @@
<property name="node.js.detected.package.tslint" value="true" />
<property name="node.js.selected.package.eslint" value="(autodetect)" />
<property name="node.js.selected.package.tslint" value="(autodetect)" />
<property name="nodejs_package_manager_path" value="npm" />
<property name="org.rust.cargo.project.model.PROJECT_DISCOVERY" value="true" />
<property name="settings.editor.selected.configurable" value="reference.settingsdialog.project.grazie" />
</component>
@ -78,7 +82,7 @@
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1643546643557</updated>
<workItem from="1643546645546" duration="2136000" />
<workItem from="1643546645546" duration="7299000" />
</task>
<servers />
</component>

View File

@ -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 }
}
}

View File

@ -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);
}
}

View File

@ -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 {
}
}
}

View File

@ -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<Map>,
noise_areas : HashMap<i32, Vec<usize>>
}
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<usize> = 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<Map> {
self.history.clone()
}
fn take_snapshot(&mut self) {
if SHOW_MAPGEN_VISUALIZER {
self.history.push(common::reveal_all(&self.map))
}
}
}

View File

@ -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<dyn MapBuilder> {
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)),

View File

@ -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);
}
}

View File

@ -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,32 +86,56 @@ fn monster<S: ToString>(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<usize, String> = HashMap::new();
pub fn spawn_room(ecs: &mut World, room: &Rect, map_depth: i32) {
let mut possible_targets: Vec<usize> = Vec::new();
{
let map = ecs.fetch::<Map>();
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)
}
}
}
}
spawn_region(ecs, &possible_targets, map_depth);
}
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<usize, String>) {
for spawn in spawn_points.iter() {
spawn_entity(ecs, &spawn);
}
}
fn calculate_spawn_points(ecs: &mut World, area: &[usize], map_depth: i32) -> Option<HashMap<usize, String>> {
let mut spawn_points: HashMap<usize, String> = HashMap::new();
let spawn_table = room_table(map_depth);
let mut areas: Vec<usize> = Vec::from(area);
let mut rng = ecs.write_resource::<RandomNumberGenerator>();
let num_spawns = rng.roll_dice(1, MAX_MONSTER + 3) + (map_depth - 1) - 3;
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 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 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);
}
for spawn in spawn_points.iter() {
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;
@ -130,7 +159,6 @@ pub fn spawn_room(ecs: &mut World, room: &Rect, map_depth: i32, map: &Map) {
"Bear Trap" => bear_trap(ecs, x, y),
_ => {}
}
}
}
pub fn health_potion(ecs: &mut World, x: i32, y: i32) {