forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

evac.rs377 lines, 12.4 KiBHistoryRawDownload
1//! Evacuation: a losing front sector threatens a nearby factory, farm or city.
2//! The player rails its crates to the rear with one drag. When the crates are
3//! out, the site is dismantled and rebuilt at the destination. When the clock
4//! runs out, the site is captured. A front that recovers cancels the threat.
5
6use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, TAU};
7
8use bevy::prelude::*;
9use bevy::time::{Real, Time};
10
11use crate::front::front_hour_system;
12use crate::map::WorldText;
13use crate::model::{
14 CarKind, Evac, HourTick, LocoKind, Network, NodeId, NodeKind, Notify, Outcome, TrackSeg, node,
15};
16
17/// A front at or below this line threatens buildings within `EVAC_RANGE`.
18const THREAT_LINE: f32 = -0.4;
19/// The threat lifts once the threatening front recovers above this line.
20const SAFE_LINE: f32 = -0.2;
21const EVAC_RANGE: f32 = 350.0;
22const EVAC_HOURS: u32 = 120;
23const EVAC_CRATES: u32 = 6;
24/// An evacuation destination lies at least this far west of the building.
25const REAR_GAP: f32 = 150.0;
26/// Distance from the destination to the rebuilt site, and the clearance it needs.
27const REBUILD_OFFSET: f32 = 45.0;
28const REBUILD_CLEAR: f32 = 35.0;
29
30const CRATE_FILL: Color = Color::srgb(0.55, 0.36, 0.16);
31const CRATE_EDGE: Color = Color::srgb(0.22, 0.15, 0.09);
32const ALARM: Color = Color::srgb(0.78, 0.12, 0.10);
33const AMBER: Color = Color::srgb(1.0, 0.70, 0.10);
34const CAPTION_SIZE: f32 = 15.0;
35
36pub struct EvacPlugin;
37
38impl Plugin for EvacPlugin {
39 fn build(&self, app: &mut App) {
40 app.add_systems(Update, evac_hour_system.after(front_hour_system))
41 .add_systems(Update, (sync_captions, draw_evac).chain());
42 }
43}
44
45/// Checks that `to` can take the crates of the evacuating building `from`.
46pub fn check_dest(net: &Network, from: NodeId, to: NodeId) -> Result<(), String> {
47 let a = &net.nodes[from.0];
48 let b = &net.nodes[to.0];
49 let Some(evac) = a.evac else {
50 return Err(format!("{} is not evacuating", a.name));
51 };
52 if b.kind == NodeKind::Front {
53 return Err("Not a rear site".to_string());
54 }
55 if b.captured {
56 return Err(format!("{} is captured", b.name));
57 }
58 if a.pos.x - b.pos.x < REAR_GAP {
59 return Err("Too close to the front".to_string());
60 }
61 if let Some(old) = evac.dest
62 && old != to
63 && evac.delivered > 0
64 {
65 return Err("Crates already delivered".to_string());
66 }
67 Ok(())
68}
69
70/// The train that carries crates: a Light loco with three Flat cars.
71pub fn evac_consist() -> (LocoKind, Vec<CarKind>) {
72 (LocoKind::Light, vec![CarKind::Flat; 3])
73}
74
75/// True when an evacuation already threatens the spot `at`.
76fn in_reach(net: &Network, at: Vec2) -> bool {
77 net.nodes
78 .iter()
79 .any(|n| n.evac.is_some() && n.pos.distance(at) <= EVAC_RANGE)
80}
81
82/// Founds a replacement of `kind` next to `dest`, linked to it by a short track.
83/// Its output is the share of crates that arrived.
84fn found_rebuild(net: &mut Network, name: &str, kind: NodeKind, dest: NodeId, delivered: u32) {
85 let center = net.nodes[dest.0].pos;
86 let dirs: Vec<Vec2> = (0..8)
87 .map(|k| Vec2::from_angle(k as f32 * FRAC_PI_4))
88 .collect();
89 let dir = dirs
90 .iter()
91 .copied()
92 .find(|d| {
93 let at = center + *d * REBUILD_OFFSET;
94 net.nodes
95 .iter()
96 .all(|n| n.pos.distance(at) >= REBUILD_CLEAR)
97 })
98 .unwrap_or(Vec2::X);
99 let pos = center + dir * REBUILD_OFFSET;
100 let mut site = node(&format!("{name} II"), kind, pos.x, pos.y, [0.0; 4]);
101 site.output = delivered as f32 / EVAC_CRATES as f32;
102 net.nodes.push(site);
103 net.tracks.push(TrackSeg {
104 a: dest,
105 b: NodeId(net.nodes.len() - 1),
106 length: REBUILD_OFFSET,
107 condition: 1.0,
108 });
109}
110
111/// Starts new threats and advances every evacuation one game hour.
112/// Returns the news lines.
113pub(crate) fn step_evacuations(net: &mut Network) -> Vec<String> {
114 let mut news = Vec::new();
115
116 let fronts: Vec<(usize, Vec2, f32)> = net
117 .nodes
118 .iter()
119 .enumerate()
120 .filter_map(|(i, n)| n.front.map(|f| (i, n.pos, f.line)))
121 .collect();
122 for (fi, fpos, line) in fronts {
123 if line > THREAT_LINE || in_reach(net, fpos) {
124 continue;
125 }
126 let target = net
127 .nodes
128 .iter()
129 .enumerate()
130 .filter(|(_, n)| {
131 matches!(n.kind, NodeKind::Factory | NodeKind::Farm | NodeKind::City)
132 && !n.captured
133 && n.evac.is_none()
134 })
135 .map(|(i, n)| (i, n.pos.distance(fpos)))
136 .filter(|(_, d)| *d <= EVAC_RANGE)
137 .min_by(|a, b| a.1.total_cmp(&b.1));
138 if let Some((i, _)) = target {
139 let site = &mut net.nodes[i];
140 site.evac = Some(Evac {
141 hours_left: EVAC_HOURS,
142 crates_left: EVAC_CRATES,
143 dest: None,
144 delivered: 0,
145 threat: fi,
146 });
147 news.push(format!("{} threatened!", site.name));
148 }
149 }
150
151 for i in 0..net.nodes.len() {
152 let Some(mut evac) = net.nodes[i].evac else {
153 continue;
154 };
155 let name = net.nodes[i].name.clone();
156 let kind = net.nodes[i].kind;
157 let threat_line = net
158 .nodes
159 .get(evac.threat)
160 .and_then(|n| n.front)
161 .map_or(-1.0, |f| f.line);
162
163 // The front held: the site keeps what crates it still has.
164 if threat_line > SAFE_LINE {
165 net.nodes[i].evac = None;
166 net.nodes[i].output = evac.crates_left as f32 / EVAC_CRATES as f32;
167 news.push(format!("{name} is safe"));
168 if let Some(dest) = evac.dest
169 && evac.delivered > 0
170 {
171 found_rebuild(net, &name, kind, dest, evac.delivered);
172 }
173 continue;
174 }
175
176 // Every crate got out: the old site was dismantled and is lost.
177 if evac.delivered >= EVAC_CRATES {
178 net.nodes[i].evac = None;
179 net.capture(i);
180 news.push(format!("{name} saved"));
181 if let Some(dest) = evac.dest {
182 found_rebuild(net, &name, kind, dest, evac.delivered);
183 }
184 continue;
185 }
186
187 // The deadline passed: the site is overrun.
188 evac.hours_left = evac.hours_left.saturating_sub(1);
189 if evac.hours_left == 0 {
190 net.nodes[i].evac = None;
191 net.capture(i);
192 news.push(format!("{name} lost!"));
193 if let Some(dest) = evac.dest {
194 found_rebuild(net, &name, kind, dest, evac.delivered);
195 }
196 continue;
197 }
198 net.nodes[i].evac = Some(evac);
199 }
200 news
201}
202
203fn evac_hour_system(
204 mut ticks: MessageReader<HourTick>,
205 mut net: ResMut<Network>,
206 outcome: Res<Outcome>,
207 mut notify: MessageWriter<Notify>,
208) {
209 for _ in ticks.read() {
210 if *outcome != Outcome::Ongoing {
211 continue;
212 }
213 for text in step_evacuations(&mut net) {
214 notify.write(Notify(text));
215 }
216 }
217}
218
219/// Marker for the "Drag to evacuate" caption beside a site. Holds the node index.
220#[derive(Component)]
221struct EvacCaption(usize);
222
223/// Keeps one caption per site that still needs a destination.
224fn sync_captions(
225 mut commands: Commands,
226 net: Res<Network>,
227 captions: Query<(Entity, &EvacCaption)>,
228) {
229 let wanted = |i: usize| {
230 net.nodes
231 .get(i)
232 .and_then(|n| n.evac)
233 .is_some_and(|e| e.dest.is_none())
234 };
235 let mut have = vec![false; net.nodes.len()];
236 for (entity, caption) in &captions {
237 if wanted(caption.0) {
238 have[caption.0] = true;
239 } else {
240 commands.entity(entity).despawn();
241 }
242 }
243 for (i, site) in net.nodes.iter().enumerate() {
244 if !wanted(i) || have[i] {
245 continue;
246 }
247 commands.spawn((
248 EvacCaption(i),
249 Text2d::new("Drag to evacuate"),
250 WorldText { size: CAPTION_SIZE },
251 TextColor(ALARM),
252 Transform::from_xyz(site.pos.x - 90.0, site.pos.y - 16.0, 21.0),
253 ));
254 }
255}
256
257/// Crate `k` of a stack sits north-west of its site, each one above the last.
258fn crate_at(pos: Vec2, k: u32) -> Vec2 {
259 pos + Vec2::new(-36.0, 14.0 + k as f32 * 9.0)
260}
261
262fn draw_crate(gizmos: &mut Gizmos, c: Vec2) {
263 gizmos.rect_2d(
264 Isometry2d::from_translation(c),
265 Vec2::new(8.0, 7.0),
266 CRATE_EDGE,
267 );
268 for dy in [-2.0_f32, 0.0, 2.0] {
269 gizmos.line_2d(c + Vec2::new(-3.0, dy), c + Vec2::new(3.0, dy), CRATE_FILL);
270 }
271}
272
273/// A line with a head at `to`.
274fn draw_arrow(gizmos: &mut Gizmos, from: Vec2, to: Vec2, color: Color) {
275 gizmos.line_2d(from, to, color);
276 let dir = (to - from).normalize_or_zero();
277 let side = Vec2::new(-dir.y, dir.x);
278 gizmos.line_2d(to, to - dir * 7.0 + side * 4.0, color);
279 gizmos.line_2d(to, to - dir * 7.0 - side * 4.0, color);
280}
281
282/// Countdown ring around a site: a faint full ring with the time left drawn over it.
283fn draw_countdown(gizmos: &mut Gizmos, pos: Vec2, frac: f32) {
284 const RADIUS: f32 = 34.0;
285 const STEPS: u32 = 48;
286 gizmos.circle_2d(
287 Isometry2d::from_translation(pos),
288 RADIUS,
289 Color::srgba(0.22, 0.15, 0.09, 0.25),
290 );
291 let color = if frac < 0.3 { ALARM } else { AMBER };
292 let sweep = TAU * frac;
293 for dr in [-0.6_f32, 0.0, 0.6] {
294 let pts = (0..=STEPS).map(|k| {
295 let ang = FRAC_PI_2 - sweep * k as f32 / STEPS as f32;
296 pos + Vec2::from_angle(ang) * (RADIUS + dr)
297 });
298 gizmos.linestrip_2d(pts, color);
299 }
300}
301
302/// Everything shown for the evacuations: the flashing site, the countdown, crates on
303/// site, the piles at the destination, the hint to drag, and the threat arrow.
304fn draw_evac(mut gizmos: Gizmos, net: Res<Network>, time: Res<Time<Real>>) {
305 let t = time.elapsed_secs();
306 let blink = 0.5 + 0.5 * (t * 6.0).sin();
307 let pulse = 0.5 + 0.5 * (t * 4.0).sin();
308 for site in &net.nodes {
309 let Some(evac) = site.evac else {
310 continue;
311 };
312 let pos = site.pos;
313 let frac = evac.hours_left as f32 / EVAC_HOURS as f32;
314
315 // Flashing outline around the threatened site.
316 let flash = ALARM.with_alpha(0.35 + 0.65 * blink);
317 gizmos.circle_2d(Isometry2d::from_translation(pos), 26.0, flash);
318 gizmos.circle_2d(Isometry2d::from_translation(pos), 27.0, flash);
319 draw_countdown(&mut gizmos, pos, frac);
320
321 for k in 0..evac.crates_left {
322 draw_crate(&mut gizmos, crate_at(pos, k));
323 }
324 match evac.dest.and_then(|d| net.nodes.get(d.0)) {
325 None => {
326 // Hint pointing to the rear, until a destination is chosen.
327 let hint = ALARM.with_alpha(0.4 + 0.6 * pulse);
328 draw_arrow(
329 &mut gizmos,
330 pos + Vec2::new(-40.0, 0.0),
331 pos + Vec2::new(-110.0, 0.0),
332 hint,
333 );
334 }
335 Some(dest) => {
336 for k in 0..evac.delivered {
337 draw_crate(&mut gizmos, crate_at(dest.pos, k));
338 }
339 }
340 }
341
342 // Threat: an arrow from the threatening front, longer as the deadline nears.
343 if let Some(front) = net.nodes.get(evac.threat) {
344 let east = (front.pos - pos).normalize_or_zero();
345 let progress = 1.0 - frac;
346 let tip = pos + east * 40.0;
347 let tail = pos + east * (60.0 + 70.0 * progress);
348 draw_arrow(&mut gizmos, tail, tip, ALARM.with_alpha(0.5 + 0.5 * blink));
349 }
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn timeout_captures_site_and_rebuilds_with_delivered_share() {
359 let mut net = Network::default();
360 // North Sector (node 9) collapses: Dornmark (node 12) is threatened.
361 net.nodes[9].front.as_mut().unwrap().line = -0.6;
362 step_evacuations(&mut net);
363 assert!(net.nodes[12].evac.is_some());
364
365 // Half the crates reached Feldau (node 7) and the deadline hits.
366 if let Some(e) = net.nodes[12].evac.as_mut() {
367 e.dest = Some(NodeId(7));
368 e.delivered = 3;
369 e.hours_left = 1;
370 }
371 step_evacuations(&mut net);
372 assert!(net.nodes[12].captured);
373 assert!(net.nodes[12].evac.is_none());
374 assert_eq!(net.nodes.len(), 15);
375 assert!((net.nodes[14].output - 0.5).abs() < 1e-6);
376 }
377}