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