src/world.rs 15.7 K · 520 lines · raw · history

1 use serde::{Deserialize, Serialize};
2 use std::collections::HashSet;
3
4 use bevy::prelude::*;
5
6 pub const MIN_WEAR: f32 = 0.05;
7 pub const TILE_SIZE: f32 = 16.0;
8 pub const MAX_HEIGHT: f32 = 100.0;
9 pub const UPHILL_COST_PER_METER: f32 = 20.0;
10 pub const CHEAPEST_MOVE_COST: u32 = 60;
11
12 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13 pub enum Terrain {
14 Grass,
15 Soil,
16 Sand,
17 ShallowWater,
18 DeepWater,
19 Stone,
20 IronOre,
21 GoldOre,
22 Gravel,
23 Path,
24 Paved,
25 WoodFloor,
26 }
27
28 impl Terrain {
29 pub const ALL: [Terrain; 12] = [
30 Terrain::Grass,
31 Terrain::Soil,
32 Terrain::Sand,
33 Terrain::ShallowWater,
34 Terrain::DeepWater,
35 Terrain::Stone,
36 Terrain::IronOre,
37 Terrain::GoldOre,
38 Terrain::Gravel,
39 Terrain::Path,
40 Terrain::Paved,
41 Terrain::WoodFloor,
42 ];
43
44 pub fn index(self) -> u16 {
45 self as u16
46 }
47
48 pub fn move_cost(self) -> Option<u32> {
49 match self {
50 Terrain::Paved | Terrain::WoodFloor => Some(CHEAPEST_MOVE_COST),
51 Terrain::Path => Some(80),
52 Terrain::Grass | Terrain::Soil => Some(100),
53 Terrain::Sand | Terrain::Gravel => Some(130),
54 Terrain::ShallowWater => Some(300),
55 Terrain::DeepWater | Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => None,
56 }
57 }
58
59 pub fn is_water(self) -> bool {
60 matches!(self, Terrain::ShallowWater | Terrain::DeepWater)
61 }
62
63 pub fn is_rock(self) -> bool {
64 matches!(self, Terrain::Stone | Terrain::IronOre | Terrain::GoldOre)
65 }
66
67 pub fn color(self) -> Srgba {
68 match self {
69 Terrain::Grass => Srgba::rgb_u8(92, 140, 64),
70 Terrain::Soil => Srgba::rgb_u8(122, 92, 60),
71 Terrain::Sand => Srgba::rgb_u8(214, 196, 140),
72 Terrain::ShallowWater => Srgba::rgb_u8(72, 132, 184),
73 Terrain::DeepWater => Srgba::rgb_u8(36, 76, 140),
74 Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => Srgba::rgb_u8(118, 118, 124),
75 Terrain::Gravel => Srgba::rgb_u8(150, 146, 138),
76 Terrain::Path => Srgba::rgb_u8(160, 128, 86),
77 Terrain::Paved => Srgba::rgb_u8(168, 164, 156),
78 Terrain::WoodFloor => Srgba::rgb_u8(150, 108, 66),
79 }
80 }
81
82 pub fn speck_color(self) -> Option<Srgba> {
83 match self {
84 Terrain::IronOre => Some(Srgba::rgb_u8(178, 104, 72)),
85 Terrain::GoldOre => Some(Srgba::rgb_u8(236, 196, 60)),
86 Terrain::Path => Some(Srgba::rgb_u8(130, 104, 70)),
87 _ => None,
88 }
89 }
90 }
91
92 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
93 pub enum Plant {
94 Tree,
95 BerryBush,
96 Crop,
97 }
98
99 impl Plant {
100 pub const ALL: [Plant; 3] = [Plant::Tree, Plant::BerryBush, Plant::Crop];
101
102 pub fn extra_move_cost(self) -> u32 {
103 match self {
104 Plant::Tree => 100,
105 Plant::BerryBush => 60,
106 Plant::Crop => 30,
107 }
108 }
109
110 pub fn ripening_ticks(self) -> Option<f32> {
111 let days = match self {
112 Plant::Tree => return None,
113 Plant::BerryBush => 2.0,
114 Plant::Crop => 1.5,
115 };
116 Some(days * 24.0 * crate::sim::TICKS_PER_HOUR as f32)
117 }
118
119 pub fn is_ripe(self, growth: f32) -> bool {
120 self.ripening_ticks().is_some() && growth >= 1.0
121 }
122 }
123
124 #[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
125 pub struct TilePos(pub UVec2);
126
127 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
128 pub struct MapLayers {
129 size: UVec2,
130 terrain: Vec<(u8, u32)>,
131 plants: Vec<(u8, u32)>,
132 walls: Vec<(u8, u32)>,
133 roofs: Vec<(u8, u32)>,
134 growth: Vec<(u32, f32)>,
135 wear: Vec<(u32, f32)>,
136 }
137
138 fn run_length(values: impl Iterator<Item = u8>) -> Vec<(u8, u32)> {
139 let mut runs: Vec<(u8, u32)> = Vec::new();
140 for v in values {
141 match runs.last_mut() {
142 Some((last, count)) if *last == v => *count += 1,
143 _ => runs.push((v, 1)),
144 }
145 }
146 runs
147 }
148
149 #[derive(Message, Debug, Clone, Copy, PartialEq)]
150 pub struct TileChanged(pub UVec2);
151
152 #[derive(Resource, Clone, Debug)]
153 pub struct WorldMap {
154 pub size: UVec2,
155 tiles: Vec<Terrain>,
156 plants: Vec<Option<Plant>>,
157 heights: Vec<f32>,
158 walls: Vec<bool>,
159 roofs: Vec<bool>,
160 growth: Vec<f32>,
161 wear: Vec<f32>,
162 worn: HashSet<UVec2>,
163 growing: HashSet<UVec2>,
164 shape_version: u64,
165 }
166
167 impl WorldMap {
168 pub fn filled(size: UVec2, terrain: Terrain) -> Self {
169 let n = size.element_product() as usize;
170 Self {
171 size,
172 tiles: vec![terrain; n],
173 plants: vec![None; n],
174 heights: vec![0.0; n],
175 walls: vec![false; n],
176 roofs: vec![false; n],
177 growth: vec![0.0; n],
178 wear: vec![0.0; n],
179 worn: HashSet::new(),
180 growing: HashSet::new(),
181 shape_version: 0,
182 }
183 }
184
185 pub fn in_bounds(&self, pos: IVec2) -> bool {
186 pos.x >= 0 && pos.y >= 0 && (pos.x as u32) < self.size.x && (pos.y as u32) < self.size.y
187 }
188
189 fn index(&self, pos: UVec2) -> usize {
190 (pos.y * self.size.x + pos.x) as usize
191 }
192
193 pub fn get(&self, pos: IVec2) -> Option<Terrain> {
194 self.in_bounds(pos)
195 .then(|| self.tiles[self.index(pos.as_uvec2())])
196 }
197
198 pub fn set(&mut self, pos: UVec2, terrain: Terrain) {
199 let i = self.index(pos);
200 self.tiles[i] = terrain;
201 }
202
203 pub fn plant(&self, pos: IVec2) -> Option<Plant> {
204 self.in_bounds(pos)
205 .then(|| self.plants[self.index(pos.as_uvec2())])
206 .flatten()
207 }
208
209 pub fn set_plant(&mut self, pos: UVec2, plant: Option<Plant>) {
210 let i = self.index(pos);
211 self.plants[i] = plant;
212 if plant.is_some_and(|p| p.ripening_ticks().is_some()) {
213 self.growing.insert(pos);
214 } else {
215 self.growing.remove(&pos);
216 }
217 }
218
219 pub fn growing_plants(&self) -> Vec<UVec2> {
220 let mut tiles: Vec<UVec2> = self.growing.iter().copied().collect();
221 tiles.sort_by_key(|t| (t.y, t.x));
222 tiles
223 }
224
225 pub fn height(&self, pos: IVec2) -> Option<f32> {
226 self.in_bounds(pos)
227 .then(|| self.heights[self.index(pos.as_uvec2())])
228 }
229
230 pub fn set_height(&mut self, pos: UVec2, height: f32) {
231 let i = self.index(pos);
232 self.heights[i] = height;
233 }
234
235 pub fn is_wall(&self, pos: IVec2) -> bool {
236 self.in_bounds(pos) && self.walls[self.index(pos.as_uvec2())]
237 }
238
239 pub fn set_wall(&mut self, pos: UVec2, wall: bool) {
240 let i = self.index(pos);
241 if self.walls[i] != wall {
242 self.walls[i] = wall;
243 self.shape_version += 1;
244 }
245 }
246
247 pub fn growth(&self, pos: IVec2) -> f32 {
248 if self.in_bounds(pos) {
249 self.growth[self.index(pos.as_uvec2())]
250 } else {
251 0.0
252 }
253 }
254
255 pub fn set_growth(&mut self, pos: UVec2, growth: f32) {
256 let i = self.index(pos);
257 self.growth[i] = growth.clamp(0.0, 1.0);
258 }
259
260 pub fn wear(&self, pos: IVec2) -> f32 {
261 if self.in_bounds(pos) {
262 self.wear[self.index(pos.as_uvec2())]
263 } else {
264 0.0
265 }
266 }
267
268 pub fn set_wear(&mut self, pos: UVec2, wear: f32) {
269 let i = self.index(pos);
270 let wear = if wear < MIN_WEAR { 0.0 } else { wear };
271 self.wear[i] = wear;
272 if wear > 0.0 {
273 self.worn.insert(pos);
274 } else {
275 self.worn.remove(&pos);
276 }
277 }
278
279 pub fn layers(&self) -> MapLayers {
280 let sparse = |values: &[f32]| {
281 values
282 .iter()
283 .enumerate()
284 .filter(|(_, v)| **v != 0.0)
285 .map(|(i, v)| (i as u32, *v))
286 .collect()
287 };
288 MapLayers {
289 size: self.size,
290 terrain: run_length(self.tiles.iter().map(|t| t.index() as u8)),
291 plants: run_length(self.plants.iter().map(|p| p.map_or(0, |p| p as u8 + 1))),
292 walls: run_length(self.walls.iter().map(|&w| w as u8)),
293 roofs: run_length(self.roofs.iter().map(|&r| r as u8)),
294 growth: sparse(&self.growth),
295 wear: sparse(&self.wear),
296 }
297 }
298
299 pub fn restore(&mut self, layers: &MapLayers) -> Result<(), String> {
300 let n = self.tiles.len();
301 let unpacked = |runs: &[(u8, u32)]| {
302 let values: Vec<u8> = runs
303 .iter()
304 .flat_map(|&(v, count)| std::iter::repeat_n(v, count as usize))
305 .collect();
306 if values.len() == n {
307 Ok(values)
308 } else {
309 Err("map layer has the wrong size".to_string())
310 }
311 };
312 if layers.size != self.size {
313 return Err("map size differs".into());
314 }
315 let terrain = unpacked(&layers.terrain)?;
316 let plants = unpacked(&layers.plants)?;
317 let walls = unpacked(&layers.walls)?;
318 let roofs = unpacked(&layers.roofs)?;
319 for (i, pos) in self.positions().enumerate() {
320 let terrain = Terrain::ALL
321 .get(terrain[i] as usize)
322 .ok_or("unknown terrain")?;
323 self.set(pos, *terrain);
324 let plant = match plants[i] {
325 0 => None,
326 p => Some(*Plant::ALL.get(p as usize - 1).ok_or("unknown plant")?),
327 };
328 self.set_plant(pos, plant);
329 self.set_wall(pos, walls[i] != 0);
330 self.set_roof(pos, roofs[i] != 0);
331 self.set_growth(pos, 0.0);
332 self.set_wear(pos, 0.0);
333 }
334 let width = self.size.x;
335 let at = |i: u32| UVec2::new(i % width, i / width);
336 for &(i, growth) in &layers.growth {
337 self.set_growth(at(i), growth);
338 }
339 for &(i, wear) in &layers.wear {
340 self.set_wear(at(i), wear);
341 }
342 Ok(())
343 }
344
345 pub fn worn_tiles(&self) -> Vec<UVec2> {
346 let mut tiles: Vec<UVec2> = self.worn.iter().copied().collect();
347 tiles.sort_by_key(|t| (t.y, t.x));
348 tiles
349 }
350
351 pub fn ripe_plant(&self, pos: IVec2) -> Option<Plant> {
352 self.plant(pos).filter(|p| p.is_ripe(self.growth(pos)))
353 }
354
355 pub fn is_roofed(&self, pos: IVec2) -> bool {
356 self.in_bounds(pos) && self.roofs[self.index(pos.as_uvec2())]
357 }
358
359 pub fn set_roof(&mut self, pos: UVec2, roof: bool) {
360 let i = self.index(pos);
361 if self.roofs[i] != roof {
362 self.roofs[i] = roof;
363 self.shape_version += 1;
364 }
365 }
366
367 pub fn shape_version(&self) -> u64 {
368 self.shape_version
369 }
370
371 pub fn move_cost(&self, pos: IVec2) -> Option<u32> {
372 if self.is_wall(pos) {
373 return None;
374 }
375 let terrain = self.get(pos)?.move_cost()?;
376 Some(terrain + self.plant(pos).map_or(0, Plant::extra_move_cost))
377 }
378
379 pub fn step_cost(&self, from: IVec2, to: IVec2) -> Option<u32> {
380 let climb = (self.height(to)? - self.height(from)?).max(0.0);
381 Some(self.move_cost(to)? + (climb * UPHILL_COST_PER_METER).round() as u32)
382 }
383
384 pub fn positions(&self) -> impl Iterator<Item = UVec2> + use<> {
385 let size = self.size;
386 (0..size.y).flat_map(move |y| (0..size.x).map(move |x| UVec2::new(x, y)))
387 }
388
389 pub fn world_size(&self) -> Vec2 {
390 self.size.as_vec2() * TILE_SIZE
391 }
392
393 pub fn tile_center(pos: UVec2) -> Vec2 {
394 (pos.as_vec2() + 0.5) * TILE_SIZE
395 }
396
397 pub fn tile_at(&self, world: Vec2) -> Option<UVec2> {
398 let pos = (world / TILE_SIZE).floor().as_ivec2();
399 self.in_bounds(pos).then(|| pos.as_uvec2())
400 }
401 }
402
403 pub fn hash2(x: u32, y: u32) -> u32 {
404 let mut h = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77);
405 h ^= h >> 15;
406 h = h.wrapping_mul(0x2C1B_3C6D);
407 h ^= h >> 12;
408 h = h.wrapping_mul(0x297A_2D39);
409 h ^ (h >> 15)
410 }
411
412 #[cfg(test)]
413 mod tests {
414 use super::*;
415
416 // Growth runs ten times a game hour; it visits only tracked growing plants because a
417 // full-map pass that often dominated frame time at high speeds.
418 #[test]
419 fn only_ripening_plants_are_tracked_as_growing() {
420 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
421 map.set_plant(UVec2::new(1, 1), Some(Plant::Tree));
422 map.set_plant(UVec2::new(2, 2), Some(Plant::BerryBush));
423 map.set_plant(UVec2::new(3, 3), Some(Plant::Crop));
424 assert_eq!(
425 map.growing_plants(),
426 vec![UVec2::new(2, 2), UVec2::new(3, 3)]
427 );
428 map.set_plant(UVec2::new(2, 2), None);
429 assert_eq!(map.growing_plants(), vec![UVec2::new(3, 3)]);
430 }
431
432 #[test]
433 fn get_out_of_bounds_is_none() {
434 let map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
435 assert_eq!(map.get(IVec2::new(-1, 0)), None);
436 assert_eq!(map.get(IVec2::new(4, 0)), None);
437 assert_eq!(map.get(IVec2::new(0, 3)), None);
438 assert_eq!(map.get(IVec2::new(3, 2)), Some(Terrain::Grass));
439 }
440
441 #[test]
442 fn tiles_are_stored_row_major_from_bottom_left() {
443 let mut map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
444 map.set(UVec2::new(1, 2), Terrain::Stone);
445 assert_eq!(map.tiles[2 * 4 + 1], Terrain::Stone);
446 }
447
448 #[test]
449 fn tile_at_inverts_tile_center() {
450 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
451 for pos in [UVec2::ZERO, UVec2::new(17, 99), map.size - 1] {
452 assert_eq!(map.tile_at(WorldMap::tile_center(pos)), Some(pos));
453 }
454 }
455
456 #[test]
457 fn tile_at_outside_world_is_none() {
458 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
459 assert_eq!(map.tile_at(Vec2::new(-0.1, 0.0)), None);
460 assert_eq!(map.tile_at(map.world_size()), None);
461 }
462
463 #[test]
464 fn trees_slow_movement_but_do_not_block_it() {
465 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
466 let open = map.move_cost(IVec2::ZERO).unwrap();
467 map.set_plant(UVec2::ZERO, Some(Plant::Tree));
468 assert!(map.move_cost(IVec2::ZERO).unwrap() > open);
469 }
470
471 #[test]
472 fn bushes_and_crops_ripen_but_trees_do_not() {
473 assert!(Plant::BerryBush.is_ripe(1.0));
474 assert!(!Plant::Crop.is_ripe(0.9));
475 assert!(!Plant::Tree.is_ripe(1.0));
476 }
477
478 // A* uses CHEAPEST_MOVE_COST in its distance estimate; if any terrain were cheaper the
479 // estimate would overshoot and colonists could take needlessly long routes.
480 #[test]
481 fn no_terrain_is_cheaper_than_the_pathfinding_estimate() {
482 for terrain in Terrain::ALL {
483 if let Some(cost) = terrain.move_cost() {
484 assert!(cost >= CHEAPEST_MOVE_COST, "{terrain:?}");
485 }
486 }
487 }
488
489 #[test]
490 fn walls_block_movement() {
491 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
492 map.set_wall(UVec2::ZERO, true);
493 assert_eq!(map.move_cost(IVec2::ZERO), None);
494 assert!(map.move_cost(IVec2::X).is_some());
495 }
496
497 #[test]
498 fn walking_uphill_costs_more_than_downhill_or_flat() {
499 let mut map = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
500 map.set_height(UVec2::new(1, 0), 5.0);
501 let (low, high, flat) = (IVec2::new(0, 0), IVec2::new(1, 0), IVec2::new(2, 0));
502 let up = map.step_cost(low, high).unwrap();
503 let down = map.step_cost(high, low).unwrap();
504 assert!(up > down);
505 assert_eq!(down, map.step_cost(low, flat).unwrap());
506 }
507
508 #[test]
509 fn rock_and_water_classification() {
510 assert!(Terrain::IronOre.is_rock() && Terrain::IronOre.move_cost().is_none());
511 assert!(Terrain::ShallowWater.is_water() && !Terrain::ShallowWater.is_rock());
512 }
513
514 #[test]
515 fn terrain_index_matches_position_in_all() {
516 for (i, t) in Terrain::ALL.iter().enumerate() {
517 assert_eq!(t.index() as usize, i);
518 }
519 }
520 }