src/world.rs 7.6 K · 265 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 }
107
108 impl WorldMap {
109 pub fn filled(size: UVec2, terrain: Terrain) -> Self {
110 let n = size.element_product() as usize;
111 Self {
112 size,
113 tiles: vec![terrain; n],
114 plants: vec![None; n],
115 heights: vec![0.0; n],
116 }
117 }
118
119 pub fn in_bounds(&self, pos: IVec2) -> bool {
120 pos.x >= 0 && pos.y >= 0 && (pos.x as u32) < self.size.x && (pos.y as u32) < self.size.y
121 }
122
123 fn index(&self, pos: UVec2) -> usize {
124 (pos.y * self.size.x + pos.x) as usize
125 }
126
127 pub fn get(&self, pos: IVec2) -> Option<Terrain> {
128 self.in_bounds(pos)
129 .then(|| self.tiles[self.index(pos.as_uvec2())])
130 }
131
132 pub fn set(&mut self, pos: UVec2, terrain: Terrain) {
133 let i = self.index(pos);
134 self.tiles[i] = terrain;
135 }
136
137 pub fn plant(&self, pos: IVec2) -> Option<Plant> {
138 self.in_bounds(pos)
139 .then(|| self.plants[self.index(pos.as_uvec2())])
140 .flatten()
141 }
142
143 pub fn set_plant(&mut self, pos: UVec2, plant: Option<Plant>) {
144 let i = self.index(pos);
145 self.plants[i] = plant;
146 }
147
148 pub fn height(&self, pos: IVec2) -> Option<f32> {
149 self.in_bounds(pos)
150 .then(|| self.heights[self.index(pos.as_uvec2())])
151 }
152
153 pub fn set_height(&mut self, pos: UVec2, height: f32) {
154 let i = self.index(pos);
155 self.heights[i] = height;
156 }
157
158 pub fn move_cost(&self, pos: IVec2) -> Option<u32> {
159 let terrain = self.get(pos)?.move_cost()?;
160 Some(terrain + self.plant(pos).map_or(0, Plant::extra_move_cost))
161 }
162
163 pub fn step_cost(&self, from: IVec2, to: IVec2) -> Option<u32> {
164 let climb = (self.height(to)? - self.height(from)?).max(0.0);
165 Some(self.move_cost(to)? + (climb * UPHILL_COST_PER_METER).round() as u32)
166 }
167
168 pub fn positions(&self) -> impl Iterator<Item = UVec2> + use<> {
169 let size = self.size;
170 (0..size.y).flat_map(move |y| (0..size.x).map(move |x| UVec2::new(x, y)))
171 }
172
173 pub fn world_size(&self) -> Vec2 {
174 self.size.as_vec2() * TILE_SIZE
175 }
176
177 pub fn tile_center(pos: UVec2) -> Vec2 {
178 (pos.as_vec2() + 0.5) * TILE_SIZE
179 }
180
181 pub fn tile_at(&self, world: Vec2) -> Option<UVec2> {
182 let pos = (world / TILE_SIZE).floor().as_ivec2();
183 self.in_bounds(pos).then(|| pos.as_uvec2())
184 }
185 }
186
187 pub fn hash2(x: u32, y: u32) -> u32 {
188 let mut h = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77);
189 h ^= h >> 15;
190 h = h.wrapping_mul(0x2C1B_3C6D);
191 h ^= h >> 12;
192 h = h.wrapping_mul(0x297A_2D39);
193 h ^ (h >> 15)
194 }
195
196 #[cfg(test)]
197 mod tests {
198 use super::*;
199
200 #[test]
201 fn get_out_of_bounds_is_none() {
202 let map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
203 assert_eq!(map.get(IVec2::new(-1, 0)), None);
204 assert_eq!(map.get(IVec2::new(4, 0)), None);
205 assert_eq!(map.get(IVec2::new(0, 3)), None);
206 assert_eq!(map.get(IVec2::new(3, 2)), Some(Terrain::Grass));
207 }
208
209 #[test]
210 fn tiles_are_stored_row_major_from_bottom_left() {
211 let mut map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
212 map.set(UVec2::new(1, 2), Terrain::Stone);
213 assert_eq!(map.tiles[2 * 4 + 1], Terrain::Stone);
214 }
215
216 #[test]
217 fn tile_at_inverts_tile_center() {
218 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
219 for pos in [UVec2::ZERO, UVec2::new(17, 99), map.size - 1] {
220 assert_eq!(map.tile_at(WorldMap::tile_center(pos)), Some(pos));
221 }
222 }
223
224 #[test]
225 fn tile_at_outside_world_is_none() {
226 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
227 assert_eq!(map.tile_at(Vec2::new(-0.1, 0.0)), None);
228 assert_eq!(map.tile_at(map.world_size()), None);
229 }
230
231 #[test]
232 fn trees_slow_movement_but_do_not_block_it() {
233 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
234 let open = map.move_cost(IVec2::ZERO).unwrap();
235 map.set_plant(UVec2::ZERO, Some(Plant::Tree));
236 assert!(map.move_cost(IVec2::ZERO).unwrap() > open);
237 }
238
239 #[test]
240 fn walking_uphill_costs_more_than_downhill_or_flat() {
241 let mut map = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
242 map.set_height(UVec2::new(1, 0), 5.0);
243 let (low, high, flat) = (IVec2::new(0, 0), IVec2::new(1, 0), IVec2::new(2, 0));
244 let up = map.step_cost(low, high).unwrap();
245 let down = map.step_cost(high, low).unwrap();
246 assert!(up > down);
247 assert_eq!(down, map.step_cost(low, flat).unwrap());
248 }
249
250 #[test]
251 fn rock_and_water_classification() {
252 assert!(Terrain::IronOre.is_rock() && Terrain::IronOre.move_cost().is_none());
253 assert!(Terrain::ShallowWater.is_water() && !Terrain::ShallowWater.is_rock());
254 }
255
256 #[test]
257 fn terrain_index_matches_position_in_all() {
258 for (i, t) in Terrain::ALL.iter().enumerate() {
259 assert_eq!(t.index() as usize, i);
260 }
261 for (i, p) in Plant::ALL.iter().enumerate() {
262 assert_eq!(p.index() as usize, i);
263 }
264 }
265 }