forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

demo.rs583 lines, 18.5 KiBHistoryRawDownload
1//! Self-playing narrated demo, active only with `--demo`.
2//!
3//! A scripted bot plays the real game. It sets the same `Tool` and writes the
4//! same `NodeClicked` and `TrackClicked` messages a mouse would, and it confirms
5//! routes the way the route editor does. Captions explain each step. With
6//! `--record` the run ends four seconds after the last caption, and the screenshot
7//! recorder in `scenario.rs` writes the frames.
8
9use std::collections::VecDeque;
10
11use bevy::app::AppExit;
12use bevy::ecs::change_detection::Mut;
13use bevy::prelude::*;
14use bevy::time::{Real, Time};
15use bevy::ui::Display;
16
17use crate::audio::SoundEvent;
18use crate::build::track_cost;
19use crate::front::{FrontRuntime, air_raid, reset_game};
20use crate::hud::BOTTOM_H;
21use crate::menu::{Menu, MenuScreen};
22use crate::model::{
23 Network, NodeClicked, NodeId, NodeKind, Notify, REPAIR_COST, Selected, SimClock, Tool,
24 CarKind, LocoKind, TrackClicked, Train, Treasury, consist_cost,
25};
26
27/// Captions stay at least this long (real seconds), longer for longer text.
28const CAPTION_MIN_SECS: f64 = 4.0;
29const CAPTION_SECS_PER_CHAR: f64 = 0.05;
30/// Gap between the subtitle box and the bottom strip.
31const SUBTITLE_GAP: f32 = 12.0;
32/// Side margin of the subtitle box, from the window edge.
33const SUBTITLE_MARGIN: f32 = 16.0;
34/// Real seconds to wait for a natural air raid before forcing one. At 4x a game day
35/// passes in about 3 real seconds, so a long wait lets the unsupplied South Sector collapse.
36const RAID_WAIT_SECS: f64 = 8.0;
37/// Real seconds allowed for a money wait or a budget wait before moving on.
38const WAIT_TIMEOUT_SECS: f64 = 150.0;
39/// One weekly budget, in game hours.
40const WEEK_HOURS: u32 = 24 * 7;
41
42/// Adds the narrated demo bot and its caption box.
43pub struct DemoPlugin {
44 /// End the run when the script ends (used with `--record`).
45 pub exit_when_done: bool,
46}
47
48impl Plugin for DemoPlugin {
49 fn build(&self, app: &mut App) {
50 app.insert_resource(Captions::default())
51 .insert_resource(Script {
52 steps: build_steps(),
53 wait: None,
54 exit_when_done: self.exit_when_done,
55 done: false,
56 })
57 .add_systems(Startup, spawn_subtitle)
58 .add_systems(Update, (advance_captions, update_subtitle).chain())
59 .add_systems(Update, run_script);
60 }
61}
62
63/// Captions waiting to be shown, and the one on screen now.
64#[derive(Resource, Default)]
65struct Captions {
66 queue: VecDeque<String>,
67 current: Option<String>,
68 /// Real seconds when `current` appeared, and how long it stays.
69 shown_at: f64,
70 hold: f64,
71}
72
73impl Captions {
74 fn idle(&self) -> bool {
75 self.queue.is_empty() && self.current.is_none()
76 }
77}
78
79fn hold_secs(text: &str) -> f64 {
80 (text.chars().count() as f64 * CAPTION_SECS_PER_CHAR).max(CAPTION_MIN_SECS)
81}
82
83fn advance_captions(time: Res<Time<Real>>, mut captions: ResMut<Captions>) {
84 let now = time.elapsed_secs_f64();
85 if captions.current.is_some() {
86 if now - captions.shown_at < captions.hold {
87 return;
88 }
89 captions.current = None;
90 }
91 if let Some(next) = captions.queue.pop_front() {
92 captions.hold = hold_secs(&next);
93 captions.shown_at = now;
94 captions.current = Some(next);
95 }
96}
97
98#[derive(Component)]
99struct SubtitleRoot;
100
101#[derive(Component)]
102struct SubtitleText;
103
104/// The caption box sits above the bottom strip, centred, and above the menus.
105fn spawn_subtitle(mut commands: Commands) {
106 commands.spawn((
107 SubtitleRoot,
108 Node {
109 position_type: PositionType::Absolute,
110 left: Val::Px(SUBTITLE_MARGIN),
111 right: Val::Px(SUBTITLE_MARGIN),
112 bottom: Val::Px(BOTTOM_H + SUBTITLE_GAP),
113 justify_content: JustifyContent::Center,
114 display: Display::None,
115 ..default()
116 },
117 GlobalZIndex(300),
118 children![(
119 Node {
120 max_width: Val::Vw(60.0),
121 padding: UiRect::axes(Val::Px(14.0), Val::Px(9.0)),
122 ..default()
123 },
124 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.72)),
125 children![(
126 SubtitleText,
127 Text::new(""),
128 TextFont {
129 font_size: FontSize::Px(22.0),
130 ..default()
131 },
132 TextColor(Color::WHITE),
133 TextLayout::justify(Justify::Center),
134 )],
135 )],
136 ));
137}
138
139fn update_subtitle(
140 captions: Res<Captions>,
141 mut roots: Query<&mut Node, With<SubtitleRoot>>,
142 mut texts: Query<&mut Text, With<SubtitleText>>,
143) {
144 let shown = captions.current.as_deref();
145 let display = if shown.is_some() {
146 Display::Flex
147 } else {
148 Display::None
149 };
150 for mut node in &mut roots {
151 if node.display != display {
152 node.display = display;
153 }
154 }
155 let want = shown.unwrap_or("");
156 for mut text in &mut texts {
157 if text.0 != want {
158 text.0 = want.to_string();
159 }
160 }
161}
162
163type Act = Box<dyn Fn(&mut World) + Send + Sync>;
164type Check = Box<dyn Fn(&World) -> bool + Send + Sync>;
165
166/// One scripted step. The script runs them in order.
167enum Step {
168 /// Queue a caption and wait until it has been read.
169 Say(String),
170 /// Wait this many real seconds.
171 Pause(f64),
172 /// Run game code once.
173 Act(Act),
174 /// Wait until the check passes, or until the timeout (real seconds) runs out.
175 Until(Check, f64),
176}
177
178enum Wait {
179 /// Real time (elapsed seconds) to wait until.
180 Pause(f64),
181 /// Check to pass, and the real time after which the wait ends anyway.
182 Until(Check, f64),
183}
184
185#[derive(Resource)]
186struct Script {
187 steps: VecDeque<Step>,
188 wait: Option<Wait>,
189 exit_when_done: bool,
190 done: bool,
191}
192
193fn act(f: impl Fn(&mut World) + Send + Sync + 'static) -> Step {
194 Step::Act(Box::new(f))
195}
196
197fn until(f: impl Fn(&World) -> bool + Send + Sync + 'static, timeout: f64) -> Step {
198 Step::Until(Box::new(f), timeout)
199}
200
201fn say(text: impl Into<String>) -> Step {
202 Step::Say(text.into())
203}
204
205fn pause(secs: f64) -> Step {
206 Step::Pause(secs)
207}
208
209/// Runs the script. Exclusive, so steps can change any resource and write messages.
210fn run_script(world: &mut World) {
211 let now = world.resource::<Time<Real>>().elapsed_secs_f64();
212 loop {
213 let taken = world.resource_mut::<Script>().wait.take();
214 if let Some(wait) = taken {
215 let ready = match &wait {
216 Wait::Pause(until) => now >= *until,
217 Wait::Until(check, deadline) => now >= *deadline || check(world),
218 };
219 if !ready {
220 world.resource_mut::<Script>().wait = Some(wait);
221 return;
222 }
223 }
224 let Some(step) = world.resource_mut::<Script>().steps.pop_front() else {
225 if !world.resource::<Script>().done {
226 world.resource_mut::<Script>().done = true;
227 if world.resource::<Script>().exit_when_done {
228 world.write_message(AppExit::Success);
229 }
230 }
231 return;
232 };
233 match step {
234 Step::Say(text) => {
235 world.resource_mut::<Captions>().queue.push_back(text);
236 world.resource_mut::<Script>().wait = Some(Wait::Until(
237 Box::new(|w: &World| w.resource::<Captions>().idle()),
238 f64::INFINITY,
239 ));
240 }
241 Step::Pause(secs) => {
242 world.resource_mut::<Script>().wait = Some(Wait::Pause(now + secs));
243 }
244 Step::Act(f) => f(world),
245 Step::Until(check, timeout) => {
246 world.resource_mut::<Script>().wait = Some(Wait::Until(check, now + timeout));
247 }
248 }
249 }
250}
251
252fn node_id(net: &Network, name: &str) -> NodeId {
253 net.nodes
254 .iter()
255 .position(|n| n.name == name)
256 .map(NodeId)
257 .unwrap_or_else(|| panic!("demo: no node named {name}"))
258}
259
260fn money(w: &World) -> i64 {
261 w.resource::<Treasury>().0
262}
263
264fn set_tool(w: &mut World, tool: Tool) {
265 *w.resource_mut::<Tool>() = tool;
266}
267
268fn set_speed(w: &mut World, speed: u32) {
269 w.resource_mut::<SimClock>().speed = speed;
270}
271
272/// Sets the open menu screen. Settings and How to Play return to the main menu.
273fn set_screen(w: &mut World, screen: Option<MenuScreen>) {
274 let mut menu = w.resource_mut::<Menu>();
275 if matches!(screen, Some(MenuScreen::Settings | MenuScreen::HowToPlay)) {
276 menu.return_to = MenuScreen::Main;
277 }
278 menu.screen = screen;
279}
280
281/// Closes the menu and starts a fresh operation, as the New Operation button does.
282fn new_operation(w: &mut World) {
283 set_screen(w, None);
284 reset_game(w);
285}
286
287fn select(w: &mut World, name: &str) {
288 let id = node_id(w.resource::<Network>(), name);
289 w.resource_mut::<Selected>().0 = Some(id);
290}
291
292/// A map click on a named node, exactly as `map.rs` sends it.
293fn click(w: &mut World, name: &str) {
294 let id = node_id(w.resource::<Network>(), name);
295 w.write_message(NodeClicked(id));
296}
297
298/// Sets the load flags of one stop of the route being built.
299fn set_loads(w: &mut World, stop: usize, load: [bool; 4]) {
300 if let Tool::NewRoute { stops, .. } = &mut *w.resource_mut::<Tool>()
301 && let Some(s) = stops.get_mut(stop)
302 {
303 s.load = load;
304 }
305}
306
307/// Confirms the route being built, the same way the route editor's Confirm does.
308fn confirm_route(w: &mut World) {
309 let Tool::NewRoute { loco, cars, stops } = w.resource::<Tool>().clone() else {
310 return;
311 };
312 let cost = consist_cost(loco, &cars);
313 if stops.len() < 2 || money(w) < cost {
314 return;
315 }
316 let names: Vec<String> = {
317 let net = w.resource::<Network>();
318 stops
319 .iter()
320 .map(|s| net.nodes[s.node.0].name.clone())
321 .collect()
322 };
323 w.resource_mut::<Treasury>().0 -= cost;
324 let start = stops[0].node;
325 w.spawn(Train {
326 loco,
327 cars,
328 route: stops,
329 stop_idx: 0,
330 at: start,
331 path: Vec::new(),
332 progress: 0.0,
333 cargo: [0.0; 4],
334 dwell: 0.0,
335 stalled: false,
336 crates: 0,
337 });
338 w.write_message(SoundEvent::TrainDeparts);
339 w.write_message(Notify(format!(
340 "New {} train in service: {}",
341 loco.name(),
342 names.join(" -> ")
343 )));
344 set_tool(w, Tool::Inspect);
345}
346
347/// Index of the first track that a raid has damaged.
348fn damaged_track(w: &World) -> Option<usize> {
349 w.resource::<Network>()
350 .tracks
351 .iter()
352 .position(|t| t.condition < 1.0)
353}
354
355/// Damages one front track exactly as the hourly raid check does.
356fn force_raid(w: &mut World) {
357 let raid = w.resource_scope(|world: &mut World, mut net: Mut<Network>| {
358 world.resource_scope(|_: &mut World, mut runtime: Mut<FrontRuntime>| {
359 air_raid(&mut net, &mut runtime)
360 })
361 });
362 if let Some((_, text)) = raid {
363 w.write_message(SoundEvent::Raid);
364 w.write_message(Notify(text));
365 }
366}
367
368/// Selects the hungriest city with real hunger, or Kestrau when none is hungry.
369fn select_hungry_city(w: &mut World) {
370 let target = {
371 let net = w.resource::<Network>();
372 net.nodes
373 .iter()
374 .enumerate()
375 .filter(|(_, n)| n.kind == NodeKind::City && n.hunger >= 0.5)
376 .max_by(|a, b| a.1.hunger.total_cmp(&b.1.hunger))
377 .map(|(i, _)| NodeId(i))
378 };
379 let id = match target {
380 Some(id) => id,
381 None => node_id(w.resource::<Network>(), "Kestrau"),
382 };
383 w.resource_mut::<Selected>().0 = Some(id);
384}
385
386/// Waits for the treasury to reach `cost`, with the clock at 4x while waiting.
387fn wait_for_money(cost: i64) -> Vec<Step> {
388 vec![
389 act(|w| set_speed(w, 4)),
390 until(move |w| money(w) >= cost, WAIT_TIMEOUT_SECS),
391 act(|w| set_speed(w, 1)),
392 ]
393}
394
395/// Builds the whole demo, with the track costs taken from the starting map.
396fn build_steps() -> VecDeque<Step> {
397 let net = Network::default();
398 let track = |a: &str, b: &str| {
399 let (a, b) = (node_id(&net, a), node_id(&net, b));
400 track_cost(net.nodes[a.0].pos.distance(net.nodes[b.0].pos))
401 };
402 let feldau_north = track("Feldau", "North Sector");
403 let light_cost = consist_cost(LocoKind::Light, &[CarKind::Food; 2]);
404 let hospital_cost = consist_cost(LocoKind::Light, &[CarKind::Hospital; 3]);
405
406 let mut s = VecDeque::new();
407
408 // 1. Main menu, Settings, How to Play, then New Operation.
409 s.push_back(say(
410 "This is Iron Lifeline. You are the railway commander of a nation at war.",
411 ));
412 s.push_back(act(|w| set_screen(w, Some(MenuScreen::Settings))));
413 s.push_back(say(
414 "Settings: resolution, window mode, VSync, FPS limit, performance overlay and audio. Saved to settings.toml.",
415 ));
416 s.push_back(act(|w| set_screen(w, Some(MenuScreen::Main))));
417 s.push_back(act(|w| set_screen(w, Some(MenuScreen::HowToPlay))));
418 s.push_back(say("How to Play explains the rules any time."));
419 s.push_back(act(|w| set_screen(w, Some(MenuScreen::Main))));
420 s.push_back(pause(0.5));
421 s.push_back(act(new_operation));
422 s.push_back(pause(0.5));
423
424 // 2. The map.
425 s.push_back(say(
426 "Left side is home: factories make Ammo, farms make Food, cities and the capital make Troops.",
427 ));
428 s.push_back(say(
429 "Right side is the front. Three sectors burn through supplies every hour.",
430 ));
431 s.push_back(say(
432 "The red line is the front. Supplied sectors push it right. Starving ones fall back.",
433 ));
434 s.push_back(say(
435 "One ammo train is already running to the Centre Sector.",
436 ));
437
438 // 3. Select North Sector.
439 s.push_back(act(|w| select(w, "North Sector")));
440 s.push_back(say(
441 "North Sector has no railway yet. Its supplies are running out.",
442 ));
443
444 // 4. Build track Feldau -> North Sector, then connect the Lindach farm to Feldau.
445 s.push_back(act(|w| set_tool(w, Tool::BuildTrack { from: None })));
446 s.push_back(pause(0.6));
447 s.push_back(act(|w| click(w, "Feldau")));
448 s.push_back(pause(0.8));
449 s.push_back(act(|w| click(w, "North Sector")));
450 s.push_back(pause(0.8));
451 s.push_back(say(format!(
452 "Laying track costs money: about ${feldau_north} for this line."
453 )));
454 s.push_back(act(|w| set_tool(w, Tool::BuildTrack { from: None })));
455 s.push_back(act(|w| click(w, "Lindach")));
456 s.push_back(pause(0.6));
457 s.push_back(act(|w| click(w, "Feldau")));
458 s.push_back(pause(0.8));
459 s.push_back(act(|w| set_tool(w, Tool::Inspect)));
460 s.push_back(pause(0.4));
461
462 // 5. Heavy ammo train: Ostwerk (load Ammo) -> Feldau -> North Sector.
463 s.push_back(act(|w| {
464 set_tool(
465 w,
466 Tool::NewRoute {
467 loco: LocoKind::Heavy,
468 cars: vec![CarKind::Ammo; 4],
469 stops: Vec::new(),
470 },
471 )
472 }));
473 s.push_back(pause(0.4));
474 s.push_back(act(|w| click(w, "Ostwerk")));
475 s.push_back(pause(0.5));
476 s.push_back(act(|w| click(w, "Feldau")));
477 s.push_back(pause(0.5));
478 s.push_back(act(|w| click(w, "North Sector")));
479 s.push_back(pause(0.5));
480 s.push_back(act(|w| set_loads(w, 1, [false; 4])));
481 s.push_back(act(|w| set_loads(w, 2, [false; 4])));
482 s.push_back(pause(0.4));
483 s.push_back(say(
484 "A Heavy train: slow, but its four ammo cars carry 40 crates. It loads Ammo at the factory and unloads at the front.",
485 ));
486 s.push_back(act(confirm_route));
487 s.push_back(pause(0.6));
488
489 // 6. Light food train: Lindach (load Food) -> North Sector.
490 s.push_back(act(|w| {
491 set_tool(
492 w,
493 Tool::NewRoute {
494 loco: LocoKind::Light,
495 cars: vec![CarKind::Food; 2],
496 stops: Vec::new(),
497 },
498 )
499 }));
500 s.push_back(pause(0.4));
501 s.push_back(act(|w| click(w, "Lindach")));
502 s.push_back(pause(0.5));
503 s.push_back(act(|w| click(w, "North Sector")));
504 s.push_back(pause(0.5));
505 s.push_back(act(|w| set_loads(w, 1, [false; 4])));
506 s.push_back(pause(0.4));
507 s.extend(wait_for_money(light_cost));
508 s.push_back(say("A Light train brings Food from the farm."));
509 s.push_back(act(confirm_route));
510 s.push_back(pause(0.6));
511
512 // 7. Hospital train: Centre Sector (wounded) -> Varenholm.
513 s.push_back(act(|w| {
514 set_tool(
515 w,
516 Tool::NewRoute {
517 loco: LocoKind::Light,
518 cars: vec![CarKind::Hospital; 3],
519 stops: Vec::new(),
520 },
521 )
522 }));
523 s.push_back(pause(0.4));
524 s.push_back(act(|w| click(w, "Centre Sector")));
525 s.push_back(pause(0.5));
526 s.push_back(act(|w| click(w, "Varenholm")));
527 s.push_back(pause(0.5));
528 s.extend(wait_for_money(hospital_cost));
529 s.push_back(say(
530 "Fronts produce wounded soldiers. Hospital trains bring them home, where they recover into troops.",
531 ));
532 s.push_back(act(confirm_route));
533 s.push_back(pause(0.6));
534
535 // 8. Faster time.
536 s.push_back(act(|w| set_speed(w, 4)));
537 s.push_back(say(
538 "Time runs faster now. Watch the supply bars and the red line.",
539 ));
540
541 // 9. Air raid, then repair.
542 s.push_back(until(|w| damaged_track(w).is_some(), RAID_WAIT_SECS));
543 s.push_back(act(|w| {
544 if damaged_track(w).is_none() {
545 force_raid(w);
546 }
547 }));
548 s.push_back(say(
549 "Air raid! Bombed track turns orange, or red with a gap. Trains slow down or stop.",
550 ));
551 s.push_back(act(|w| {
552 set_tool(w, Tool::Repair);
553 if let Some(i) = damaged_track(w) {
554 w.write_message(TrackClicked(i));
555 }
556 }));
557 s.push_back(pause(0.5));
558 s.push_back(say(format!(
559 "Click it (wrench mark) to repair for ${REPAIR_COST}."
560 )));
561 s.push_back(act(|w| set_tool(w, Tool::Inspect)));
562
563 // 10. A hungry city.
564 s.push_back(act(select_hungry_city));
565 s.push_back(say(
566 "Your cities need food too. Hungry cities make fewer troops and less ammo. Feeding the front or your people: that's the real choice.",
567 ));
568
569 // 11. The weekly budget.
570 s.push_back(until(|w| w.resource::<SimClock>().hour >= WEEK_HOURS, 25.0));
571 s.push_back(say(
572 "Every week the War Ministry sends a budget. Train upkeep is paid from it.",
573 ));
574
575 // 12. Pause menu and the end.
576 s.push_back(act(|w| set_screen(w, Some(MenuScreen::Pause))));
577 s.push_back(say(
578 "Press Esc any time to pause, change settings or read How to Play.",
579 ));
580 s.push_back(say("Keep the front alive. Thanks for watching."));
581 s.push_back(pause(4.0));
582 s
583}