forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

trains.rs499 lines, 16.1 KiBHistoryRawDownload
1//! Train simulation and train drawing.
2
3use bevy::prelude::*;
4
5use crate::audio::SoundEvent;
6use crate::map::good_color;
7use crate::model::{
8 CAR_CAPACITY, CarKind, GOODS, LocoKind, MIN_USABLE_CONDITION, Network, NodeId, Notify,
9 SimClock, Stop, Train, speed_factor,
10};
11use crate::seasons::SeasonState;
12
13/// The train every game starts with: a Heavy with four ammo cars running Ostwerk
14/// (factory, node 3) to Centre Sector (node 10), loading Ammo at Ostwerk.
15pub fn starting_train() -> Train {
16 new_train(
17 LocoKind::Heavy,
18 vec![CarKind::Ammo; 4],
19 vec![
20 Stop {
21 node: NodeId(3),
22 load: [true, false, false, false],
23 },
24 Stop {
25 node: NodeId(10),
26 load: [false; 4],
27 },
28 ],
29 )
30}
31
32/// A new train waiting at the first stop of `route`, with nothing aboard.
33pub fn new_train(loco: LocoKind, cars: Vec<CarKind>, route: Vec<Stop>) -> Train {
34 Train {
35 loco,
36 cars,
37 at: route[0].node,
38 route,
39 stop_idx: 0,
40 path: Vec::new(),
41 progress: 0.0,
42 cargo: [0.0; 4],
43 dwell: 0.0,
44 stalled: false,
45 crates: 0,
46 }
47}
48
49fn spawn_starting_train(mut commands: Commands) {
50 commands.spawn(starting_train());
51}
52
53/// World position of a train: along its current segment, or at its node.
54pub fn train_center(net: &Network, train: &Train) -> Vec2 {
55 let origin = net.nodes[train.at.0].pos;
56 match train.path.first() {
57 Some(next) => origin.lerp(net.nodes[next.0].pos, train.progress.clamp(0.0, 1.0)),
58 None => origin,
59 }
60}
61
62/// Display number of a train, counted from 1 in spawn order.
63#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
64pub struct TrainNo(pub u32);
65
66/// Last number handed out. Reset to zero on restart so numbering starts again at 1.
67#[derive(Resource, Debug, Default)]
68pub struct TrainCounter(pub u32);
69
70/// Private per-train bookkeeping for stalls.
71#[derive(Component, Debug, Default)]
72struct TrainAux {
73 /// Seconds until the next re-route attempt while stalled.
74 retry: f32,
75 /// True once the stall news was sent for the current stall.
76 notified: bool,
77}
78
79const DWELL_SECS: f32 = 1.0;
80const STALL_RETRY_SECS: f32 = 1.0;
81/// Locomotive length, and car length and spacing, in world units.
82const LOCO_LEN: f32 = 18.0;
83const CAR_LEN: f32 = 12.0;
84const CAR_GAP: f32 = 2.0;
85const TRAIN_HALF_WIDTH: f32 = 4.0;
86const LOAD_EPS: f32 = 1e-4;
87
88/// Splits the free space among the goods that are in stock and have room.
89///
90/// `room[i]` caps how much of good `i` may be taken: zero for goods the stop
91/// does not load or the train has no car for. Each round every open good gets
92/// an equal share of what is left. A good capped by its stock or its room drops
93/// out and its unused share goes to the others in the next round. Returns the
94/// amount taken per good. The result never exceeds `free` in total, nor `stock`
95/// or `room` per good.
96pub fn split_load(free: f32, stock: [f32; 4], room: [f32; 4]) -> [f32; 4] {
97 let limit = |i: usize| stock[i].min(room[i]);
98 let mut take = [0.0_f32; 4];
99 let mut left = free.max(0.0);
100 let mut open: Vec<usize> = (0..4).filter(|&i| limit(i) > LOAD_EPS).collect();
101 while left > LOAD_EPS && !open.is_empty() {
102 let share = left / open.len() as f32;
103 let mut spent = 0.0;
104 for &i in &open {
105 let t = share.min(limit(i) - take[i]);
106 take[i] += t;
107 spent += t;
108 }
109 left -= spent;
110 open.retain(|&i| limit(i) - take[i] > LOAD_EPS);
111 }
112 take
113}
114
115/// Gives every new train a `TrainNo` and its private bookkeeping.
116fn number_new_trains(
117 mut commands: Commands,
118 mut counter: ResMut<TrainCounter>,
119 new_trains: Query<Entity, Added<Train>>,
120) {
121 for entity in &new_trains {
122 counter.0 += 1;
123 commands
124 .entity(entity)
125 .insert((TrainNo(counter.0), TrainAux::default()));
126 }
127}
128
129/// Finds the path from the train's position to its current stop target and
130/// drops the first element (the node it is already at). Returns false and
131/// marks the train stalled when no usable track exists.
132fn plan_next(train: &mut Train, net: &Network) -> bool {
133 let target = train.route[train.stop_idx].node;
134 match net.shortest_path(train.at, target) {
135 Some(mut p) => {
136 p.remove(0);
137 train.path = p;
138 train.stalled = false;
139 true
140 }
141 None => {
142 train.path.clear();
143 train.stalled = true;
144 false
145 }
146 }
147}
148
149/// Plans the next leg. On failure sets the stall retry timer and sends the
150/// stall news once per stall.
151fn plan_or_stall(
152 train: &mut Train,
153 aux: &mut TrainAux,
154 net: &Network,
155 no: TrainNo,
156 notify: &mut MessageWriter<Notify>,
157) {
158 if plan_next(train, net) {
159 aux.notified = false;
160 return;
161 }
162 aux.retry = STALL_RETRY_SECS;
163 if !aux.notified {
164 aux.notified = true;
165 let target = train.route[train.stop_idx].node;
166 notify.write(Notify(format!(
167 "Train #{} stalled: no track to {}",
168 no.0, net.nodes[target.0].name
169 )));
170 }
171}
172
173/// Stop actions for a train that is at its current stop node: unload, load,
174/// start the dwell and advance to the next stop. The caller then plans the
175/// path to that next stop.
176fn run_stop(train: &mut Train, net: &mut Network) {
177 let stop = train.route[train.stop_idx];
178
179 // (0) Crates: credit what reached the destination to the evacuation at the
180 // route's first stop, then take on crates at an evacuating site.
181 let origin = train.route[0].node;
182 if train.crates > 0 && origin != train.at {
183 if let Some(evac) = net.nodes[origin.0].evac.as_mut() {
184 evac.delivered += train.crates;
185 }
186 train.crates = 0;
187 }
188 if let Some(evac) = net.nodes[train.at.0].evac.as_mut()
189 && evac.dest.is_some()
190 {
191 let take = train.crate_slots().saturating_sub(train.crates).min(evac.crates_left);
192 evac.crates_left -= take;
193 train.crates += take;
194 }
195
196 let node = &mut net.nodes[train.at.0];
197
198 // (1) Unload every good the node accepts.
199 for g in GOODS {
200 let i = g.idx();
201 if train.cargo[i] > 0.0 && node.kind.accepts(g) {
202 node.stock[i] += train.cargo[i];
203 train.cargo[i] = 0.0;
204 }
205 }
206
207 // (2) Load flagged goods up to what each good's cars can still hold.
208 let mut room = [0.0_f32; 4];
209 for g in GOODS {
210 let i = g.idx();
211 if stop.load[i] {
212 room[i] = (train.capacity(g) - train.cargo[i]).max(0.0);
213 }
214 }
215 let take = split_load(room.iter().sum(), node.stock, room);
216 for (i, &amount) in take.iter().enumerate() {
217 train.cargo[i] += amount;
218 node.stock[i] = (node.stock[i] - amount).max(0.0);
219 }
220
221 // (3) Dwell and advance to the next stop.
222 train.dwell = DWELL_SECS;
223 train.stop_idx = (train.stop_idx + 1) % train.route.len();
224}
225
226fn simulate_trains(
227 time: Res<Time>,
228 clock: Res<SimClock>,
229 season: Res<SeasonState>,
230 mut network: ResMut<Network>,
231 mut notify: MessageWriter<Notify>,
232 mut sounds: MessageWriter<SoundEvent>,
233 mut trains: Query<(&mut Train, &mut TrainAux, &TrainNo)>,
234) {
235 let dt = time.delta_secs() * clock.speed as f32;
236 if dt <= 0.0 {
237 return;
238 }
239 let net: &mut Network = &mut network;
240
241 for (mut train, mut aux, no) in &mut trains {
242 let len = train.route.len();
243 if len == 0 {
244 continue;
245 }
246 if train.stop_idx >= len {
247 train.stop_idx = 0;
248 }
249 if train.dwell > 0.0 {
250 train.dwell -= dt;
251 }
252
253 // Stalled: retry the route every STALL_RETRY_SECS.
254 if train.stalled {
255 aux.retry -= dt;
256 if aux.retry <= 0.0 {
257 plan_or_stall(&mut train, &mut aux, net, *no, &mut notify);
258 }
259 continue;
260 }
261
262 // Standing at a node with no path left.
263 if train.path.is_empty() {
264 if train.dwell > 0.0 {
265 continue;
266 }
267 if train.at == train.route[train.stop_idx].node {
268 run_stop(&mut train, net);
269 sounds.write(SoundEvent::TrainDeparts);
270 }
271 plan_or_stall(&mut train, &mut aux, net, *no, &mut notify);
272 continue;
273 }
274
275 // Moving along the segment to path[0].
276 let next = train.path[0];
277 if train.progress <= 0.0 {
278 let usable = net
279 .track_between(train.at, next)
280 .is_some_and(|i| net.tracks[i].condition >= MIN_USABLE_CONDITION);
281 if !usable {
282 plan_or_stall(&mut train, &mut aux, net, *no, &mut notify);
283 continue;
284 }
285 }
286 // A train mid-segment keeps going even if the track was damaged,
287 // but damaged track (below SLOW_CONDITION) halves its speed.
288 let segment = net.track_between(train.at, next).map(|i| net.tracks[i]);
289 let length = segment.map_or(0.0, |t| t.length);
290 let condition = segment.map_or(1.0, |t| t.condition);
291 if length <= 0.0 {
292 train.progress = 1.0;
293 } else {
294 train.progress +=
295 train.speed() * speed_factor(condition) * season.season.speed_mult() * dt / length;
296 }
297 if train.progress >= 1.0 {
298 train.at = train.path.remove(0);
299 train.progress = 0.0;
300 }
301 }
302}
303
304/// Draws a filled horizontal band in the train's local frame, as parallel
305/// lines spaced one world unit apart.
306fn draw_band(gizmos: &mut Gizmos, frame: &Frame, x0: f32, x1: f32, half_h: f32, color: Color) {
307 let steps = (2.0 * half_h).round() as i32;
308 for k in 0..=steps {
309 let y = -half_h + k as f32;
310 gizmos.line_2d(frame.at(x0, y), frame.at(x1, y), color);
311 }
312}
313
314/// Local train frame: origin at the train centre, `dir` along the track.
315struct Frame {
316 center: Vec2,
317 dir: Vec2,
318 nrm: Vec2,
319}
320
321impl Frame {
322 fn at(&self, x: f32, y: f32) -> Vec2 {
323 self.center + self.dir * x + self.nrm * y
324 }
325}
326
327fn draw_trains(mut gizmos: Gizmos, time: Res<Time>, network: Res<Network>, trains: Query<&Train>) {
328 let ink = Color::srgb(0.12, 0.10, 0.08);
329 let steel_blue = Color::srgb(0.27, 0.51, 0.71);
330 let near_black = Color::srgb(0.08, 0.08, 0.09);
331 let cross_red = Color::srgb(0.80, 0.10, 0.10);
332 let stall_red = Color::srgb(0.90, 0.12, 0.12);
333 let flat_grey = Color::srgb(0.55, 0.53, 0.50);
334 let crate_fill = Color::srgb(0.55, 0.36, 0.16);
335 let blink_on = ((time.elapsed_secs() * 2.0) as u32).is_multiple_of(2);
336
337 for train in &trains {
338 let Some(origin) = network.nodes.get(train.at.0).map(|n| n.pos) else {
339 continue;
340 };
341 let (center, dir) = match train.path.first() {
342 Some(next) => {
343 let target = network.nodes[next.0].pos;
344 let d = (target - origin).normalize_or_zero();
345 let d = if d == Vec2::ZERO { Vec2::X } else { d };
346 let p = origin.lerp(target, train.progress.clamp(0.0, 1.0));
347 (p, d)
348 }
349 None => (origin, Vec2::X),
350 };
351 let frame = Frame {
352 center,
353 dir,
354 nrm: Vec2::new(-dir.y, dir.x),
355 };
356 let angle = dir.y.atan2(dir.x);
357
358 // Locomotive: outline, then body fill, blinking red when stalled.
359 let half_loco = LOCO_LEN / 2.0;
360 gizmos.rect_2d(
361 Isometry2d::new(center, Rot2::radians(angle)),
362 Vec2::new(LOCO_LEN, TRAIN_HALF_WIDTH * 2.0),
363 ink,
364 );
365 let base = match train.loco {
366 LocoKind::Light => steel_blue,
367 LocoKind::Heavy => near_black,
368 };
369 let body = if train.stalled && blink_on {
370 stall_red
371 } else {
372 base
373 };
374 draw_band(
375 &mut gizmos,
376 &frame,
377 -half_loco,
378 half_loco,
379 TRAIN_HALF_WIDTH,
380 body,
381 );
382
383 // Cars trail behind the locomotive, one rectangle each.
384 for (i, car) in train.cars.iter().enumerate() {
385 let right = -half_loco - CAR_GAP - i as f32 * (CAR_LEN + CAR_GAP);
386 let left = right - CAR_LEN;
387 let mid = (left + right) / 2.0;
388 let Some(good) = car.good() else {
389 // Flat cars carry one evacuation crate each, in order.
390 gizmos.rect_2d(
391 Isometry2d::new(frame.at(mid, 0.0), Rot2::radians(angle)),
392 Vec2::new(CAR_LEN, TRAIN_HALF_WIDTH * 2.0),
393 flat_grey,
394 );
395 let flats_before = train.cars[..i].iter().filter(|c| **c == CarKind::Flat).count();
396 if (flats_before as u32) < train.crates {
397 draw_band(&mut gizmos, &frame, mid - 4.0, mid + 4.0, 3.0, crate_fill);
398 }
399 continue;
400 };
401 gizmos.rect_2d(
402 Isometry2d::new(frame.at(mid, 0.0), Rot2::radians(angle)),
403 Vec2::new(CAR_LEN, TRAIN_HALF_WIDTH * 2.0),
404 ink,
405 );
406 // Faint tint for the empty part, solid tint up to how full this car is.
407 // Cars of one good fill in order, so the cargo spreads over them.
408 let color = good_color(good);
409 draw_band(
410 &mut gizmos,
411 &frame,
412 left,
413 right,
414 TRAIN_HALF_WIDTH,
415 color.with_alpha(0.25),
416 );
417 let before = train.cars[..i].iter().filter(|c| c.good() == Some(good)).count();
418 let held = (train.cargo[good.idx()] - before as f32 * CAR_CAPACITY)
419 .clamp(0.0, CAR_CAPACITY);
420 let fill = held / CAR_CAPACITY;
421 if fill > 0.0 {
422 draw_band(
423 &mut gizmos,
424 &frame,
425 left,
426 left + CAR_LEN * fill,
427 TRAIN_HALF_WIDTH,
428 color,
429 );
430 }
431
432 // Hospital cars keep their cross.
433 if *car == CarKind::Hospital {
434 gizmos.line_2d(frame.at(mid - 3.0, 0.0), frame.at(mid + 3.0, 0.0), cross_red);
435 gizmos.line_2d(frame.at(mid, -3.0), frame.at(mid, 3.0), cross_red);
436 }
437 }
438 }
439}
440
441pub struct TrainsPlugin;
442
443impl Plugin for TrainsPlugin {
444 fn build(&self, app: &mut App) {
445 app.init_resource::<TrainCounter>()
446 .add_systems(Startup, spawn_starting_train)
447 .add_systems(
448 Update,
449 (number_new_trains, simulate_trains, draw_trains).chain(),
450 );
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 fn total(v: [f32; 4]) -> f32 {
459 v.iter().sum()
460 }
461
462 #[test]
463 fn split_gives_leftover_to_others() {
464 // Ammo is capped at 2 by stock, so food takes the rest of the 10 units.
465 let take = split_load(10.0, [2.0, 100.0, 0.0, 0.0], [10.0, 10.0, 0.0, 0.0]);
466 assert!((take[0] - 2.0).abs() < 1e-4);
467 assert!((take[1] - 8.0).abs() < 1e-4);
468 }
469
470 #[test]
471 fn split_never_exceeds_free_or_stock() {
472 let stock = [3.0, 7.0, 1.0, 50.0];
473 let room = [12.0, 12.0, 12.0, 0.0];
474 let take = split_load(12.0, stock, room);
475 assert!(total(take) <= 12.0 + 1e-3);
476 for i in 0..4 {
477 assert!(take[i] <= stock[i] + 1e-4);
478 }
479 assert!((total(take) - 11.0).abs() < 1e-3);
480 }
481
482 #[test]
483 fn stop_loads_only_up_to_each_goods_cars() {
484 // One ammo car and two food cars: 10 ammo and 20 food fit; no troop car, so no troops.
485 let mut net = Network::default();
486 let stop = Stop {
487 node: NodeId(3),
488 load: [true, true, true, false],
489 };
490 let mut train = new_train(
491 LocoKind::Light,
492 vec![CarKind::Ammo, CarKind::Food, CarKind::Food],
493 vec![stop, stop],
494 );
495 net.nodes[3].stock = [100.0, 100.0, 100.0, 0.0];
496 run_stop(&mut train, &mut net);
497 assert_eq!(train.cargo, [10.0, 20.0, 0.0, 0.0]);
498 }
499}