src/building.rs 13.5 K · 405 lines · raw · history

1 use std::collections::{HashMap, HashSet, VecDeque};
2
3 use bevy::prelude::*;
4
5 use crate::{
6 colonist::Colonist,
7 family::Homes,
8 items::{Item, ItemKind},
9 sim::{SimSystems, SimTick},
10 structures::{Structure, StructureKind},
11 world::{TILE_SIZE, TilePos, WorldMap},
12 worldgen::WorldGenerated,
13 zones::{Zones, can_zone},
14 };
15
16 pub struct BuildingPlugin;
17
18 impl Plugin for BuildingPlugin {
19 fn build(&self, app: &mut App) {
20 app.init_resource::<Blueprints>()
21 .add_systems(
22 Update,
23 (
24 clear_blueprints.run_if(on_message::<WorldGenerated>),
25 draw_blueprints,
26 ),
27 )
28 .add_systems(FixedUpdate, plan_shelter.in_set(SimSystems::Decide));
29 }
30 }
31
32 pub const MAX_ROOM_TILES: usize = 120;
33 const PLAN_INTERVAL_TICKS: u64 = 300;
34 const MAX_ROOM_MARGIN: i32 = 2;
35 const CRAMPED_SIDE_COST: i32 = 3;
36 const WALL_BLUEPRINT_COLOR: Color = Color::srgba(0.5, 0.75, 1.0, 0.8);
37 const DOOR_BLUEPRINT_COLOR: Color = Color::srgba(1.0, 0.8, 0.4, 0.8);
38 const PAVE_BLUEPRINT_COLOR: Color = Color::srgba(0.85, 0.85, 0.85, 0.5);
39 const ROOF_BLUEPRINT_COLOR: Color = Color::srgba(0.8, 0.6, 1.0, 0.35);
40
41 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
42 pub enum BuildKind {
43 Structure(StructureKind),
44 Roof,
45 Pave,
46 }
47
48 impl BuildKind {
49 pub fn cost(self) -> (ItemKind, u32) {
50 match self {
51 BuildKind::Structure(kind) => kind.cost(),
52 BuildKind::Roof => (ItemKind::Wood, 1),
53 BuildKind::Pave => (ItemKind::Stone, 1),
54 }
55 }
56
57 pub fn work(self) -> u32 {
58 match self {
59 BuildKind::Structure(StructureKind::Campfire) => 360,
60 BuildKind::Structure(StructureKind::Torch) => 120,
61 BuildKind::Structure(StructureKind::Bed) => 600,
62 BuildKind::Structure(StructureKind::Wall) => 300,
63 BuildKind::Structure(StructureKind::Door) => 300,
64 BuildKind::Roof => 120,
65 BuildKind::Pave => 120,
66 }
67 }
68
69 pub fn name(self) -> &'static str {
70 match self {
71 BuildKind::Structure(kind) => kind.name(),
72 BuildKind::Roof => "roof",
73 BuildKind::Pave => "paving",
74 }
75 }
76
77 pub fn blocks_tile(self) -> bool {
78 self == BuildKind::Structure(StructureKind::Wall)
79 }
80 }
81
82 #[derive(Resource, Default, Debug, Clone)]
83 pub struct Blueprints(pub HashMap<UVec2, BuildKind>);
84
85 impl Blueprints {
86 pub fn get(&self, tile: UVec2) -> Option<BuildKind> {
87 self.0.get(&tile).copied()
88 }
89
90 pub fn tiles(&self) -> HashSet<UVec2> {
91 self.0.keys().copied().collect()
92 }
93 }
94
95 fn clear_blueprints(mut blueprints: ResMut<Blueprints>) {
96 blueprints.0.clear();
97 }
98
99 pub fn enclosed_room(map: &WorldMap, doors: &HashSet<UVec2>, start: UVec2) -> Option<Vec<UVec2>> {
100 let mut seen = HashSet::from([start]);
101 let mut queue = VecDeque::from([start]);
102 while let Some(tile) = queue.pop_front() {
103 if seen.len() > MAX_ROOM_TILES {
104 return None;
105 }
106 for step in [IVec2::X, IVec2::NEG_X, IVec2::Y, IVec2::NEG_Y] {
107 let next = tile.as_ivec2() + step;
108 if !map.in_bounds(next) {
109 return None;
110 }
111 let next = next.as_uvec2();
112 let barrier = map.is_wall(next.as_ivec2())
113 || doors.contains(&next)
114 || map.get(next.as_ivec2()).is_some_and(|t| t.is_rock());
115 if !barrier && seen.insert(next) {
116 queue.push_back(next);
117 }
118 }
119 }
120 let mut room: Vec<UVec2> = seen.into_iter().collect();
121 room.sort_by_key(|t| (t.y, t.x));
122 Some(room)
123 }
124
125 pub struct ShelterContext<'a> {
126 pub map: &'a WorldMap,
127 pub structures: &'a [(UVec2, StructureKind)],
128 pub items: &'a [UVec2],
129 }
130
131 impl ShelterContext<'_> {
132 fn doors(&self) -> HashSet<UVec2> {
133 self.structures
134 .iter()
135 .filter(|(_, kind)| *kind == StructureKind::Door)
136 .map(|(pos, _)| *pos)
137 .collect()
138 }
139
140 fn wall_buildable(&self, tile: IVec2) -> bool {
141 can_zone(self.map, tile)
142 && self.map.plant(tile).is_none()
143 && !self.items.contains(&tile.as_uvec2())
144 && !self
145 .structures
146 .iter()
147 .any(|(pos, _)| *pos == tile.as_uvec2())
148 }
149
150 fn already_closed(&self, tile: IVec2, doors: &HashSet<UVec2>) -> bool {
151 self.map.is_wall(tile)
152 || doors.contains(&tile.as_uvec2())
153 || self.map.get(tile).is_some_and(|t| t.is_rock())
154 }
155
156 pub fn plan(&self, beds: &[UVec2], toward: UVec2) -> Option<HashMap<UVec2, BuildKind>> {
157 let doors = self.doors();
158 if let Some(&first) = beds.first()
159 && let Some(room) = enclosed_room(self.map, &doors, first)
160 {
161 let roofs: HashMap<UVec2, BuildKind> = room
162 .into_iter()
163 .filter(|t| !self.map.is_roofed(t.as_ivec2()))
164 .map(|t| (t, BuildKind::Roof))
165 .collect();
166 return (!roofs.is_empty()).then_some(roofs);
167 }
168 let min = beds.iter().copied().reduce(|a, b| a.min(b))?.as_ivec2();
169 let max = beds.iter().copied().reduce(|a, b| a.max(b))?.as_ivec2();
170 let margins = 0..=MAX_ROOM_MARGIN;
171 let shapes = margins.clone().flat_map(|l| {
172 let margins = margins.clone();
173 margins.clone().flat_map(move |r| {
174 let margins = margins.clone();
175 margins
176 .clone()
177 .flat_map(move |d| margins.clone().map(move |u| IVec4::new(l, r, d, u)))
178 })
179 });
180 shapes
181 .filter_map(|m| {
182 let lo = min - IVec2::new(m.x, m.z) - 1;
183 let hi = max + IVec2::new(m.y, m.w) + 1;
184 let plan = self.walls_around(lo, hi, toward, &doors)?;
185 let cramped = m.to_array().iter().filter(|&&side| side == 0).count() as i32;
186 let cost = plan.len() as i32 + CRAMPED_SIDE_COST * cramped;
187 Some((cost, m.to_array(), plan))
188 })
189 .min_by_key(|(cost, margins, _)| (*cost, *margins))
190 .map(|(_, _, plan)| plan)
191 }
192
193 fn walls_around(
194 &self,
195 lo: IVec2,
196 hi: IVec2,
197 toward: UVec2,
198 doors: &HashSet<UVec2>,
199 ) -> Option<HashMap<UVec2, BuildKind>> {
200 let ring: Vec<IVec2> = (lo.y..=hi.y)
201 .flat_map(|y| (lo.x..=hi.x).map(move |x| IVec2::new(x, y)))
202 .filter(|t| t.x == lo.x || t.x == hi.x || t.y == lo.y || t.y == hi.y)
203 .collect();
204 let mut plan = HashMap::new();
205 for &tile in &ring {
206 if !self.map.in_bounds(tile) {
207 return None;
208 }
209 if self.already_closed(tile, doors) {
210 continue;
211 }
212 if !self.wall_buildable(tile) {
213 return None;
214 }
215 plan.insert(tile.as_uvec2(), BuildKind::Structure(StructureKind::Wall));
216 }
217 let has_door = ring.iter().any(|t| doors.contains(&t.as_uvec2()));
218 if !has_door {
219 let corner = |t: &UVec2| {
220 let t = t.as_ivec2();
221 (t.x == lo.x || t.x == hi.x) && (t.y == lo.y || t.y == hi.y)
222 };
223 let door = plan.keys().filter(|t| !corner(t)).copied().min_by(|a, b| {
224 a.as_vec2()
225 .distance_squared(toward.as_vec2())
226 .total_cmp(&b.as_vec2().distance_squared(toward.as_vec2()))
227 .then((a.y, a.x).cmp(&(b.y, b.x)))
228 })?;
229 plan.insert(door, BuildKind::Structure(StructureKind::Door));
230 }
231 Some(plan)
232 }
233 }
234
235 pub fn plan_shelter(
236 tick: Res<SimTick>,
237 map: Res<WorldMap>,
238 mut zones: ResMut<Zones>,
239 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
240 items: Query<&TilePos, With<Item>>,
241 mut blueprints: ResMut<Blueprints>,
242 homes: Res<Homes>,
243 ) {
244 let shelter_pending = blueprints.0.values().any(|k| *k != BuildKind::Pave);
245 if !tick.0.is_multiple_of(PLAN_INTERVAL_TICKS) || shelter_pending {
246 return;
247 }
248 let structures: Vec<(UVec2, StructureKind)> =
249 structures.iter().map(|(pos, s)| (pos.0, s.kind)).collect();
250 let beds: Vec<UVec2> = structures
251 .iter()
252 .filter(|(pos, kind)| {
253 *kind == StructureKind::Bed
254 && !map.is_roofed(pos.as_ivec2())
255 && homes.owner(*pos).is_none()
256 })
257 .map(|(pos, _)| *pos)
258 .collect();
259 if beds.is_empty() {
260 return;
261 }
262 let items: Vec<UVec2> = items.iter().map(|pos| pos.0).collect();
263 let ctx = ShelterContext {
264 map: &map,
265 structures: &structures,
266 items: &items,
267 };
268 let toward = structures
269 .iter()
270 .find(|(_, kind)| *kind == StructureKind::Campfire)
271 .map(|(pos, _)| *pos)
272 .unwrap_or_else(|| zones.home(beds[0]));
273 if let Some(plan) = ctx.plan(&beds, toward) {
274 for (tile, kind) in &plan {
275 if *kind != BuildKind::Roof {
276 zones.remove_tile(*tile);
277 }
278 }
279 blueprints.0.extend(plan);
280 }
281 }
282
283 fn draw_blueprints(mut gizmos: Gizmos, blueprints: Res<Blueprints>) {
284 for (tile, kind) in &blueprints.0 {
285 let color = match kind {
286 BuildKind::Structure(StructureKind::Door) => DOOR_BLUEPRINT_COLOR,
287 BuildKind::Roof => ROOF_BLUEPRINT_COLOR,
288 BuildKind::Pave => PAVE_BLUEPRINT_COLOR,
289 _ => WALL_BLUEPRINT_COLOR,
290 };
291 gizmos.rect_2d(
292 WorldMap::tile_center(*tile),
293 Vec2::splat(TILE_SIZE * 0.85),
294 color,
295 );
296 }
297 }
298
299 #[cfg(test)]
300 mod tests {
301 use super::*;
302 use crate::world::Terrain;
303
304 fn ctx<'a>(map: &'a WorldMap, structures: &'a [(UVec2, StructureKind)]) -> ShelterContext<'a> {
305 ShelterContext {
306 map,
307 structures,
308 items: &[],
309 }
310 }
311
312 fn count(plan: &HashMap<UVec2, BuildKind>, kind: BuildKind) -> usize {
313 plan.values().filter(|k| **k == kind).count()
314 }
315
316 const WALL: BuildKind = BuildKind::Structure(StructureKind::Wall);
317 const DOOR: BuildKind = BuildKind::Structure(StructureKind::Door);
318
319 #[test]
320 fn shelter_is_a_wall_ring_with_one_door_around_the_beds() {
321 let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
322 let beds = [UVec2::new(10, 10), UVec2::new(11, 10)];
323 let plan = ctx(&map, &[]).plan(&beds, UVec2::new(10, 2)).unwrap();
324 assert_eq!(plan.len(), 6 * 5 - 4 * 3);
325 assert_eq!(count(&plan, DOOR), 1);
326 let door = plan.iter().find(|(_, k)| **k == DOOR).unwrap().0;
327 assert_eq!(door.y, 8);
328 }
329
330 // Mountains are free walls: a shelter dug against a cliff only needs walls on the open sides.
331 #[test]
332 fn rock_counts_as_wall() {
333 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
334 for y in 0..20 {
335 map.set(UVec2::new(12, y), Terrain::Stone);
336 }
337 let plan = ctx(&map, &[])
338 .plan(&[UVec2::new(10, 10)], UVec2::new(10, 2))
339 .unwrap();
340 assert!(plan.keys().all(|t| t.x != 12));
341 assert_eq!(count(&plan, WALL) + count(&plan, DOOR), 16 - 5);
342 }
343
344 #[test]
345 fn shelters_route_around_unbuildable_tiles() {
346 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
347 map.set(UVec2::new(10, 8), Terrain::ShallowWater);
348 let plan = ctx(&map, &[])
349 .plan(&[UVec2::new(10, 10)], UVec2::new(10, 2))
350 .unwrap();
351 assert!(!plan.contains_key(&UVec2::new(10, 8)));
352 assert_eq!(
353 plan.values()
354 .filter(|k| **k == BuildKind::Structure(StructureKind::Door))
355 .count(),
356 1
357 );
358 }
359
360 // Beds often end up right next to the stockpile; walls may take over empty stockpile tiles
361 // (which then stop being storage) instead of the shelter never getting planned at all.
362 #[test]
363 fn walls_may_replace_empty_stockpile_tiles_but_not_stored_items() {
364 let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
365 let mut zones = Zones::default();
366 zones.add_stockpile(&map, IVec2::new(12, 5), IVec2::new(15, 15));
367 let items = [UVec2::new(13, 10)];
368 let ctx = ShelterContext {
369 map: &map,
370 structures: &[],
371 items: &items,
372 };
373 let plan = ctx.plan(&[UVec2::new(11, 10)], UVec2::new(5, 10)).unwrap();
374 assert!(plan.keys().any(|t| zones.is_stockpile(*t)));
375 assert!(!plan.contains_key(&UVec2::new(13, 10)));
376 }
377
378 #[test]
379 fn enclosed_rooms_get_roof_blueprints() {
380 let mut map = WorldMap::filled(UVec2::splat(10), Terrain::Grass);
381 for i in 3..=6 {
382 for t in [
383 UVec2::new(i, 3),
384 UVec2::new(i, 6),
385 UVec2::new(3, i),
386 UVec2::new(6, i),
387 ] {
388 map.set_wall(t, true);
389 }
390 }
391 map.set_wall(UVec2::new(4, 3), false);
392 let structures = [(UVec2::new(4, 3), StructureKind::Door)];
393 let plan = ctx(&map, &structures)
394 .plan(&[UVec2::new(4, 4)], UVec2::ZERO)
395 .unwrap();
396 assert_eq!(plan.len(), 4);
397 assert!(plan.values().all(|k| *k == BuildKind::Roof));
398 }
399
400 #[test]
401 fn open_areas_are_not_rooms() {
402 let map = WorldMap::filled(UVec2::splat(30), Terrain::Grass);
403 assert!(enclosed_room(&map, &HashSet::new(), UVec2::new(15, 15)).is_none());
404 }
405 }