src/world.rs 8.6 K · 298 lines · raw · history

1 use bevy::prelude::*;
2
3 pub const TILE_SIZE: f32 = 16.0;
4 pub const MAX_HEIGHT: f32 = 100.0;
5 pub const UPHILL_COST_PER_METER: f32 = 20.0;
6
7 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8 pub enum Terrain {
9 Grass,
10 Soil,
11 Sand,
12 ShallowWater,
13 DeepWater,
14 Stone,
15 IronOre,
16 GoldOre,
17 Gravel,
18 }
19
20 impl Terrain {
21 pub const ALL: [Terrain; 9] = [
22 Terrain::Grass,
23 Terrain::Soil,
24 Terrain::Sand,
25 Terrain::ShallowWater,
26 Terrain::DeepWater,
27 Terrain::Stone,
28 Terrain::IronOre,
29 Terrain::GoldOre,
30 Terrain::Gravel,
31 ];
32
33 pub fn index(self) -> u16 {
34 self as u16
35 }
36
37 pub fn move_cost(self) -> Option<u32> {
38 match self {
39 Terrain::Grass | Terrain::Soil => Some(100),
40 Terrain::Sand | Terrain::Gravel => Some(130),
41 Terrain::ShallowWater => Some(300),
42 Terrain::DeepWater | Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => None,
43 }
44 }
45
46 pub fn is_water(self) -> bool {
47 matches!(self, Terrain::ShallowWater | Terrain::DeepWater)
48 }
49
50 pub fn is_rock(self) -> bool {
51 matches!(self, Terrain::Stone | Terrain::IronOre | Terrain::GoldOre)
52 }
53
54 pub fn color(self) -> Srgba {
55 match self {
56 Terrain::Grass => Srgba::rgb_u8(92, 140, 64),
57 Terrain::Soil => Srgba::rgb_u8(122, 92, 60),
58 Terrain::Sand => Srgba::rgb_u8(214, 196, 140),
59 Terrain::ShallowWater => Srgba::rgb_u8(72, 132, 184),
60 Terrain::DeepWater => Srgba::rgb_u8(36, 76, 140),
61 Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => Srgba::rgb_u8(118, 118, 124),
62 Terrain::Gravel => Srgba::rgb_u8(150, 146, 138),
63 }
64 }
65
66 pub fn speck_color(self) -> Option<Srgba> {
67 match self {
68 Terrain::IronOre => Some(Srgba::rgb_u8(178, 104, 72)),
69 Terrain::GoldOre => Some(Srgba::rgb_u8(236, 196, 60)),
70 _ => None,
71 }
72 }
73 }
74
75 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76 pub enum Plant {
77 Tree,
78 }
79
80 impl Plant {
81 pub const ALL: [Plant; 1] = [Plant::Tree];
82
83 pub fn index(self) -> u16 {
84 self as u16
85 }
86
87 pub fn extra_move_cost(self) -> u32 {
88 match self {
89 Plant::Tree => 100,
90 }
91 }
92 }
93
94 #[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
95 pub struct TilePos(pub UVec2);
96
97 #[derive(Message, Debug, Clone, Copy, PartialEq)]
98 pub struct TileChanged(pub UVec2);
99
100 #[derive(Resource, Clone, Debug)]
101 pub struct WorldMap {
102 pub size: UVec2,
103 tiles: Vec<Terrain>,
104 plants: Vec<Option<Plant>>,
105 heights: Vec<f32>,
106 walls: Vec<bool>,
107 roofs: Vec<bool>,
108 }
109
110 impl WorldMap {
111 pub fn filled(size: UVec2, terrain: Terrain) -> Self {
112 let n = size.element_product() as usize;
113 Self {
114 size,
115 tiles: vec![terrain; n],
116 plants: vec![None; n],
117 heights: vec![0.0; n],
118 walls: vec![false; n],
119 roofs: vec![false; n],
120 }
121 }
122
123 pub fn in_bounds(&self, pos: IVec2) -> bool {
124 pos.x >= 0 && pos.y >= 0 && (pos.x as u32) < self.size.x && (pos.y as u32) < self.size.y
125 }
126
127 fn index(&self, pos: UVec2) -> usize {
128 (pos.y * self.size.x + pos.x) as usize
129 }
130
131 pub fn get(&self, pos: IVec2) -> Option<Terrain> {
132 self.in_bounds(pos)
133 .then(|| self.tiles[self.index(pos.as_uvec2())])
134 }
135
136 pub fn set(&mut self, pos: UVec2, terrain: Terrain) {
137 let i = self.index(pos);
138 self.tiles[i] = terrain;
139 }
140
141 pub fn plant(&self, pos: IVec2) -> Option<Plant> {
142 self.in_bounds(pos)
143 .then(|| self.plants[self.index(pos.as_uvec2())])
144 .flatten()
145 }
146
147 pub fn set_plant(&mut self, pos: UVec2, plant: Option<Plant>) {
148 let i = self.index(pos);
149 self.plants[i] = plant;
150 }
151
152 pub fn height(&self, pos: IVec2) -> Option<f32> {
153 self.in_bounds(pos)
154 .then(|| self.heights[self.index(pos.as_uvec2())])
155 }
156
157 pub fn set_height(&mut self, pos: UVec2, height: f32) {
158 let i = self.index(pos);
159 self.heights[i] = height;
160 }
161
162 pub fn is_wall(&self, pos: IVec2) -> bool {
163 self.in_bounds(pos) && self.walls[self.index(pos.as_uvec2())]
164 }
165
166 pub fn set_wall(&mut self, pos: UVec2, wall: bool) {
167 let i = self.index(pos);
168 self.walls[i] = wall;
169 }
170
171 pub fn is_roofed(&self, pos: IVec2) -> bool {
172 self.in_bounds(pos) && self.roofs[self.index(pos.as_uvec2())]
173 }
174
175 pub fn set_roof(&mut self, pos: UVec2, roof: bool) {
176 let i = self.index(pos);
177 self.roofs[i] = roof;
178 }
179
180 pub fn move_cost(&self, pos: IVec2) -> Option<u32> {
181 if self.is_wall(pos) {
182 return None;
183 }
184 let terrain = self.get(pos)?.move_cost()?;
185 Some(terrain + self.plant(pos).map_or(0, Plant::extra_move_cost))
186 }
187
188 pub fn step_cost(&self, from: IVec2, to: IVec2) -> Option<u32> {
189 let climb = (self.height(to)? - self.height(from)?).max(0.0);
190 Some(self.move_cost(to)? + (climb * UPHILL_COST_PER_METER).round() as u32)
191 }
192
193 pub fn positions(&self) -> impl Iterator<Item = UVec2> + use<> {
194 let size = self.size;
195 (0..size.y).flat_map(move |y| (0..size.x).map(move |x| UVec2::new(x, y)))
196 }
197
198 pub fn world_size(&self) -> Vec2 {
199 self.size.as_vec2() * TILE_SIZE
200 }
201
202 pub fn tile_center(pos: UVec2) -> Vec2 {
203 (pos.as_vec2() + 0.5) * TILE_SIZE
204 }
205
206 pub fn tile_at(&self, world: Vec2) -> Option<UVec2> {
207 let pos = (world / TILE_SIZE).floor().as_ivec2();
208 self.in_bounds(pos).then(|| pos.as_uvec2())
209 }
210 }
211
212 pub fn hash2(x: u32, y: u32) -> u32 {
213 let mut h = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77);
214 h ^= h >> 15;
215 h = h.wrapping_mul(0x2C1B_3C6D);
216 h ^= h >> 12;
217 h = h.wrapping_mul(0x297A_2D39);
218 h ^ (h >> 15)
219 }
220
221 #[cfg(test)]
222 mod tests {
223 use super::*;
224
225 #[test]
226 fn get_out_of_bounds_is_none() {
227 let map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
228 assert_eq!(map.get(IVec2::new(-1, 0)), None);
229 assert_eq!(map.get(IVec2::new(4, 0)), None);
230 assert_eq!(map.get(IVec2::new(0, 3)), None);
231 assert_eq!(map.get(IVec2::new(3, 2)), Some(Terrain::Grass));
232 }
233
234 #[test]
235 fn tiles_are_stored_row_major_from_bottom_left() {
236 let mut map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
237 map.set(UVec2::new(1, 2), Terrain::Stone);
238 assert_eq!(map.tiles[2 * 4 + 1], Terrain::Stone);
239 }
240
241 #[test]
242 fn tile_at_inverts_tile_center() {
243 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
244 for pos in [UVec2::ZERO, UVec2::new(17, 99), map.size - 1] {
245 assert_eq!(map.tile_at(WorldMap::tile_center(pos)), Some(pos));
246 }
247 }
248
249 #[test]
250 fn tile_at_outside_world_is_none() {
251 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
252 assert_eq!(map.tile_at(Vec2::new(-0.1, 0.0)), None);
253 assert_eq!(map.tile_at(map.world_size()), None);
254 }
255
256 #[test]
257 fn trees_slow_movement_but_do_not_block_it() {
258 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
259 let open = map.move_cost(IVec2::ZERO).unwrap();
260 map.set_plant(UVec2::ZERO, Some(Plant::Tree));
261 assert!(map.move_cost(IVec2::ZERO).unwrap() > open);
262 }
263
264 #[test]
265 fn walls_block_movement() {
266 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
267 map.set_wall(UVec2::ZERO, true);
268 assert_eq!(map.move_cost(IVec2::ZERO), None);
269 assert!(map.move_cost(IVec2::X).is_some());
270 }
271
272 #[test]
273 fn walking_uphill_costs_more_than_downhill_or_flat() {
274 let mut map = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
275 map.set_height(UVec2::new(1, 0), 5.0);
276 let (low, high, flat) = (IVec2::new(0, 0), IVec2::new(1, 0), IVec2::new(2, 0));
277 let up = map.step_cost(low, high).unwrap();
278 let down = map.step_cost(high, low).unwrap();
279 assert!(up > down);
280 assert_eq!(down, map.step_cost(low, flat).unwrap());
281 }
282
283 #[test]
284 fn rock_and_water_classification() {
285 assert!(Terrain::IronOre.is_rock() && Terrain::IronOre.move_cost().is_none());
286 assert!(Terrain::ShallowWater.is_water() && !Terrain::ShallowWater.is_rock());
287 }
288
289 #[test]
290 fn terrain_index_matches_position_in_all() {
291 for (i, t) in Terrain::ALL.iter().enumerate() {
292 assert_eq!(t.index() as usize, i);
293 }
294 for (i, p) in Plant::ALL.iter().enumerate() {
295 assert_eq!(p.index() as usize, i);
296 }
297 }
298 }