Reorganized mod common and added a smart scope timer
[kaka/rust-sdl-test.git] / src / core / level.rs
1 use common::Point2D;
2 use ::{point, time_scope};
3 use core::render::Renderer;
4 use noise::{NoiseFn, OpenSimplex, Seedable};
5 use rand::Rng;
6 use sprites::SpriteManager;
7
8 ////////// LEVEL ///////////////////////////////////////////////////////////////
9
10 #[derive(Default)]
11 pub struct Level {
12     pub gravity: Point2D<f64>,
13     pub grid: Grid,
14     iterations: u8,
15 }
16
17 impl Level {
18     pub fn new(gravity: Point2D<f64>) -> Self {
19         Level { gravity, grid: Grid::generate(10), iterations: 10 }
20     }
21
22     pub fn regenerate(&mut self) {
23         self.grid = Grid::generate(self.iterations);
24     }
25
26     pub fn increase_iteration(&mut self) {
27         self.iterations += 1;
28         self.regenerate();
29         println!("iterate {} time(s)", self.iterations);
30     }
31
32     pub fn decrease_iteration(&mut self) {
33         self.iterations -= 1;
34         self.regenerate();
35         println!("iterate {} time(s)", self.iterations);
36     }
37
38     pub fn filter_regions(&mut self) {
39         self.grid.filter_regions();
40     }
41
42     pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager) {
43         renderer.canvas().set_draw_color((64, 64, 64));
44         let size = self.grid.cell_size;
45         for x in 0..self.grid.width {
46             for y in 0..self.grid.height {
47                 if self.grid.cells[x][y] {
48                     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();
49                 }
50             }
51         }
52     }
53 }
54
55 ////////// GRID ////////////////////////////////////////////////////////////////
56
57 #[derive(Default)]
58 pub struct Grid {
59     pub width: usize,
60     pub height: usize,
61     pub cell_size: usize,
62     pub cells: Vec<Vec<bool>>,
63 }
64
65 impl Grid {
66     fn generate(iterations: u8) -> Grid {
67         time_scope!("grid generation");
68
69         let cell_size = 20;
70         let (width, height) = (2560 / cell_size, 1440 / cell_size);
71
72         let mut grid = Grid {
73             cell_size,
74             width,
75             height,
76             cells: vec!(vec!(true; height); width),
77         };
78
79         // start with some noise
80 //      grid.simplex_noise();
81         grid.random_noise();
82
83         // smooth with cellular automata
84         grid.smooth(iterations);
85 //      grid.smooth_until_equilibrium();
86
87         // increase resolution
88         for _i in 0..1 {
89             grid = grid.subdivide();
90             grid.smooth(iterations);
91         }
92
93         grid
94     }
95
96     #[allow(dead_code)]
97     fn simplex_noise(&mut self) {
98         let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
99         self.set_each(|x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
100     }
101
102     #[allow(dead_code)]
103     fn random_noise(&mut self) {
104         let mut rng = rand::thread_rng();
105         let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
106         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
107         // let w = self.width as f64;
108         // self.set_each(|_x, _y| rng.gen_range(0, 100) > (45 + ((15 * _x) as f64 / w) as usize), 1); // opens up to the right
109     }
110
111     #[allow(dead_code)]
112     fn smooth(&mut self, iterations: u8) {
113         let distance = 1;
114         for _i in 0..iterations {
115             let mut next = vec!(vec!(true; self.height); self.width);
116             for x in distance..(self.width - distance) {
117                 for y in distance..(self.height - distance) {
118                     match Grid::neighbours(&self.cells, x, y, distance) {
119                         n if n < 4 => next[x][y] = false,
120                         n if n > 4 => next[x][y] = true,
121                         _ => next[x][y] = self.cells[x][y]
122                     }
123                 }
124             }
125             if self.cells == next {
126                 break; // exit early
127             } else {
128                 self.cells = next;
129             }
130         }
131     }
132
133     #[allow(dead_code)]
134     fn smooth_until_equilibrium(&mut self) {
135         let distance = 1;
136         let mut count = 0;
137         loop {
138             count += 1;
139             let mut next = vec!(vec!(true; self.height); self.width);
140             for x in distance..(self.width - distance) {
141                 for y in distance..(self.height - distance) {
142                     match Grid::neighbours(&self.cells, x, y, distance) {
143                         n if n < 4 => next[x][y] = false,
144                         n if n > 4 => next[x][y] = true,
145                         _ => next[x][y] = self.cells[x][y]
146                     };
147                 }
148             }
149             if self.cells == next {
150                 break;
151             } else {
152                 self.cells = next;
153             }
154         }
155         println!("{} iterations needed", count);
156     }
157
158     fn neighbours(grid: &Vec<Vec<bool>>, px: usize, py: usize, distance: usize) -> u8 {
159         let mut count = 0;
160         for x in (px - distance)..=(px + distance) {
161             for y in (py - distance)..=(py + distance) {
162                 if !(x == px && y == py) && grid[x][y] {
163                     count += 1;
164                 }
165             }
166         }
167         count
168     }
169
170     fn set_each<F: FnMut(usize, usize) -> bool>(&mut self, mut func: F, walls: usize) {
171         for x in walls..(self.width - walls) {
172             for y in walls..(self.height - walls) {
173                 self.cells[x][y] = func(x, y);
174             }
175         }
176     }
177
178     fn subdivide(&mut self) -> Grid {
179         let (width, height) = (self.width * 2, self.height * 2);
180         let mut cells = vec!(vec!(true; height); width);
181         for x in 1..(width - 1) {
182             for y in 1..(height - 1) {
183                 cells[x][y] = self.cells[x / 2][y / 2];
184             }
185         }
186         Grid {
187             cell_size: self.cell_size / 2,
188             width,
189             height,
190             cells
191         }
192     }
193
194     fn find_regions(&self) -> Vec<Region> {
195         time_scope!("finding all regions");
196         let mut regions = vec!();
197         let mut marked = vec!(vec!(false; self.height); self.width);
198         for x in 0..self.width {
199             for y in 0..self.height {
200                 if !marked[x][y] {
201                     regions.push(self.get_region_at_point(x, y, &mut marked));
202                 }
203             }
204         }
205         regions
206     }
207
208     fn get_region_at_point(&self, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
209         let value = self.cells[x][y];
210         let mut cells = vec!();
211         let mut queue = vec!((x, y));
212         marked[x][y] = true;
213
214         while let Some(p) = queue.pop() {
215             cells.push(p);
216             for i in &[(-1, 0), (1, 0), (0, -1), (0, 1)] {
217                 let ip = (p.0 as isize + i.0, p.1 as isize + i.1);
218                 if ip.0 >= 0 && ip.0 < self.width as isize && ip.1 >= 0 && ip.1 < self.height as isize {
219                     let up = (ip.0 as usize, ip.1 as usize);
220                     if self.cells[up.0][up.1] == value && !marked[up.0][up.1] {
221                         marked[up.0][up.1] = true;
222                         queue.push(up);
223                     }
224                 }
225             }
226         }
227
228         Region { value, cells }
229     }
230
231     fn delete_region(&mut self, region: &Region) {
232         for c in &region.cells {
233             self.cells[c.0][c.1] = !region.value;
234         }
235     }
236
237     pub fn filter_regions(&mut self) {
238         let min_wall_size = 0.0015;
239         println!("grid size: ({}, {}) = {} cells", self.width, self.height, self.width * self.height);
240         println!("min wall size: {}", (self.width * self.height) as f64 * min_wall_size);
241
242         // delete all smaller wall regions
243         for r in self.find_regions().iter().filter(|r| r.value) {
244             let percent = r.cells.len() as f64 / (self.width * self.height) as f64;
245             if percent < min_wall_size {
246                 println!("delete wall region of size {}", r.cells.len());
247                 self.delete_region(r);
248             }
249         }
250
251         // delete all rooms but the largest
252         let regions = self.find_regions(); // check again, because if a removed room contains a removed wall, the removed wall will become a room
253         let mut rooms: Vec<&Region> = regions.iter().filter(|r| !r.value).collect();
254         rooms.sort_by_key(|r| r.cells.len());
255         rooms.reverse();
256         while rooms.len() > 1 {
257             self.delete_region(rooms.pop().unwrap());
258         }
259     }
260 }
261
262 ////////// REGION //////////////////////////////////////////////////////////////
263
264 struct Region {
265     value: bool,
266     cells: Vec<(usize, usize)>,
267 }