src/zones.rs 12.5 K · 375 lines · raw · history

1 use std::collections::HashSet;
2
3 use bevy::prelude::*;
4
5 use crate::{
6 actions::Action,
7 pathfinding::nearest_tile,
8 selection::{Cursor, update_cursor},
9 ui::PointerOverUi,
10 world::{TILE_SIZE, WorldMap},
11 worldgen::WorldGenerated,
12 };
13
14 pub struct ZonesPlugin;
15
16 impl Plugin for ZonesPlugin {
17 fn build(&self, app: &mut App) {
18 app.init_resource::<Zones>()
19 .init_resource::<ZoneTool>()
20 .add_systems(Update, clear_zones.run_if(on_message::<WorldGenerated>))
21 .add_systems(
22 PostUpdate,
23 (zone_tool, draw_zone_preview).chain().after(update_cursor),
24 );
25 }
26 }
27
28 pub const NEW_STOCKPILE_SIZE: u32 = 4;
29 const STOCKPILE_SITE_SEARCH_TILES: usize = 4000;
30 const PREVIEW_ADD_COLOR: Color = Color::srgba(0.4, 0.7, 1.0, 0.9);
31 const PREVIEW_REMOVE_COLOR: Color = Color::srgba(1.0, 0.4, 0.4, 0.9);
32
33 #[derive(Resource, Default, Debug, Clone, PartialEq)]
34 pub struct Zones {
35 stockpile: HashSet<UVec2>,
36 }
37
38 impl Zones {
39 pub fn is_stockpile(&self, tile: UVec2) -> bool {
40 self.stockpile.contains(&tile)
41 }
42
43 pub fn stockpile_tiles(&self) -> impl Iterator<Item = UVec2> + '_ {
44 self.stockpile.iter().copied()
45 }
46
47 pub fn home(&self, fallback: UVec2) -> UVec2 {
48 let centroid = self.stockpile.iter().map(|t| t.as_vec2()).sum::<Vec2>()
49 / self.stockpile.len().max(1) as f32;
50 self.stockpile
51 .iter()
52 .copied()
53 .min_by(|a, b| {
54 a.as_vec2()
55 .distance_squared(centroid)
56 .total_cmp(&b.as_vec2().distance_squared(centroid))
57 .then((a.y, a.x).cmp(&(b.y, b.x)))
58 })
59 .unwrap_or(fallback)
60 }
61
62 pub fn has_stockpile(&self) -> bool {
63 !self.stockpile.is_empty()
64 }
65
66 pub fn empty_stockpile_tiles(&self, occupied: &HashSet<UVec2>) -> usize {
67 self.stockpile.difference(occupied).count()
68 }
69
70 pub fn add_stockpile(&mut self, map: &WorldMap, a: IVec2, b: IVec2) {
71 self.add_tiles(map, rect_tiles(a, b).filter_map(|t| t.try_into().ok()));
72 }
73
74 pub fn add_tiles(&mut self, map: &WorldMap, tiles: impl IntoIterator<Item = UVec2>) {
75 for tile in tiles {
76 if can_zone(map, tile.as_ivec2()) {
77 self.stockpile.insert(tile);
78 }
79 }
80 }
81
82 pub fn remove_stockpile(&mut self, a: IVec2, b: IVec2) {
83 for tile in rect_tiles(a, b) {
84 if tile.x >= 0 && tile.y >= 0 {
85 self.stockpile.remove(&tile.as_uvec2());
86 }
87 }
88 }
89 }
90
91 pub fn plan_expansion(map: &WorldMap, zones: &Zones, count: usize) -> Vec<UVec2> {
92 if zones.stockpile.is_empty() {
93 return Vec::new();
94 }
95 let centroid =
96 zones.stockpile.iter().map(|t| t.as_vec2()).sum::<Vec2>() / zones.stockpile.len() as f32;
97 let preference = |t: UVec2| {
98 (
99 map.plant(t.as_ivec2()).is_some(),
100 t.as_vec2().distance_squared(centroid),
101 t.y,
102 t.x,
103 )
104 };
105 let mut planned: Vec<UVec2> = Vec::new();
106 while planned.len() < count {
107 let taken = |t: UVec2| zones.is_stockpile(t) || planned.contains(&t);
108 let best = zones
109 .stockpile
110 .iter()
111 .chain(planned.iter())
112 .flat_map(|t| {
113 [IVec2::X, IVec2::NEG_X, IVec2::Y, IVec2::NEG_Y].map(|d| t.as_ivec2() + d)
114 })
115 .filter(|&t| can_zone(map, t) && !taken(t.as_uvec2()))
116 .map(|t| t.as_uvec2())
117 .min_by(|&a, &b| {
118 let (ka, kb) = (preference(a), preference(b));
119 ka.0.cmp(&kb.0)
120 .then(ka.1.total_cmp(&kb.1))
121 .then((ka.2, ka.3).cmp(&(kb.2, kb.3)))
122 });
123 match best {
124 Some(tile) => planned.push(tile),
125 None => break,
126 }
127 }
128 planned
129 }
130
131 pub fn can_zone(map: &WorldMap, tile: IVec2) -> bool {
132 map.move_cost(tile).is_some() && !map.get(tile).is_some_and(|t| t.is_water())
133 }
134
135 fn rect_tiles(a: IVec2, b: IVec2) -> impl Iterator<Item = IVec2> {
136 let (min, max) = (a.min(b), a.max(b));
137 (min.y..=max.y).flat_map(move |y| (min.x..=max.x).map(move |x| IVec2::new(x, y)))
138 }
139
140 #[derive(Resource, Default, Debug)]
141 pub struct ZoneTool {
142 pub active: bool,
143 drag_start: Option<UVec2>,
144 }
145
146 fn clear_zones(mut zones: ResMut<Zones>) {
147 *zones = Zones::default();
148 }
149
150 pub fn new_stockpile_tiles(corner: UVec2) -> impl Iterator<Item = UVec2> {
151 (0..NEW_STOCKPILE_SIZE)
152 .flat_map(move |y| (0..NEW_STOCKPILE_SIZE).map(move |x| corner + UVec2::new(x, y)))
153 }
154
155 fn is_open_square(map: &WorldMap, corner: UVec2) -> bool {
156 new_stockpile_tiles(corner)
157 .all(|t| can_zone(map, t.as_ivec2()) && map.plant(t.as_ivec2()).is_none())
158 }
159
160 pub fn find_stockpile_site(map: &WorldMap, near: UVec2) -> Option<UVec2> {
161 nearest_tile(map, near, STOCKPILE_SITE_SEARCH_TILES, |p| {
162 is_open_square(map, p)
163 })
164 .or_else(|| {
165 nearest_tile(map, near, STOCKPILE_SITE_SEARCH_TILES, |p| {
166 can_zone(map, p.as_ivec2())
167 })
168 })
169 }
170
171 fn removing(keys: &ButtonInput<KeyCode>) -> bool {
172 keys.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight])
173 }
174
175 fn zone_tool(
176 mut actions: MessageReader<Action>,
177 keys: Res<ButtonInput<KeyCode>>,
178 buttons: Res<ButtonInput<MouseButton>>,
179 over_ui: Res<PointerOverUi>,
180 cursor: Res<Cursor>,
181 map: Res<WorldMap>,
182 mut tool: ResMut<ZoneTool>,
183 mut zones: ResMut<Zones>,
184 ) {
185 for action in actions.read() {
186 match action {
187 Action::ToggleStockpileTool => tool.active = !tool.active,
188 Action::Cancel => tool.active = false,
189 _ => continue,
190 }
191 tool.drag_start = None;
192 return;
193 }
194 if !tool.active {
195 return;
196 }
197 if buttons.just_pressed(MouseButton::Left) && !over_ui.0 {
198 tool.drag_start = cursor.tile;
199 }
200 if !buttons.just_released(MouseButton::Left) {
201 return;
202 }
203 if let (Some(start), Some(end)) = (tool.drag_start.take(), cursor.tile) {
204 if removing(&keys) {
205 zones.remove_stockpile(start.as_ivec2(), end.as_ivec2());
206 } else {
207 zones.add_stockpile(&map, start.as_ivec2(), end.as_ivec2());
208 }
209 }
210 }
211
212 fn draw_zone_preview(
213 keys: Res<ButtonInput<KeyCode>>,
214 cursor: Res<Cursor>,
215 tool: Res<ZoneTool>,
216 mut gizmos: Gizmos,
217 ) {
218 let (Some(start), Some(end)) = (tool.drag_start, cursor.tile) else {
219 return;
220 };
221 let (min, max) = (start.min(end), start.max(end));
222 let center = (WorldMap::tile_center(min) + WorldMap::tile_center(max)) / 2.0;
223 let size = (max - min + 1).as_vec2() * TILE_SIZE;
224 let color = if removing(&keys) {
225 PREVIEW_REMOVE_COLOR
226 } else {
227 PREVIEW_ADD_COLOR
228 };
229 gizmos.rect_2d(center, size, color);
230 }
231
232 #[cfg(test)]
233 mod tests {
234 use super::*;
235 use crate::world::Terrain;
236
237 #[test]
238 fn stockpiles_only_cover_walkable_dry_land() {
239 let mut map = WorldMap::filled(UVec2::new(4, 1), Terrain::Grass);
240 map.set(UVec2::new(1, 0), Terrain::Stone);
241 map.set(UVec2::new(2, 0), Terrain::ShallowWater);
242 let mut zones = Zones::default();
243 zones.add_stockpile(&map, IVec2::new(3, 0), IVec2::new(-1, 0));
244 let mut tiles: Vec<_> = zones.stockpile_tiles().collect();
245 tiles.sort_by_key(|t| t.x);
246 assert_eq!(tiles, vec![UVec2::new(0, 0), UVec2::new(3, 0)]);
247 }
248
249 #[test]
250 fn expansion_grows_compactly_around_the_stockpile() {
251 let map = WorldMap::filled(UVec2::splat(10), Terrain::Grass);
252 let mut zones = Zones::default();
253 zones.add_stockpile(&map, IVec2::new(4, 4), IVec2::new(5, 5));
254 let plan = plan_expansion(&map, &zones, 8);
255 assert_eq!(plan.len(), 8);
256 assert!(plan.iter().all(|t| !zones.is_stockpile(*t)));
257 let beyond_one_ring = plan_expansion(&map, &zones, 20);
258 assert_eq!(beyond_one_ring.len(), 20);
259 assert!(
260 plan.iter()
261 .all(|t| (3..=6).contains(&t.x) && (3..=6).contains(&t.y))
262 );
263 }
264
265 // Trees can be zoned, but stockpiling on open ground keeps forests intact and avoids
266 // colonists cutting trees just to make room, so expansion only takes trees as a last resort.
267 #[test]
268 fn expansion_prefers_open_ground_over_trees_and_skips_unzonable_tiles() {
269 let mut map = WorldMap::filled(UVec2::splat(10), Terrain::Grass);
270 map.set(UVec2::new(3, 4), Terrain::Stone);
271 map.set_plant(UVec2::new(5, 4), Some(crate::world::Plant::Tree));
272 let mut zones = Zones::default();
273 zones.add_stockpile(&map, IVec2::new(4, 4), IVec2::new(4, 4));
274 let plan = plan_expansion(&map, &zones, 2);
275 assert_eq!(plan.len(), 2);
276 assert!(!plan.contains(&UVec2::new(3, 4)));
277 assert!(!plan.contains(&UVec2::new(5, 4)));
278 }
279
280 #[test]
281 fn no_expansion_without_a_stockpile() {
282 let map = WorldMap::filled(UVec2::splat(10), Terrain::Grass);
283 assert!(plan_expansion(&map, &Zones::default(), 8).is_empty());
284 }
285
286 #[test]
287 fn removing_clears_a_rectangle() {
288 let map = WorldMap::filled(UVec2::new(4, 4), Terrain::Grass);
289 let mut zones = Zones::default();
290 zones.add_stockpile(&map, IVec2::ZERO, IVec2::splat(3));
291 zones.remove_stockpile(IVec2::new(1, 1), IVec2::new(2, 2));
292 assert_eq!(zones.stockpile_tiles().count(), 12);
293 assert!(!zones.is_stockpile(UVec2::new(1, 2)));
294 assert!(zones.is_stockpile(UVec2::new(0, 2)));
295 }
296
297 fn tool_app() -> App {
298 let mut app = App::new();
299 app.insert_resource(WorldMap::filled(UVec2::splat(8), Terrain::Grass))
300 .init_resource::<Zones>()
301 .init_resource::<ButtonInput<KeyCode>>()
302 .init_resource::<ButtonInput<MouseButton>>()
303 .insert_resource(ZoneTool {
304 active: true,
305 drag_start: None,
306 })
307 .init_resource::<Cursor>()
308 .init_resource::<PointerOverUi>()
309 .add_message::<Action>()
310 .add_systems(Update, zone_tool);
311 app
312 }
313
314 fn drag(app: &mut App, from: UVec2, to: UVec2) {
315 app.world_mut().resource_mut::<Cursor>().tile = Some(from);
316 app.world_mut()
317 .resource_mut::<ButtonInput<MouseButton>>()
318 .press(MouseButton::Left);
319 app.update();
320 app.world_mut().resource_mut::<Cursor>().tile = Some(to);
321 let mut buttons = app.world_mut().resource_mut::<ButtonInput<MouseButton>>();
322 buttons.clear();
323 buttons.release(MouseButton::Left);
324 app.update();
325 app.world_mut()
326 .resource_mut::<ButtonInput<MouseButton>>()
327 .clear();
328 }
329
330 #[test]
331 fn dragging_adds_and_shift_dragging_removes() {
332 let mut app = tool_app();
333 drag(&mut app, UVec2::new(1, 1), UVec2::new(3, 2));
334 assert_eq!(app.world().resource::<Zones>().stockpile_tiles().count(), 6);
335 app.world_mut()
336 .resource_mut::<ButtonInput<KeyCode>>()
337 .press(KeyCode::ShiftLeft);
338 drag(&mut app, UVec2::new(3, 2), UVec2::new(3, 1));
339 assert_eq!(app.world().resource::<Zones>().stockpile_tiles().count(), 4);
340 }
341
342 #[test]
343 fn dragging_does_nothing_when_the_tool_is_off() {
344 let mut app = tool_app();
345 app.world_mut().resource_mut::<ZoneTool>().active = false;
346 drag(&mut app, UVec2::new(1, 1), UVec2::new(3, 2));
347 assert_eq!(app.world().resource::<Zones>().stockpile_tiles().count(), 0);
348 }
349
350 #[test]
351 fn new_worlds_start_without_stockpiles() {
352 let map = WorldMap::filled(UVec2::splat(8), Terrain::Grass);
353 let mut app = App::new();
354 app.init_resource::<Zones>()
355 .add_message::<WorldGenerated>()
356 .add_systems(Update, clear_zones.run_if(on_message::<WorldGenerated>));
357 app.world_mut()
358 .resource_mut::<Zones>()
359 .add_stockpile(&map, IVec2::ZERO, IVec2::ONE);
360 app.world_mut().write_message(WorldGenerated);
361 app.update();
362 assert!(!app.world().resource::<Zones>().has_stockpile());
363 }
364
365 #[test]
366 fn new_stockpiles_go_on_the_nearest_fully_open_ground() {
367 let mut map = WorldMap::filled(UVec2::splat(12), Terrain::Grass);
368 for y in 0..12 {
369 map.set_plant(UVec2::new(4, y), Some(crate::world::Plant::Tree));
370 map.set(UVec2::new(7, y), Terrain::DeepWater);
371 }
372 let site = find_stockpile_site(&map, UVec2::new(5, 5)).unwrap();
373 assert!(new_stockpile_tiles(site).all(|t| t.x < 4));
374 }
375 }