forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

scenario.rs254 lines, 7.2 KiBHistoryRawDownload
1//! Verification harness, active only with command-line flags.
2//!
3//! - `--scenario` lays out a fixed network with trains, selects a front
4//! sector and runs the clock at 4x.
5//! - `--record <dir>` saves a screenshot of the primary window every 0.1 real
6//! seconds to `<dir>/frame_{:05}.png`.
7//! - `--quit-after <secs>` exits the app after that much real time.
8//! - `--stress` (with `--scenario`) pushes North Sector's front line back and
9//! starts in summer, to reach evacuations and seasons quickly.
10//! - `--demo` runs the self-playing narrated demo (`demo.rs`).
11//!
12//! Without flags none of this is added to the app.
13
14use std::path::PathBuf;
15
16use bevy::app::AppExit;
17use bevy::prelude::*;
18use bevy::render::view::window::screenshot::{Screenshot, save_to_disk};
19use bevy::time::{Real, Time};
20
21use crate::model::{
22 CarKind, LocoKind, Network, NodeId, Selected, SimClock, Stop, TrackSeg, Train,
23};
24
25/// Seconds between saved frames.
26const RECORD_INTERVAL: f32 = 0.1;
27
28/// Command-line options. Unknown arguments are ignored.
29#[derive(Default)]
30pub struct Cli {
31 pub scenario: bool,
32 pub stress: bool,
33 pub play: bool,
34 pub demo: bool,
35 pub record: Option<PathBuf>,
36 pub quit_after: Option<f32>,
37}
38
39impl Cli {
40 pub fn from_env() -> Self {
41 let mut cli = Cli::default();
42 let mut args = std::env::args().skip(1);
43 while let Some(arg) = args.next() {
44 match arg.as_str() {
45 "--scenario" => cli.scenario = true,
46 "--stress" => cli.stress = true,
47 "--play" => cli.play = true,
48 "--demo" => cli.demo = true,
49 "--record" => cli.record = args.next().map(PathBuf::from),
50 "--quit-after" => cli.quit_after = args.next().and_then(|s| s.parse().ok()),
51 _ => {}
52 }
53 }
54 cli
55 }
56}
57
58fn find(net: &Network, name: &str) -> NodeId {
59 net.nodes
60 .iter()
61 .position(|n| n.name == name)
62 .map(NodeId)
63 .unwrap_or_else(|| panic!("scenario: no node named {name}"))
64}
65
66fn stop(node: NodeId, goods: &[usize]) -> Stop {
67 let mut load = [false; 4];
68 for &g in goods {
69 load[g] = true;
70 }
71 Stop { node, load }
72}
73
74fn train(loco: LocoKind, cars: Vec<CarKind>, route: Vec<Stop>) -> Train {
75 Train {
76 loco,
77 cars,
78 at: route[0].node,
79 route,
80 stop_idx: 0,
81 path: Vec::new(),
82 progress: 0.0,
83 cargo: [0.0; 4],
84 dwell: 0.0,
85 stalled: false,
86 crates: 0,
87 }
88}
89
90/// Lays the scenario network, spawns the trains and selects a front sector.
91fn setup_scenario(
92 mut commands: Commands,
93 mut net: ResMut<Network>,
94 mut clock: ResMut<SimClock>,
95 mut selected: ResMut<Selected>,
96 stress: Res<Stress>,
97) {
98 // Good indices: ammo 0, food 1, troops 2, wounded 3.
99 let (ammo, food, troops, wounded) = (0, 1, 2, 3);
100
101 let links = [
102 ("Varenholm", "Lindach"),
103 ("Lindach", "Feldau"),
104 ("Feldau", "North Sector"),
105 ("Feldau", "Centre Sector"),
106 ("Vellin", "Sorvik"),
107 ("Sorvik", "Rhunen"),
108 ("Rhunen", "South Sector"),
109 ("Brenhollow", "Lindach"),
110 ];
111 for (a, b) in links {
112 let (a, b) = (find(&net, a), find(&net, b));
113 let length = net.nodes[a.0].pos.distance(net.nodes[b.0].pos);
114 net.tracks.push(TrackSeg {
115 a,
116 b,
117 length,
118 condition: 1.0,
119 });
120 }
121
122 let n = |name: &str| find(&net, name);
123 let trains = [
124 // Heavy ammo: factory to the front and back.
125 train(
126 LocoKind::Heavy,
127 vec![CarKind::Ammo; 4],
128 vec![stop(n("Ostwerk"), &[ammo]), stop(n("North Sector"), &[])],
129 ),
130 train(
131 LocoKind::Heavy,
132 vec![CarKind::Ammo; 4],
133 vec![stop(n("Vellin"), &[ammo]), stop(n("South Sector"), &[])],
134 ),
135 // Light food: farms to the centre front and to a city.
136 train(
137 LocoKind::Light,
138 vec![CarKind::Food; 2],
139 vec![stop(n("Lindach"), &[food]), stop(n("Centre Sector"), &[])],
140 ),
141 train(
142 LocoKind::Light,
143 vec![CarKind::Food; 2],
144 vec![stop(n("Sorvik"), &[food]), stop(n("South Sector"), &[])],
145 ),
146 train(
147 LocoKind::Light,
148 vec![CarKind::Food; 2],
149 vec![stop(n("Lindach"), &[food]), stop(n("Brenhollow"), &[])],
150 ),
151 // Hospital: wounded from the north front back to the capital.
152 train(
153 LocoKind::Light,
154 vec![CarKind::Hospital; 3],
155 vec![
156 stop(n("North Sector"), &[wounded]),
157 stop(n("Varenholm"), &[]),
158 ],
159 ),
160 // Light troops from the capital to the centre front.
161 train(
162 LocoKind::Light,
163 vec![CarKind::Troop; 2],
164 vec![
165 stop(n("Varenholm"), &[troops]),
166 stop(n("Centre Sector"), &[]),
167 ],
168 ),
169 ];
170 for t in trains {
171 commands.spawn(t);
172 }
173
174 clock.speed = 4;
175 selected.0 = Some(n("North Sector"));
176 if stress.0 {
177 // Summer starts at hour 14 days; the front is pushed back to threaten the north.
178 clock.hour = 24 * 14;
179 let north = n("North Sector");
180 if let Some(front) = net.nodes[north.0].front.as_mut() {
181 front.line = -0.45;
182 }
183 }
184}
185
186#[derive(Resource)]
187struct Stress(bool);
188
189/// Adds the fixed scenario network, trains and clock speed at startup.
190pub struct ScenarioPlugin {
191 pub stress: bool,
192}
193
194impl Plugin for ScenarioPlugin {
195 fn build(&self, app: &mut App) {
196 app.insert_resource(Stress(self.stress))
197 .add_systems(Startup, setup_scenario);
198 }
199}
200
201#[derive(Resource)]
202struct Recorder {
203 dir: PathBuf,
204 /// Real seconds since the last frame was saved.
205 acc: f32,
206 frame: u32,
207}
208
209#[derive(Resource)]
210struct QuitAfter(f32);
211
212/// Screenshot recording and timed exit. Added only when a flag asks for them.
213#[derive(Default)]
214pub struct CapturePlugin {
215 pub record: Option<PathBuf>,
216 pub quit_after: Option<f32>,
217}
218
219impl Plugin for CapturePlugin {
220 fn build(&self, app: &mut App) {
221 if let Some(dir) = &self.record {
222 std::fs::create_dir_all(dir).expect("create --record directory");
223 app.insert_resource(Recorder {
224 dir: dir.clone(),
225 acc: 0.0,
226 frame: 0,
227 })
228 .add_systems(Update, record_frames);
229 }
230 if let Some(secs) = self.quit_after {
231 app.insert_resource(QuitAfter(secs))
232 .add_systems(Update, quit_when_due);
233 }
234 }
235}
236
237fn record_frames(mut commands: Commands, time: Res<Time<Real>>, mut rec: ResMut<Recorder>) {
238 rec.acc += time.delta_secs();
239 if rec.acc < RECORD_INTERVAL {
240 return;
241 }
242 rec.acc -= RECORD_INTERVAL;
243 let path = rec.dir.join(format!("frame_{:05}.png", rec.frame));
244 rec.frame += 1;
245 commands
246 .spawn(Screenshot::primary_window())
247 .observe(save_to_disk(path));
248}
249
250fn quit_when_due(time: Res<Time<Real>>, quit: Res<QuitAfter>, mut exit: MessageWriter<AppExit>) {
251 if time.elapsed_secs() >= quit.0 {
252 exit.write(AppExit::Success);
253 }
254}