Delete smaller wall regions and leave only one room
[kaka/rust-sdl-test.git] / src / core / level.rs
index f0c6c0e..65e74ff 100644 (file)
@@ -34,6 +34,10 @@ impl Level {
        println!("iterate {} time(s)", self.iterations);
     }
 
+    pub fn filter_regions(&mut self) {
+       self.grid.filter_regions();
+    }
+
     pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager) {
        let w = renderer.viewport().0 as i32;
 
@@ -67,59 +71,199 @@ pub struct Grid {
 
 impl Grid {
     fn generate(iterations: u8) -> Grid {
-       let cell_size = 10;
-       let (width, height) = (1280 / cell_size, 600 / cell_size);
-       let mut cells = vec!(vec!(true; height); width);
+       let cell_size = 20;
+       let (width, height) = (2560 / cell_size, 1440 / cell_size);
+
+       let mut grid = Grid {
+           cell_size,
+           width,
+           height,
+           cells: vec!(vec!(true; height); width),
+       };
+
+       // start with some noise
+//     grid.simplex_noise();
+       grid.random_noise();
+
+       // smooth with cellular automata
+       grid.smooth(iterations);
+//     grid.smooth_until_equilibrium();
 
+       // increase resolution
+       for _i in 0..1 {
+           grid = grid.subdivide();
+           grid.smooth(iterations);
+       }
+
+       grid
+    }
+
+    #[allow(dead_code)]
+    fn simplex_noise(&mut self) {
+       use noise::{NoiseFn, OpenSimplex, Seedable};
+       let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
+       self.set_each(|x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
+    }
+
+    #[allow(dead_code)]
+    fn random_noise(&mut self) {
        let mut rng = rand::thread_rng();
+       self.set_each(|_x, _y| rng.gen_range(0, 100) > 55, 1);
+    }
 
-       // randomize
-       for x in 1..(width - 1) {
-           for y in 1..(height - 1) {
-               cells[x][y] = rng.gen_range(0, 100) > 55;
+    #[allow(dead_code)]
+    fn smooth(&mut self, iterations: u8) {
+       let distance = 1;
+       for _i in 0..iterations {
+           let mut next = vec!(vec!(true; self.height); self.width);
+           for x in distance..(self.width - distance) {
+               for y in distance..(self.height - distance) {
+                   match Grid::neighbours(&self.cells, x, y, distance) {
+                       n if n < 4 => next[x][y] = false,
+                       n if n > 4 => next[x][y] = true,
+                       _ => next[x][y] = self.cells[x][y]
+                   }
+               }
+           }
+           if self.cells == next {
+               break; // exit early
+           } else {
+               self.cells = next;
            }
        }
+    }
 
-       // smooth
-       // let mut count = 0;
-       // loop {
-       //     count += 1;
-       //     println!("iteration {}", count);
-       for _i in 0..iterations {
-           let mut next = vec!(vec!(true; height); width);
-           for x in 1..(width - 1) {
-               for y in 1..(height - 1) {
-                   match Grid::neighbours(&cells, x, y) {
+    #[allow(dead_code)]
+    fn smooth_until_equilibrium(&mut self) {
+       let distance = 1;
+       let mut count = 0;
+       loop {
+           count += 1;
+           let mut next = vec!(vec!(true; self.height); self.width);
+           for x in distance..(self.width - distance) {
+               for y in distance..(self.height - distance) {
+                   match Grid::neighbours(&self.cells, x, y, distance) {
                        n if n < 4 => next[x][y] = false,
                        n if n > 4 => next[x][y] = true,
-                       _ => next[x][y] = cells[x][y]
+                       _ => next[x][y] = self.cells[x][y]
                    };
                }
            }
-           if cells == next {
+           if self.cells == next {
                break;
            } else {
-               cells = next;
+               self.cells = next;
            }
        }
+       println!("{} iterations needed", count);
+    }
 
+    fn neighbours(grid: &Vec<Vec<bool>>, px: usize, py: usize, distance: usize) -> u8 {
+       let mut count = 0;
+       for x in (px - distance)..=(px + distance) {
+           for y in (py - distance)..=(py + distance) {
+               if !(x == px && y == py) && grid[x][y] {
+                   count += 1;
+               }
+           }
+       }
+       count
+    }
+
+    fn set_each<F: FnMut(usize, usize) -> bool>(&mut self, mut func: F, walls: usize) {
+       for x in walls..(self.width - walls) {
+           for y in walls..(self.height - walls) {
+               self.cells[x][y] = func(x, y);
+           }
+       }
+    }
+
+    fn subdivide(&mut self) -> Grid {
+       let (width, height) = (self.width * 2, self.height * 2);
+       let mut cells = vec!(vec!(true; height); width);
+       for x in 1..(width - 1) {
+           for y in 1..(height - 1) {
+               cells[x][y] = self.cells[x / 2][y / 2];
+           }
+       }
        Grid {
+           cell_size: self.cell_size / 2,
            width,
            height,
-           cell_size,
            cells
        }
     }
 
-    fn neighbours(grid: &Vec<Vec<bool>>, px: usize, py: usize) -> u8 {
-       let mut count = 0;
-       for x in (px - 1)..=(px + 1) {
-           for y in (py - 1)..=(py + 1) {
-               if !(x == px && y == py) && grid[x][y] {
-                   count += 1;
+    fn find_regions(&self) -> Vec<Region> {
+       let mut regions = vec!();
+       let mut marked = vec!(vec!(false; self.height); self.width);
+       for x in 0..self.width {
+           for y in 0..self.height {
+               if !marked[x][y] {
+                   regions.push(self.get_region_at_point(x, y, &mut marked));
                }
            }
        }
-       count
+       regions
+    }
+
+    fn get_region_at_point(&self, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
+       let value = self.cells[x][y];
+       let mut cells = vec!();
+       let mut queue = vec!((x, y));
+       marked[x][y] = true;
+
+       while let Some(p) = queue.pop() {
+           cells.push(p);
+           for i in &[(-1, 0), (1, 0), (0, -1), (0, 1)] {
+               let ip = (p.0 as isize + i.0, p.1 as isize + i.1);
+               if ip.0 >= 0 && ip.0 < self.width as isize && ip.1 >= 0 && ip.1 < self.height as isize {
+                   let up = (ip.0 as usize, ip.1 as usize);
+                   if self.cells[up.0][up.1] == value && !marked[up.0][up.1] {
+                       marked[up.0][up.1] = true;
+                       queue.push(up);
+                   }
+               }
+           }
+       }
+
+       Region { value, cells }
     }
+
+    fn delete_region(&mut self, region: &Region) {
+       for c in &region.cells {
+           self.cells[c.0][c.1] = !region.value;
+       }
+    }
+
+    pub fn filter_regions(&mut self) {
+       let min_wall_size = 0.0015;
+       println!("grid size: ({}, {}) = {} cells", self.width, self.height, self.width * self.height);
+       println!("min wall size: {}", (self.width * self.height) as f64 * min_wall_size);
+
+       // delete all smaller wall regions
+       for r in self.find_regions().iter().filter(|r| r.value) {
+           let percent = r.cells.len() as f64 / (self.width * self.height) as f64;
+           if percent < min_wall_size {
+               println!("delete wall region of size {}", r.cells.len());
+               self.delete_region(r);
+           }
+       }
+
+       // delete all rooms but the largest
+       let regions = self.find_regions(); // check again, because if a removed room contains a removed wall, the removed wall will become a room
+       let mut rooms: Vec<&Region> = regions.iter().filter(|r| !r.value).collect();
+       rooms.sort_by_key(|r| r.cells.len());
+       rooms.reverse();
+       while rooms.len() > 1 {
+           self.delete_region(rooms.pop().unwrap());
+       }
+    }
+}
+
+////////// REGION //////////////////////////////////////////////////////////////
+
+struct Region {
+    value: bool,
+    cells: Vec<(usize, usize)>,
 }