+use {point, time_scope};
+use common::Point2D;
+use super::{Grid, Level};
+use noise::{NoiseFn, OpenSimplex, Seedable};
+use rand::Rng;
+
+////////// LEVEL GENERATOR /////////////////////////////////////////////////////
+
+#[derive(Default)]
+pub struct LevelGenerator {
+ pub seed: u32,
+ pub iterations: u8,
+}
+
+impl LevelGenerator {
+ pub fn new(seed: u32, iterations: u8) -> Self{
+ LevelGenerator { seed, iterations }
+ }
+
+ pub fn generate(&self) -> Level {
+ time_scope!("grid generation");
+
+ 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
+// self.simplex_noise(&mut grid);
+ self.random_noise(&mut grid);
+
+ // smooth with cellular automata
+ self.smooth(&mut grid);
+// grid.smooth_until_equilibrium(&mut grid);
+
+ // increase resolution
+ for _i in 0..1 {
+ grid = self.subdivide(&mut grid);
+ self.smooth(&mut grid);
+// self.smooth_until_equilibrium(&mut grid);
+ }
+
+ self.filter_regions(&mut grid);
+
+ let walls = self.find_walls(&grid);
+ Level {
+ gravity: point!(0.0, 0.1),
+ grid,
+ walls,
+ }
+ }
+
+ #[allow(dead_code)]
+ fn simplex_noise(&self, grid: &mut Grid) {
+ let noise = OpenSimplex::new().set_seed(self.seed);
+ self.set_each(grid, |x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
+ }
+
+ #[allow(dead_code)]
+ fn random_noise(&self, grid: &mut Grid) {
+ let mut rng: rand::prelude::StdRng = rand::SeedableRng::seed_from_u64(self.seed as u64);
+ let noise = OpenSimplex::new().set_seed(self.seed);
+ self.set_each(grid, |_x, _y| rng.gen_range(0, 100) > (45 + (150.0 * noise.get([_x as f64 / 40.0, _y as f64 / 10.0])) as usize), 1); // more horizontal platforms
+ // let w = self.width as f64;
+ // self.set_each(|_x, _y| rng.gen_range(0, 100) > (45 + ((15 * _x) as f64 / w) as usize), 1); // opens up to the right
+ }
+
+ #[allow(dead_code)]
+ fn smooth(&self, grid: &mut Grid) {
+ let distance = 1;
+ for _i in 0..self.iterations {
+ let mut next = vec!(vec!(true; grid.height); grid.width);
+ for x in distance..(grid.width - distance) {
+ for y in distance..(grid.height - distance) {
+ match self.neighbours(&grid.cells, x, y, distance) {
+ n if n < 4 => next[x][y] = false,
+ n if n > 4 => next[x][y] = true,
+ _ => next[x][y] = grid.cells[x][y]
+ }
+ }
+ }
+ if grid.cells == next {
+ break; // exit early
+ } else {
+ grid.cells = next;
+ }
+ }
+ }
+
+ #[allow(dead_code)]
+ fn smooth_until_equilibrium(&self, grid: &mut Grid) {
+ let distance = 1;
+ let mut count = 0;
+ loop {
+ count += 1;
+ let mut next = vec!(vec!(true; grid.height); grid.width);
+ for x in distance..(grid.width - distance) {
+ for y in distance..(grid.height - distance) {
+ match self.neighbours(&grid.cells, x, y, distance) {
+ n if n < 4 => next[x][y] = false,
+ n if n > 4 => next[x][y] = true,
+ _ => next[x][y] = grid.cells[x][y]
+ };
+ }
+ }
+ if grid.cells == next {
+ break;
+ } else {
+ grid.cells = next;
+ }
+ }
+ println!("{} iterations needed", count);
+ }
+
+ fn neighbours(&self, 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>(&self, grid: &mut Grid, mut func: F, walls: usize) {
+ for x in walls..(grid.width - walls) {
+ for y in walls..(grid.height - walls) {
+ grid.cells[x][y] = func(x, y);
+ }
+ }
+ }
+
+ fn subdivide(&self, grid: &mut Grid) -> Grid {
+ let (width, height) = (grid.width * 2, grid.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] = grid.cells[x / 2][y / 2];
+ }
+ }
+ Grid {
+ cell_size: grid.cell_size / 2,
+ width,
+ height,
+ cells
+ }
+ }
+
+ fn find_regions(&self, grid: &Grid) -> Vec<Region> {
+ time_scope!("finding all regions");
+ let mut regions = vec!();
+ let mut marked = vec!(vec!(false; grid.height); grid.width);
+ for x in 0..grid.width {
+ for y in 0..grid.height {
+ if !marked[x][y] {
+ regions.push(self.get_region_at_point(grid, x, y, &mut marked));
+ }
+ }
+ }
+ regions
+ }
+
+ fn get_region_at_point(&self, grid: &Grid, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
+ let value = grid.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 < grid.width as isize && ip.1 >= 0 && ip.1 < grid.height as isize {
+ let up = (ip.0 as usize, ip.1 as usize);
+ if grid.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(&self, grid: &mut Grid, region: &Region) {
+ for c in ®ion.cells {
+ grid.cells[c.0][c.1] = !region.value;
+ }
+ }
+
+ fn filter_regions(&self, grid: &mut Grid) {
+ let min_wall_size = 0.0015;
+ println!("grid size: ({}, {}) = {} cells", grid.width, grid.height, grid.width * grid.height);
+ println!("min wall size: {}", (grid.width * grid.height) as f64 * min_wall_size);
+
+ // delete all smaller wall regions
+ for r in self.find_regions(grid).iter().filter(|r| r.value) {
+ let percent = r.cells.len() as f64 / (grid.width * grid.height) as f64;
+ if percent < min_wall_size {
+ // println!("delete wall region of size {}", r.cells.len());
+ self.delete_region(grid, r);
+ }
+ }
+
+ // delete all rooms but the largest
+ let regions = self.find_regions(grid); // 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(grid, rooms.pop().unwrap());
+ }
+ }
+
+ fn find_walls(&self, grid: &Grid) -> Vec<Vec<Point2D<isize>>> {
+ let mut walls = vec!();
+ for r in self.find_regions(&grid) {
+ if r.value {
+ let mut outline = r.outline(grid.cell_size);
+ for i in 2..(outline.len() - 2) {
+// outline[i] = (outline[i - 1] + outline[i] + outline[i + 1]) / 3;
+ outline[i] = (outline[i - 2] + outline[i - 1] + outline[i] + outline[i + 1] + outline[i + 2]) / 5;
+ }
+ walls.push(outline);
+ }
+ }
+ walls
+ }
+}
+
+////////// REGION //////////////////////////////////////////////////////////////
+
+struct Region {
+ value: bool,
+ cells: Vec<(usize, usize)>,
+}
+
+impl Region {
+ fn enclosing_rect(&self) -> (usize, usize, usize, usize) {
+ let mut min = (usize::MAX, usize::MAX);
+ let mut max = (0, 0);
+ for c in &self.cells {
+ if c.0 < min.0 { min.0 = c.0; }
+ else if c.0 > max.0 { max.0 = c.0; }
+ if c.1 < min.1 { min.1 = c.1; }
+ else if c.1 > max.1 { max.1 = c.1; }
+ }
+ (min.0, min.1, 1 + max.0 - min.0, 1 + max.1 - min.1)
+ }
+
+ pub fn outline(&self, scale: usize) -> Vec<Point2D<isize>> {
+ let rect = self.enclosing_rect();
+ let (ox, oy, w, h) = rect;
+ let grid = self.grid(&rect);
+ let mut marked = vec!(vec!(false; h); w);
+ let mut outline = vec!();
+ let mut directions = vec!((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)); // 8 directions rotating right from starting direction right
+
+ let mut p = self.find_first_point_of_outline(&rect, &grid);
+ marked[p.x as usize][p.y as usize] = true;
+ loop {
+ outline.push((p + (ox as isize, oy as isize)) * scale as isize);
+ self.find_next_point_of_outline(&grid, &mut p, &mut directions);
+ if marked[p.x as usize][p.y as usize] {
+ // we're back at the beginning
+ break;
+ }
+ marked[p.x as usize][p.y as usize] = true;
+ }
+
+ outline
+ }
+
+ #[allow(dead_code)]
+ fn print_grid(&self, grid: &Vec<Vec<bool>>) {
+ let w = grid.len();
+ let h = grid[0].len();
+ let mut g = vec!(vec!(false; w); h);
+ for x in 0..w {
+ for y in 0..h {
+ g[y][x] = grid[x][y];
+ }
+ }
+ println!("grid {} x {}", w, h);
+ print!(" ");
+ for n in 0..w {
+ print!("{}", n % 10);
+ }
+ println!();
+ for (n, row) in g.iter().enumerate() {
+ print!("{:>3}|", n);
+ for col in row {
+ print!("{}", if *col { "#" } else { " " });
+ }
+ println!("|");
+ }
+ }
+
+ fn grid(&self, rect: &(usize, usize, usize, usize)) -> Vec<Vec<bool>> {
+ let (x, y, w, h) = rect;
+ let mut grid = vec!(vec!(false; *h); *w);
+ for c in &self.cells {
+ grid[c.0 - x][c.1 - y] = true;
+ }
+ grid
+ }
+
+ fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> Point2D<isize> {
+ let (ox, oy, w, h) = rect;
+ let is_outer_wall = (ox, oy) == (&0, &0); // we know this is always the outer wall of the level
+ for x in 0..*w {
+ for y in 0..*h {
+ if is_outer_wall && !grid[x][y] {
+ return point!(x as isize, y as isize - 1); // one step back because we're not on a wall tile
+ }
+ else if !is_outer_wall && grid[x][y] {
+ return point!(x as isize, y as isize);
+ }
+ }
+ }
+ panic!("no wall found!");
+ }
+
+ fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: &mut Point2D<isize>, directions: &mut Vec<(isize, isize)>) {
+ directions.rotate_left(2);
+ loop {
+ let d = directions[0];
+ if self.check(*p + d, grid) {
+ *p += d;
+ break;
+ }
+ directions.rotate_right(1);
+ }
+ }
+
+ fn check(&self, p: Point2D<isize>, grid: &Vec<Vec<bool>>) -> bool {
+ if p.x < 0 || p.x >= grid.len() as isize || p.y < 0 || p.y >= grid[0].len() as isize {
+ false
+ } else {
+ grid[p.x as usize][p.y as usize]
+ }
+ }
+}