2 use ::{point, time_scope};
3 use core::render::Renderer;
4 use noise::{NoiseFn, OpenSimplex, Seedable};
6 use sprites::SpriteManager;
8 ////////// LEVEL ///////////////////////////////////////////////////////////////
12 pub gravity: Point2D<f64>,
15 walls: Vec<Vec<Point2D<isize>>>,
19 pub fn new(gravity: Point2D<f64>) -> Self {
20 let mut lvl = Level { gravity, grid: Grid::generate(10), iterations: 10, walls: vec!() };
25 fn generate(&mut self) {
26 self.grid = Grid::generate(self.iterations);
29 pub fn increase_iteration(&mut self) {
32 println!("iterate {} time(s)", self.iterations);
35 pub fn decrease_iteration(&mut self) {
38 println!("iterate {} time(s)", self.iterations);
41 pub fn filter_regions(&mut self) {
42 self.grid.filter_regions();
43 let mut walls = vec!();
44 for mut r in self.grid.find_regions() {
46 let mut outline = r.outline(self.grid.cell_size);
47 for i in 2..(outline.len() - 2) {
48 // outline[i] = (outline[i - 1] + outline[i] + outline[i + 1]) / 3;
49 outline[i] = (outline[i - 2] + outline[i - 1] + outline[i] + outline[i + 1] + outline[i + 2]) / 5;
57 pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager) {
58 renderer.canvas().set_draw_color((64, 64, 64));
59 let size = self.grid.cell_size;
60 for x in 0..self.grid.width {
61 for y in 0..self.grid.height {
62 if self.grid.cells[x][y] {
63 renderer.canvas().fill_rect(sdl2::rect::Rect::new(x as i32 * size as i32, y as i32 * size as i32, size as u32, size as u32)).unwrap();
68 let off = (size / 2) as i32;
69 for wall in &self.walls {
70 for w in wall.windows(2) {
71 renderer.draw_line((w[0].x as i32 + off, w[0].y as i32 + off), (w[1].x as i32 + off, w[1].y as i32 + off), (255, 255, 0));
73 let last = wall.len() - 1;
74 renderer.draw_line((wall[0].x as i32 + off, wall[0].y as i32 + off), (wall[last].x as i32 + off, wall[last].y as i32 + off), (255, 255, 0));
79 ////////// GRID ////////////////////////////////////////////////////////////////
87 pub cells: Vec<Vec<bool>>,
91 fn generate(iterations: u8) -> Grid {
92 time_scope!("grid generation");
95 let (width, height) = (2560 / cell_size, 1440 / cell_size);
101 cells: vec!(vec!(true; height); width),
104 // start with some noise
105 // grid.simplex_noise();
108 // smooth with cellular automata
109 grid.smooth(iterations);
110 // grid.smooth_until_equilibrium();
112 // increase resolution
114 grid = grid.subdivide();
115 grid.smooth(iterations);
122 fn simplex_noise(&mut self) {
123 let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
124 self.set_each(|x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
128 fn random_noise(&mut self) {
129 let mut rng = rand::thread_rng();
130 let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
131 self.set_each(|_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
132 // let w = self.width as f64;
133 // self.set_each(|_x, _y| rng.gen_range(0, 100) > (45 + ((15 * _x) as f64 / w) as usize), 1); // opens up to the right
137 fn smooth(&mut self, iterations: u8) {
139 for _i in 0..iterations {
140 let mut next = vec!(vec!(true; self.height); self.width);
141 for x in distance..(self.width - distance) {
142 for y in distance..(self.height - distance) {
143 match Grid::neighbours(&self.cells, x, y, distance) {
144 n if n < 4 => next[x][y] = false,
145 n if n > 4 => next[x][y] = true,
146 _ => next[x][y] = self.cells[x][y]
150 if self.cells == next {
159 fn smooth_until_equilibrium(&mut self) {
164 let mut next = vec!(vec!(true; self.height); self.width);
165 for x in distance..(self.width - distance) {
166 for y in distance..(self.height - distance) {
167 match Grid::neighbours(&self.cells, x, y, distance) {
168 n if n < 4 => next[x][y] = false,
169 n if n > 4 => next[x][y] = true,
170 _ => next[x][y] = self.cells[x][y]
174 if self.cells == next {
180 println!("{} iterations needed", count);
183 fn neighbours(grid: &Vec<Vec<bool>>, px: usize, py: usize, distance: usize) -> u8 {
185 for x in (px - distance)..=(px + distance) {
186 for y in (py - distance)..=(py + distance) {
187 if !(x == px && y == py) && grid[x][y] {
195 fn set_each<F: FnMut(usize, usize) -> bool>(&mut self, mut func: F, walls: usize) {
196 for x in walls..(self.width - walls) {
197 for y in walls..(self.height - walls) {
198 self.cells[x][y] = func(x, y);
203 fn subdivide(&mut self) -> Grid {
204 let (width, height) = (self.width * 2, self.height * 2);
205 let mut cells = vec!(vec!(true; height); width);
206 for x in 1..(width - 1) {
207 for y in 1..(height - 1) {
208 cells[x][y] = self.cells[x / 2][y / 2];
212 cell_size: self.cell_size / 2,
219 fn find_regions(&self) -> Vec<Region> {
220 time_scope!("finding all regions");
221 let mut regions = vec!();
222 let mut marked = vec!(vec!(false; self.height); self.width);
223 for x in 0..self.width {
224 for y in 0..self.height {
226 regions.push(self.get_region_at_point(x, y, &mut marked));
233 fn get_region_at_point(&self, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
234 let value = self.cells[x][y];
235 let mut cells = vec!();
236 let mut queue = vec!((x, y));
239 while let Some(p) = queue.pop() {
241 for i in &[(-1, 0), (1, 0), (0, -1), (0, 1)] {
242 let ip = (p.0 as isize + i.0, p.1 as isize + i.1);
243 if ip.0 >= 0 && ip.0 < self.width as isize && ip.1 >= 0 && ip.1 < self.height as isize {
244 let up = (ip.0 as usize, ip.1 as usize);
245 if self.cells[up.0][up.1] == value && !marked[up.0][up.1] {
246 marked[up.0][up.1] = true;
253 Region { value, cells }
256 fn delete_region(&mut self, region: &Region) {
257 for c in ®ion.cells {
258 self.cells[c.0][c.1] = !region.value;
262 pub fn filter_regions(&mut self) {
263 let min_wall_size = 0.0015;
264 println!("grid size: ({}, {}) = {} cells", self.width, self.height, self.width * self.height);
265 println!("min wall size: {}", (self.width * self.height) as f64 * min_wall_size);
267 // delete all smaller wall regions
268 for r in self.find_regions().iter().filter(|r| r.value) {
269 let percent = r.cells.len() as f64 / (self.width * self.height) as f64;
270 if percent < min_wall_size {
271 println!("delete wall region of size {}", r.cells.len());
272 self.delete_region(r);
276 // delete all rooms but the largest
277 let regions = self.find_regions(); // check again, because if a removed room contains a removed wall, the removed wall will become a room
278 let mut rooms: Vec<&Region> = regions.iter().filter(|r| !r.value).collect();
279 rooms.sort_by_key(|r| r.cells.len());
281 while rooms.len() > 1 {
282 self.delete_region(rooms.pop().unwrap());
287 ////////// REGION //////////////////////////////////////////////////////////////
291 cells: Vec<(usize, usize)>,
295 fn enclosing_rect(&self) -> (usize, usize, usize, usize) {
296 let mut min = (usize::MAX, usize::MAX);
297 let mut max = (0, 0);
298 for c in &self.cells {
299 if c.0 < min.0 { min.0 = c.0; }
300 else if c.0 > max.0 { max.0 = c.0; }
301 if c.1 < min.1 { min.1 = c.1; }
302 else if c.1 > max.1 { max.1 = c.1; }
304 (min.0, min.1, 1 + max.0 - min.0, 1 + max.1 - min.1)
307 pub fn outline(&mut self, scale: usize) -> Vec<Point2D<isize>> {
308 let rect = self.enclosing_rect();
309 let (ox, oy, w, h) = rect;
310 let grid = self.grid(&rect);
311 let mut marked = vec!(vec!(false; h); w);
312 let mut outline = vec!();
314 let (mut p, mut dir) = self.find_first_point_of_outline(&rect, &grid);
315 // println!("starting at {:?} with dir {:?}", p, dir);
316 marked[p.x as usize][p.y as usize] = true;
318 outline.push((p + (ox as isize, oy as isize)) * scale as isize);
319 let result = self.find_next_point_of_outline(&grid, p, dir);
322 // println!("next at {:?} with dir {:?}", p, dir);
323 if marked[p.x as usize][p.y as usize] {
324 // we're back at the beginning
327 marked[p.x as usize][p.y as usize] = true;
333 fn grid(&self, rect: &(usize, usize, usize, usize)) -> Vec<Vec<bool>> {
334 let (x, y, w, h) = rect;
335 let mut grid = vec!(vec!(false; *h); *w);
336 for c in &self.cells {
337 grid[c.0 - x][c.1 - y] = true;
342 fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> (Point2D<isize>, Point2D<isize>) {
343 let (ox, oy, w, h) = rect;
344 let is_outer_wall = (ox, oy) == (&0, &0); // we know this is always the outer wall of the level
347 if is_outer_wall && !grid[x][y] {
348 return (point!(x as isize, y as isize - 1), point!(0, 1)) // one step back because we're not on a wall tile
350 else if !is_outer_wall && grid[x][y] {
351 return (point!(x as isize, y as isize), point!(1, 0))
355 panic!("no wall found!");
358 fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: Point2D<isize>, dir: Point2D<isize>) -> (Point2D<isize>, Point2D<isize>) {
359 let left = match dir.into() {
366 let right = match dir.into() {
373 if self.check(p + dir, grid) {
374 // println!("{:?} is true", p + dir);
375 if self.check(p + dir + left, grid) {
376 // println!("going left to {:?}", p + dir + left);
377 return (p + dir + left, left.into())
379 return (p + dir, dir)
382 // println!("{:?} is false", p + dir);
383 if self.check(p + dir + right, grid) {
384 // println!("going right to {:?}", p + dir + right);
385 return (p + dir + right, dir)
387 // println!("going right from p to {:?}", p + right);
388 return (p + right, right.into())
393 fn check(&self, p: Point2D<isize>, grid: &Vec<Vec<bool>>) -> bool {
394 if p.x < 0 || p.x >= grid.len() as isize || p.y < 0 || p.y >= grid[0].len() as isize {
397 grid[p.x as usize][p.y as usize]