use crate::config::TerrainConfig;
use crate::error::PcgResult;
use crate::model::geometry::{GridPoint, GridSize};
use crate::model::room::{DoorAnchor, Room};
use crate::model::terrain::{ConnectivitySummary, Grid2D, Terrain, TileKind};
use crate::rng::StableRng;
use super::carve::{extract_room_bounds, init_room_grid};
use super::strategy::TerrainStrategy;
#[non_exhaustive]
pub struct OrganicStrategy;
const CA_ITERATIONS: usize = 4;
const WALL_THRESHOLD: usize = 4;
impl TerrainStrategy for OrganicStrategy {
fn name(&self) -> &str {
"organic"
}
fn generate(
&self,
room: &Room,
anchors: &[DoorAnchor],
config: &TerrainConfig,
rng: &mut StableRng,
) -> PcgResult<Terrain> {
let (bounds, width, height) = extract_room_bounds(room)?;
let mut grid_a = initialize_random_grid(width, height, config.obstacle_density, rng)?;
let mut grid_b = Grid2D::new(width, height, TileKind::Wall)?;
for _ in 0..CA_ITERATIONS {
apply_ca_step_into(&grid_a, &mut grid_b, width, height);
std::mem::swap(&mut grid_a, &mut grid_b);
}
let mut tiles = grid_a;
for y in 0..height as i32 {
for x in 0..width as i32 {
if x == 0 || y == 0 || x == width as i32 - 1 || y == height as i32 - 1 {
tiles.set(x, y, TileKind::Wall);
}
}
}
let doorway_locals = super::carve::mark_doorways(&mut tiles, anchors, &room.id, bounds.min);
for pos in &doorway_locals {
for (dx, dy) in &[(1, 0), (-1, 0), (0, 1), (0, -1)] {
let nx = pos.x + dx;
let ny = pos.y + dy;
if nx > 0
&& nx < width as i32 - 1
&& ny > 0
&& ny < height as i32 - 1
&& tiles.get(nx, ny).copied() == Some(TileKind::Wall)
{
tiles.set(nx, ny, TileKind::Floor);
}
}
}
ensure_organic_connectivity(&mut tiles, &doorway_locals, width, height);
convert_internal_walls_to_obstacles(&mut tiles, width, height);
Ok(Terrain {
room_id: room.id.clone(),
grid_size: GridSize { width, height },
tiles,
reserved_zones: Vec::new(),
connectivity_summary: ConnectivitySummary {
all_doors_connected: false,
walkable_tile_count: 0,
total_tile_count: 0,
connected_region_count: 0,
},
})
}
}
fn initialize_random_grid(
width: u32,
height: u32,
density: f32,
rng: &mut StableRng,
) -> PcgResult<Grid2D<TileKind>> {
let mut tiles = init_room_grid(width, height)?;
let fill_probability = (density * 0.8 + 0.2) as f64;
for y in 1..height as i32 - 1 {
for x in 1..width as i32 - 1 {
if rng.gen_bool_with_probability(fill_probability) {
tiles.set(x, y, TileKind::Wall);
}
}
}
Ok(tiles)
}
fn apply_ca_step_into(src: &Grid2D<TileKind>, dst: &mut Grid2D<TileKind>, width: u32, height: u32) {
for y in 0..height as i32 {
for x in 0..width as i32 {
if x == 0 || y == 0 || x == width as i32 - 1 || y == height as i32 - 1 {
dst.set(x, y, TileKind::Wall);
continue;
}
let wall_count = count_wall_neighbors(src, x, y);
if wall_count >= WALL_THRESHOLD {
dst.set(x, y, TileKind::Wall);
} else {
dst.set(x, y, TileKind::Floor);
}
}
}
}
fn count_wall_neighbors(tiles: &Grid2D<TileKind>, x: i32, y: i32) -> usize {
let mut count = 0;
for dy in -1..=1i32 {
for dx in -1..=1i32 {
if dx == 0 && dy == 0 {
continue;
}
let nx = x + dx;
let ny = y + dy;
match tiles.get(nx, ny).copied() {
Some(TileKind::Wall) | Some(TileKind::Obstacle) | None => {
count += 1;
}
_ => {}
}
}
}
count
}
fn ensure_organic_connectivity(
tiles: &mut Grid2D<TileKind>,
doorways: &[GridPoint],
width: u32,
height: u32,
) {
use std::collections::VecDeque;
if doorways.len() < 2 {
return;
}
let size = (width * height) as usize;
let start = doorways[0];
let mut visited = vec![false; size];
let mut queue = VecDeque::new();
queue.push_back(start);
visited[(start.y as u32 * width + start.x as u32) as usize] = true;
while let Some(current) = queue.pop_front() {
for (dx, dy) in &[(1, 0), (-1, 0), (0, 1), (0, -1)] {
let nx = current.x + dx;
let ny = current.y + dy;
if nx < 0 || ny < 0 || nx >= width as i32 || ny >= height as i32 {
continue;
}
let ni = (ny as u32 * width + nx as u32) as usize;
if visited[ni] {
continue;
}
if let Some(tile) = tiles.get(nx, ny).copied() {
if super::grid::is_walkable(tile) {
visited[ni] = true;
queue.push_back(GridPoint { x: nx, y: ny });
}
}
}
}
let mut bfs_queue = VecDeque::new();
let mut bfs_visited = vec![false; size];
let mut bfs_parent: Vec<Option<GridPoint>> = vec![None; size];
for doorway in doorways.iter().skip(1) {
let di = (doorway.y as u32 * width + doorway.x as u32) as usize;
if visited[di] {
continue;
}
carve_path_to_reachable(
tiles,
*doorway,
&visited,
width,
height,
&mut bfs_queue,
&mut bfs_visited,
&mut bfs_parent,
);
let mut new_queue = VecDeque::new();
new_queue.push_back(*doorway);
if !visited[di] {
visited[di] = true;
}
while let Some(current) = new_queue.pop_front() {
for (dx, dy) in &[(1, 0), (-1, 0), (0, 1), (0, -1)] {
let nx = current.x + dx;
let ny = current.y + dy;
if nx < 0 || ny < 0 || nx >= width as i32 || ny >= height as i32 {
continue;
}
let ni = (ny as u32 * width + nx as u32) as usize;
if visited[ni] {
continue;
}
if let Some(tile) = tiles.get(nx, ny).copied() {
if super::grid::is_walkable(tile) {
visited[ni] = true;
new_queue.push_back(GridPoint { x: nx, y: ny });
}
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn carve_path_to_reachable(
tiles: &mut Grid2D<TileKind>,
start: GridPoint,
reachable: &[bool],
width: u32,
height: u32,
queue: &mut std::collections::VecDeque<GridPoint>,
visited: &mut [bool],
parent: &mut [Option<GridPoint>],
) {
queue.clear();
visited.fill(false);
parent.fill(None);
queue.push_back(start);
visited[(start.y as u32 * width + start.x as u32) as usize] = true;
let mut target = None;
while let Some(current) = queue.pop_front() {
let ci = (current.y as u32 * width + current.x as u32) as usize;
if reachable[ci] && current != start {
target = Some(current);
break;
}
for (dx, dy) in &[(1, 0), (-1, 0), (0, 1), (0, -1)] {
let nx = current.x + dx;
let ny = current.y + dy;
if nx <= 0 || ny <= 0 || nx >= width as i32 - 1 || ny >= height as i32 - 1 {
continue;
}
let ni = (ny as u32 * width + nx as u32) as usize;
if visited[ni] {
continue;
}
visited[ni] = true;
parent[ni] = Some(current);
queue.push_back(GridPoint { x: nx, y: ny });
}
}
if let Some(end) = target {
let mut current = end;
while current != start {
if let Some(tile) = tiles.get(current.x, current.y).copied() {
if tile == TileKind::Wall {
tiles.set(current.x, current.y, TileKind::Floor);
}
}
let ci = (current.y as u32 * width + current.x as u32) as usize;
if let Some(prev) = parent[ci] {
current = prev;
} else {
break;
}
}
}
}
fn convert_internal_walls_to_obstacles(tiles: &mut Grid2D<TileKind>, width: u32, height: u32) {
for y in 1..height as i32 - 1 {
for x in 1..width as i32 - 1 {
if tiles.get(x, y).copied() == Some(TileKind::Wall) {
tiles.set(x, y, TileKind::Obstacle);
}
}
}
}