forge
Explore
Log in

Don't you dare go Hollow

5226b95b1571495f036229b01defb665d88cd336Ahmet Kaan GümüşRoot commit (no parents)
.gitignoreadded+1 -0
@@ -0,0 +1 @@
1+/target
Cargo.lockadded+6575 -0

Diff too large; view file

@@ -0,0 +1,6575 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "ab_glyph"
7+version = "0.2.32"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"
10+dependencies = [
11+ "ab_glyph_rasterizer",
12+ "owned_ttf_parser",
13+]
14+
15+[[package]]
16+name = "ab_glyph_rasterizer"
17+version = "0.1.10"
18+source = "registry+https://github.com/rust-lang/crates.io-index"
19+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
20+
21+[[package]]
22+name = "accesskit"
23+version = "0.24.1"
24+source = "registry+https://github.com/rust-lang/crates.io-index"
25+checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320"
26+dependencies = [
27+ "uuid",
28+]
29+
30+[[package]]
31+name = "accesskit_consumer"
32+version = "0.38.0"
33+source = "registry+https://github.com/rust-lang/crates.io-index"
34+checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245"
35+dependencies = [
36+ "accesskit",
37+ "hashbrown 0.16.1",
38+]
39+
40+[[package]]
41+name = "accesskit_ios"
42+version = "0.1.2"
43+source = "registry+https://github.com/rust-lang/crates.io-index"
44+checksum = "750c4e9f6ce888dfe8a10c0f1b5ceb646a7854fd46579d74919219d1bb314083"
45+dependencies = [
46+ "accesskit",
47+ "accesskit_consumer",
48+ "hashbrown 0.16.1",
49+ "objc2 0.5.3",
50+ "objc2-foundation 0.2.2",
51+ "objc2-ui-kit",
52+]
53+
54+[[package]]
55+name = "accesskit_macos"
56+version = "0.26.3"
57+source = "registry+https://github.com/rust-lang/crates.io-index"
58+checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076"
59+dependencies = [
60+ "accesskit",
61+ "accesskit_consumer",
62+ "hashbrown 0.16.1",
63+ "objc2 0.5.3",
64+ "objc2-app-kit 0.2.2",
65+ "objc2-foundation 0.2.2",
66+]
67+
68+[[package]]
69+name = "accesskit_windows"
70+version = "0.34.0"
71+source = "registry+https://github.com/rust-lang/crates.io-index"
72+checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1"
73+dependencies = [
74+ "accesskit",
75+ "accesskit_consumer",
76+ "hashbrown 0.16.1",
77+ "static_assertions",
78+ "windows",
79+ "windows-core",
80+]
81+
82+[[package]]
83+name = "accesskit_winit"
84+version = "0.33.2"
85+source = "registry+https://github.com/rust-lang/crates.io-index"
86+checksum = "d5b41e63a69f36d9f1f41e70464c7e5f72eee485ef26aab19f0b4f86e6c0a84c"
87+dependencies = [
88+ "accesskit",
89+ "accesskit_ios",
90+ "accesskit_macos",
91+ "accesskit_windows",
92+ "raw-window-handle",
93+ "winit",
94+]
95+
96+[[package]]
97+name = "adler2"
98+version = "2.0.1"
99+source = "registry+https://github.com/rust-lang/crates.io-index"
100+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
101+
102+[[package]]
103+name = "ahash"
104+version = "0.8.12"
105+source = "registry+https://github.com/rust-lang/crates.io-index"
106+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
107+dependencies = [
108+ "cfg-if",
109+ "getrandom 0.3.4",
110+ "once_cell",
111+ "version_check",
112+ "zerocopy",
113+]
114+
115+[[package]]
116+name = "aho-corasick"
117+version = "1.1.5"
118+source = "registry+https://github.com/rust-lang/crates.io-index"
119+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
120+dependencies = [
121+ "memchr",
122+]
123+
124+[[package]]
125+name = "allocator-api2"
126+version = "0.2.21"
127+source = "registry+https://github.com/rust-lang/crates.io-index"
128+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
129+
130+[[package]]
131+name = "alsa"
132+version = "0.11.0"
133+source = "registry+https://github.com/rust-lang/crates.io-index"
134+checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
135+dependencies = [
136+ "alsa-sys",
137+ "bitflags 2.13.2",
138+ "cfg-if",
139+ "libc",
140+]
141+
142+[[package]]
143+name = "alsa-sys"
144+version = "0.4.0"
145+source = "registry+https://github.com/rust-lang/crates.io-index"
146+checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
147+dependencies = [
148+ "libc",
149+ "pkg-config",
150+]
151+
152+[[package]]
153+name = "android-activity"
154+version = "0.6.1"
155+source = "registry+https://github.com/rust-lang/crates.io-index"
156+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"
157+dependencies = [
158+ "android-properties",
159+ "bitflags 2.13.2",
160+ "cc",
161+ "jni 0.22.4",
162+ "libc",
163+ "log",
164+ "ndk",
165+ "ndk-context",
166+ "ndk-sys",
167+ "num_enum",
168+ "thiserror 2.0.21",
169+]
170+
171+[[package]]
172+name = "android-properties"
173+version = "0.2.2"
174+source = "registry+https://github.com/rust-lang/crates.io-index"
175+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
176+
177+[[package]]
178+name = "android_log-sys"
179+version = "0.3.2"
180+source = "registry+https://github.com/rust-lang/crates.io-index"
181+checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d"
182+
183+[[package]]
184+name = "android_system_properties"
185+version = "0.1.6"
186+source = "registry+https://github.com/rust-lang/crates.io-index"
187+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
188+dependencies = [
189+ "libc",
190+]
191+
192+[[package]]
193+name = "annotate-snippets"
194+version = "0.12.17"
195+source = "registry+https://github.com/rust-lang/crates.io-index"
196+checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176"
197+dependencies = [
198+ "anstyle",
199+ "memchr",
200+ "unicode-width",
201+]
202+
203+[[package]]
204+name = "anstream"
205+version = "1.0.0"
206+source = "registry+https://github.com/rust-lang/crates.io-index"
207+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
208+dependencies = [
209+ "anstyle",
210+ "anstyle-parse",
211+ "anstyle-query",
212+ "anstyle-wincon",
213+ "colorchoice",
214+ "is_terminal_polyfill",
215+ "utf8parse",
216+]
217+
218+[[package]]
219+name = "anstyle"
220+version = "1.0.14"
221+source = "registry+https://github.com/rust-lang/crates.io-index"
222+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
223+
224+[[package]]
225+name = "anstyle-parse"
226+version = "1.0.0"
227+source = "registry+https://github.com/rust-lang/crates.io-index"
228+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
229+dependencies = [
230+ "utf8parse",
231+]
232+
233+[[package]]
234+name = "anstyle-query"
235+version = "1.1.5"
236+source = "registry+https://github.com/rust-lang/crates.io-index"
237+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
238+dependencies = [
239+ "windows-sys 0.61.2",
240+]
241+
242+[[package]]
243+name = "anstyle-wincon"
244+version = "3.0.11"
245+source = "registry+https://github.com/rust-lang/crates.io-index"
246+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
247+dependencies = [
248+ "anstyle",
249+ "once_cell_polyfill",
250+ "windows-sys 0.61.2",
251+]
252+
253+[[package]]
254+name = "approx"
255+version = "0.5.1"
256+source = "registry+https://github.com/rust-lang/crates.io-index"
257+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
258+dependencies = [
259+ "num-traits",
260+]
261+
262+[[package]]
263+name = "arboard"
264+version = "3.7.0"
265+source = "registry+https://github.com/rust-lang/crates.io-index"
266+checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917"
267+dependencies = [
268+ "clipboard-win",
269+ "log",
270+ "objc2 0.6.5",
271+ "objc2-app-kit 0.3.2",
272+ "objc2-foundation 0.3.2",
273+ "parking_lot",
274+ "percent-encoding",
275+ "windows-sys 0.61.2",
276+ "wl-clipboard-rs",
277+ "x11rb",
278+]
279+
280+[[package]]
281+name = "arrayref"
282+version = "0.3.9"
283+source = "registry+https://github.com/rust-lang/crates.io-index"
284+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
285+
286+[[package]]
287+name = "arrayvec"
288+version = "0.7.8"
289+source = "registry+https://github.com/rust-lang/crates.io-index"
290+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
291+
292+[[package]]
293+name = "as-raw-xcb-connection"
294+version = "1.0.1"
295+source = "registry+https://github.com/rust-lang/crates.io-index"
296+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
297+
298+[[package]]
299+name = "ash"
300+version = "0.38.0+1.3.281"
301+source = "registry+https://github.com/rust-lang/crates.io-index"
302+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
303+dependencies = [
304+ "libloading",
305+]
306+
307+[[package]]
308+name = "assert_type_match"
309+version = "0.1.1"
310+source = "registry+https://github.com/rust-lang/crates.io-index"
311+checksum = "f548ad2c4031f2902e3edc1f29c29e835829437de49562d8eb5dc5584d3a1043"
312+dependencies = [
313+ "proc-macro2",
314+ "quote",
315+ "syn 2.0.119",
316+]
317+
318+[[package]]
319+name = "async-broadcast"
320+version = "0.7.2"
321+source = "registry+https://github.com/rust-lang/crates.io-index"
322+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
323+dependencies = [
324+ "event-listener",
325+ "event-listener-strategy",
326+ "futures-core",
327+ "pin-project-lite",
328+]
329+
330+[[package]]
331+name = "async-channel"
332+version = "2.5.0"
333+source = "registry+https://github.com/rust-lang/crates.io-index"
334+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
335+dependencies = [
336+ "concurrent-queue",
337+ "event-listener-strategy",
338+ "futures-core",
339+ "pin-project-lite",
340+]
341+
342+[[package]]
343+name = "async-executor"
344+version = "1.14.0"
345+source = "registry+https://github.com/rust-lang/crates.io-index"
346+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
347+dependencies = [
348+ "async-task",
349+ "concurrent-queue",
350+ "fastrand",
351+ "futures-lite",
352+ "pin-project-lite",
353+ "slab",
354+]
355+
356+[[package]]
357+name = "async-fs"
358+version = "2.2.0"
359+source = "registry+https://github.com/rust-lang/crates.io-index"
360+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"
361+dependencies = [
362+ "async-lock",
363+ "blocking",
364+ "futures-lite",
365+]
366+
367+[[package]]
368+name = "async-io"
369+version = "2.6.0"
370+source = "registry+https://github.com/rust-lang/crates.io-index"
371+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
372+dependencies = [
373+ "autocfg",
374+ "cfg-if",
375+ "concurrent-queue",
376+ "futures-io",
377+ "futures-lite",
378+ "parking",
379+ "polling",
380+ "rustix 1.1.5",
381+ "slab",
382+ "windows-sys 0.61.2",
383+]
384+
385+[[package]]
386+name = "async-lock"
387+version = "3.4.2"
388+source = "registry+https://github.com/rust-lang/crates.io-index"
389+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
390+dependencies = [
391+ "event-listener",
392+ "event-listener-strategy",
393+ "pin-project-lite",
394+]
395+
396+[[package]]
397+name = "async-task"
398+version = "4.7.1"
399+source = "registry+https://github.com/rust-lang/crates.io-index"
400+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
401+dependencies = [
402+ "portable-atomic",
403+]
404+
405+[[package]]
406+name = "atomic-waker"
407+version = "1.1.2"
408+source = "registry+https://github.com/rust-lang/crates.io-index"
409+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
410+dependencies = [
411+ "portable-atomic",
412+]
413+
414+[[package]]
415+name = "atomicow"
416+version = "1.2.0"
417+source = "registry+https://github.com/rust-lang/crates.io-index"
418+checksum = "301801c08259e328a1c7da556608c0c22687708831b22024dbd3a57ea741e6de"
419+dependencies = [
420+ "portable-atomic",
421+ "portable-atomic-util",
422+]
423+
424+[[package]]
425+name = "autocfg"
426+version = "1.5.1"
427+source = "registry+https://github.com/rust-lang/crates.io-index"
428+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
429+
430+[[package]]
431+name = "base64"
432+version = "0.23.1"
433+source = "registry+https://github.com/rust-lang/crates.io-index"
434+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
435+
436+[[package]]
437+name = "bevy"
438+version = "0.20.0"
439+source = "registry+https://github.com/rust-lang/crates.io-index"
440+checksum = "8bd0e4ea5ec677698955f9f285221eab78606d8c27b57b889def199c16ce36e6"
441+dependencies = [
442+ "bevy_internal",
443+]
444+
445+[[package]]
446+name = "bevy_a11y"
447+version = "0.20.0"
448+source = "registry+https://github.com/rust-lang/crates.io-index"
449+checksum = "f1070b9b7f087a5073be2da713367f29a831c85cd3391afcfc95bc0498125704"
450+dependencies = [
451+ "accesskit",
452+ "bevy_app",
453+ "bevy_derive",
454+ "bevy_ecs",
455+ "bevy_reflect",
456+]
457+
458+[[package]]
459+name = "bevy_android"
460+version = "0.20.0"
461+source = "registry+https://github.com/rust-lang/crates.io-index"
462+checksum = "17fd56a4708085b36f8aa1a011e347f8bd9334f0343bb3d5d9c3742897968a55"
463+dependencies = [
464+ "android-activity",
465+]
466+
467+[[package]]
468+name = "bevy_animation"
469+version = "0.20.0"
470+source = "registry+https://github.com/rust-lang/crates.io-index"
471+checksum = "9409aa300e8b023281b78759b3aed4124ec745dc7e1c9f96cbb445110e4b32ad"
472+dependencies = [
473+ "bevy_animation_macros",
474+ "bevy_app",
475+ "bevy_asset",
476+ "bevy_color",
477+ "bevy_curve",
478+ "bevy_derive",
479+ "bevy_ecs",
480+ "bevy_math",
481+ "bevy_mesh",
482+ "bevy_platform",
483+ "bevy_reflect",
484+ "bevy_time",
485+ "bevy_transform",
486+ "bevy_utils",
487+ "bitvec",
488+ "blake3",
489+ "derive_more",
490+ "downcast-rs 2.0.2",
491+ "either",
492+ "petgraph",
493+ "ron",
494+ "serde",
495+ "smallvec",
496+ "thiserror 2.0.21",
497+ "thread_local",
498+ "tracing",
499+ "uuid",
500+]
501+
502+[[package]]
503+name = "bevy_animation_macros"
504+version = "0.20.0"
505+source = "registry+https://github.com/rust-lang/crates.io-index"
506+checksum = "011144ef75ba95b665b1e6b03f3b7bbe9aa85d55472abb1d21e64813dac1c0a4"
507+dependencies = [
508+ "bevy_macro_utils",
509+ "quote",
510+ "syn 2.0.119",
511+]
512+
513+[[package]]
514+name = "bevy_anti_alias"
515+version = "0.20.0"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "f4df27fadf88e6ff72bf63a5e80e3921536eabfcde3196db347c31b6bbb39606"
518+dependencies = [
519+ "bevy_app",
520+ "bevy_asset",
521+ "bevy_camera",
522+ "bevy_core_pipeline",
523+ "bevy_derive",
524+ "bevy_diagnostic",
525+ "bevy_ecs",
526+ "bevy_extract",
527+ "bevy_image",
528+ "bevy_math",
529+ "bevy_reflect",
530+ "bevy_render",
531+ "bevy_shader",
532+ "bevy_utils",
533+ "tracing",
534+]
535+
536+[[package]]
537+name = "bevy_app"
538+version = "0.20.0"
539+source = "registry+https://github.com/rust-lang/crates.io-index"
540+checksum = "a2489da2972d57cccd19060d7faa44c4c4cfb296a657c84ee6ab8bde2b1c0115"
541+dependencies = [
542+ "bevy_derive",
543+ "bevy_ecs",
544+ "bevy_platform",
545+ "bevy_reflect",
546+ "bevy_tasks",
547+ "bevy_utils",
548+ "console_error_panic_hook",
549+ "ctrlc",
550+ "downcast-rs 2.0.2",
551+ "log",
552+ "thiserror 2.0.21",
553+ "variadics_please",
554+ "wasm-bindgen",
555+ "web-sys",
556+]
557+
558+[[package]]
559+name = "bevy_asset"
560+version = "0.20.0"
561+source = "registry+https://github.com/rust-lang/crates.io-index"
562+checksum = "b88b3767a2c3f5a017b2febca08a670819ea2acb46846e4d8cd02980aeb0ed3e"
563+dependencies = [
564+ "async-broadcast",
565+ "async-channel",
566+ "async-fs",
567+ "async-io",
568+ "async-lock",
569+ "atomicow",
570+ "bevy_android",
571+ "bevy_app",
572+ "bevy_asset_macros",
573+ "bevy_diagnostic",
574+ "bevy_ecs",
575+ "bevy_platform",
576+ "bevy_reflect",
577+ "bevy_tasks",
578+ "bevy_utils",
579+ "bitflags 2.13.2",
580+ "blake3",
581+ "crossbeam-channel",
582+ "derive_more",
583+ "disqualified",
584+ "downcast-rs 2.0.2",
585+ "either",
586+ "futures-io",
587+ "futures-lite",
588+ "futures-util",
589+ "js-sys",
590+ "ron",
591+ "serde",
592+ "stackfuture",
593+ "thiserror 2.0.21",
594+ "tracing",
595+ "uuid",
596+ "wasm-bindgen",
597+ "wasm-bindgen-futures",
598+ "web-sys",
599+]
600+
601+[[package]]
602+name = "bevy_asset_macros"
603+version = "0.20.0"
604+source = "registry+https://github.com/rust-lang/crates.io-index"
605+checksum = "875b4fd236612744dbd61fb0a77ffde0aee37b8b780cf8a89caa308511c70646"
606+dependencies = [
607+ "bevy_macro_utils",
608+ "proc-macro2",
609+ "quote",
610+ "syn 2.0.119",
611+]
612+
613+[[package]]
614+name = "bevy_audio"
615+version = "0.20.0"
616+source = "registry+https://github.com/rust-lang/crates.io-index"
617+checksum = "fd16f2ac779d6ce5fdcc951c314141d37deff54cef213197872054259fc3a031"
618+dependencies = [
619+ "bevy_app",
620+ "bevy_asset",
621+ "bevy_ecs",
622+ "bevy_math",
623+ "bevy_reflect",
624+ "bevy_transform",
625+ "rodio",
626+ "tracing",
627+]
628+
629+[[package]]
630+name = "bevy_camera"
631+version = "0.20.0"
632+source = "registry+https://github.com/rust-lang/crates.io-index"
633+checksum = "f32c0d8436fb9373dc3b64fa30c3dec51d6a7cfda61de3c70fd1f62f8a903887"
634+dependencies = [
635+ "bevy_app",
636+ "bevy_asset",
637+ "bevy_color",
638+ "bevy_derive",
639+ "bevy_ecs",
640+ "bevy_image",
641+ "bevy_math",
642+ "bevy_mesh",
643+ "bevy_reflect",
644+ "bevy_shape",
645+ "bevy_transform",
646+ "bevy_utils",
647+ "bevy_window",
648+ "derive_more",
649+ "downcast-rs 2.0.2",
650+ "serde",
651+ "smallvec",
652+ "thiserror 2.0.21",
653+ "wgpu-types",
654+]
655+
656+[[package]]
657+name = "bevy_clipboard"
658+version = "0.20.0"
659+source = "registry+https://github.com/rust-lang/crates.io-index"
660+checksum = "f0267b0beafd7e587a1b25b5ce14b271577f5fc1d8fd7828b2b66f0cf5dd649b"
661+dependencies = [
662+ "arboard",
663+ "bevy_app",
664+ "bevy_ecs",
665+ "bevy_log",
666+ "bevy_platform",
667+ "wasm-bindgen",
668+ "wasm-bindgen-futures",
669+ "web-sys",
670+]
671+
672+[[package]]
673+name = "bevy_color"
674+version = "0.20.0"
675+source = "registry+https://github.com/rust-lang/crates.io-index"
676+checksum = "c0e57bfc1a0da1c018235fb98bb0e15ab61f1d0253122020ab6e1450e6cfbcf9"
677+dependencies = [
678+ "bevy_curve",
679+ "bevy_math",
680+ "bevy_reflect",
681+ "bytemuck",
682+ "derive_more",
683+ "encase",
684+ "serde",
685+ "thiserror 2.0.21",
686+ "wgpu-types",
687+]
688+
689+[[package]]
690+name = "bevy_core_pipeline"
691+version = "0.20.0"
692+source = "registry+https://github.com/rust-lang/crates.io-index"
693+checksum = "a4a077b301be4b373a4cb224c54988e1f8385ecf3ab9e60bd3727a65b3d6901a"
694+dependencies = [
695+ "bevy_app",
696+ "bevy_asset",
697+ "bevy_camera",
698+ "bevy_color",
699+ "bevy_derive",
700+ "bevy_diagnostic",
701+ "bevy_ecs",
702+ "bevy_extract",
703+ "bevy_image",
704+ "bevy_light",
705+ "bevy_log",
706+ "bevy_math",
707+ "bevy_platform",
708+ "bevy_reflect",
709+ "bevy_render",
710+ "bevy_shader",
711+ "bevy_transform",
712+ "bevy_utils",
713+ "bevy_window",
714+ "bitflags 2.13.2",
715+ "indexmap",
716+ "nonmax",
717+]
718+
719+[[package]]
720+name = "bevy_curve"
721+version = "0.20.0"
722+source = "registry+https://github.com/rust-lang/crates.io-index"
723+checksum = "21ae28ed95c1c8a1bfc8930471840ee5a4b99b6b31138b17598e7ee6f4291b64"
724+dependencies = [
725+ "approx",
726+ "bevy_math",
727+ "bevy_reflect",
728+ "itertools 0.14.0",
729+ "serde",
730+ "thiserror 2.0.21",
731+ "variadics_please",
732+]
733+
734+[[package]]
735+name = "bevy_derive"
736+version = "0.20.0"
737+source = "registry+https://github.com/rust-lang/crates.io-index"
738+checksum = "fd59e9e600d792e60df17b4d52719b28c288bf047884ac89ad29d9c7a6592d2c"
739+dependencies = [
740+ "bevy_macro_utils",
741+ "quote",
742+ "syn 2.0.119",
743+]
744+
745+[[package]]
746+name = "bevy_dev_tools"
747+version = "0.20.0"
748+source = "registry+https://github.com/rust-lang/crates.io-index"
749+checksum = "c166963d672c45b34cf71f2cab3df627ec61f7ed06df451f008c9519f87e2e34"
750+dependencies = [
751+ "bevy_animation",
752+ "bevy_app",
753+ "bevy_asset",
754+ "bevy_audio",
755+ "bevy_camera",
756+ "bevy_color",
757+ "bevy_diagnostic",
758+ "bevy_ecs",
759+ "bevy_extract",
760+ "bevy_image",
761+ "bevy_input",
762+ "bevy_light",
763+ "bevy_log",
764+ "bevy_math",
765+ "bevy_mesh",
766+ "bevy_picking",
767+ "bevy_platform",
768+ "bevy_reflect",
769+ "bevy_render",
770+ "bevy_shader",
771+ "bevy_sprite",
772+ "bevy_state",
773+ "bevy_text",
774+ "bevy_time",
775+ "bevy_transform",
776+ "bevy_ui",
777+ "bevy_ui_widgets",
778+ "bevy_window",
779+ "bevy_world_serialization",
780+ "tracing",
781+]
782+
783+[[package]]
784+name = "bevy_diagnostic"
785+version = "0.20.0"
786+source = "registry+https://github.com/rust-lang/crates.io-index"
787+checksum = "7f8851dc1b253b350bf941695457007e6e44ad4b8f075bf52a1ef202e6866b6a"
788+dependencies = [
789+ "atomic-waker",
790+ "bevy_app",
791+ "bevy_ecs",
792+ "bevy_platform",
793+ "bevy_tasks",
794+ "bevy_time",
795+ "const-fnv1a-hash",
796+ "log",
797+ "serde",
798+ "sysinfo",
799+]
800+
801+[[package]]
802+name = "bevy_ecs"
803+version = "0.20.0"
804+source = "registry+https://github.com/rust-lang/crates.io-index"
805+checksum = "d5541a1658c5029b39e3ec59c6ecb47ad0a6d85fa083312a5ee2a95d6982a926"
806+dependencies = [
807+ "arrayvec",
808+ "bevy_ecs_macros",
809+ "bevy_platform",
810+ "bevy_ptr",
811+ "bevy_reflect",
812+ "bevy_tasks",
813+ "bevy_utils",
814+ "bitflags 2.13.2",
815+ "bumpalo",
816+ "concurrent-queue",
817+ "derive_more",
818+ "fixedbitset",
819+ "indexmap",
820+ "log",
821+ "nonmax",
822+ "serde",
823+ "slotmap",
824+ "smallvec",
825+ "thiserror 2.0.21",
826+ "variadics_please",
827+]
828+
829+[[package]]
830+name = "bevy_ecs_macro_logic"
831+version = "0.20.0"
832+source = "registry+https://github.com/rust-lang/crates.io-index"
833+checksum = "5197fea7643d2733e8b6d81c3dfa99adad3a754cdfd159c00255cea157b795d7"
834+dependencies = [
835+ "bevy_macro_utils",
836+ "proc-macro2",
837+ "quote",
838+ "syn 2.0.119",
839+]
840+
841+[[package]]
842+name = "bevy_ecs_macros"
843+version = "0.20.0"
844+source = "registry+https://github.com/rust-lang/crates.io-index"
845+checksum = "3dde5305169503c9101404bf8cf17e8351f56fccf5152b8e5d7d7c32dcf1c486"
846+dependencies = [
847+ "bevy_ecs_macro_logic",
848+ "bevy_macro_utils",
849+ "proc-macro2",
850+ "quote",
851+ "syn 2.0.119",
852+]
853+
854+[[package]]
855+name = "bevy_encase_derive"
856+version = "0.20.0"
857+source = "registry+https://github.com/rust-lang/crates.io-index"
858+checksum = "d4e4c4183c39ae8d00e53afeeab66aa71c41b08d82638149f9d485a2a62df569"
859+dependencies = [
860+ "bevy_macro_utils",
861+ "encase_derive_impl",
862+]
863+
864+[[package]]
865+name = "bevy_extract"
866+version = "0.20.0"
867+source = "registry+https://github.com/rust-lang/crates.io-index"
868+checksum = "08e27fc07ef8e3ab7c217fed1b171d42c90f3b6e4f7f526ffa28f9006ac49aa4"
869+dependencies = [
870+ "bevy_app",
871+ "bevy_camera",
872+ "bevy_derive",
873+ "bevy_ecs",
874+ "bevy_extract_macros",
875+ "bevy_log",
876+ "bevy_platform",
877+ "bevy_reflect",
878+ "bevy_time",
879+ "bevy_utils",
880+]
881+
882+[[package]]
883+name = "bevy_extract_macros"
884+version = "0.20.0"
885+source = "registry+https://github.com/rust-lang/crates.io-index"
886+checksum = "3a5c67e8c55ef35c65295e8cb614eda169780e21e2748f6df470d3bff21849a3"
887+dependencies = [
888+ "bevy_macro_utils",
889+ "proc-macro2",
890+ "quote",
891+ "syn 2.0.119",
892+]
893+
894+[[package]]
895+name = "bevy_feathers"
896+version = "0.20.0"
897+source = "registry+https://github.com/rust-lang/crates.io-index"
898+checksum = "9c4566f226580b5d852e3fa4fdb821e45367f598c0c6090896d686e446fa91f4"
899+dependencies = [
900+ "accesskit",
901+ "bevy_a11y",
902+ "bevy_app",
903+ "bevy_asset",
904+ "bevy_camera",
905+ "bevy_color",
906+ "bevy_derive",
907+ "bevy_ecs",
908+ "bevy_input",
909+ "bevy_input_focus",
910+ "bevy_log",
911+ "bevy_math",
912+ "bevy_picking",
913+ "bevy_platform",
914+ "bevy_reflect",
915+ "bevy_render",
916+ "bevy_scene",
917+ "bevy_shader",
918+ "bevy_text",
919+ "bevy_ui",
920+ "bevy_ui_render",
921+ "bevy_ui_widgets",
922+ "bevy_window",
923+ "smol_str",
924+]
925+
926+[[package]]
927+name = "bevy_gilrs"
928+version = "0.20.0"
929+source = "registry+https://github.com/rust-lang/crates.io-index"
930+checksum = "c7a8c6c22d01a7b2e949ac1be313fffca62a23ae0b802a884f009e6dc70a4cea"
931+dependencies = [
932+ "bevy_app",
933+ "bevy_ecs",
934+ "bevy_input",
935+ "bevy_platform",
936+ "bevy_time",
937+ "gilrs",
938+ "thiserror 2.0.21",
939+ "tracing",
940+]
941+
942+[[package]]
943+name = "bevy_gizmos"
944+version = "0.20.0"
945+source = "registry+https://github.com/rust-lang/crates.io-index"
946+checksum = "dfc92f635ec5eaef5733afee45e6a0452e8c65de42d818dc7269dc5265087689"
947+dependencies = [
948+ "bevy_app",
949+ "bevy_asset",
950+ "bevy_camera",
951+ "bevy_color",
952+ "bevy_curve",
953+ "bevy_ecs",
954+ "bevy_gizmos_macros",
955+ "bevy_input",
956+ "bevy_log",
957+ "bevy_math",
958+ "bevy_mesh",
959+ "bevy_reflect",
960+ "bevy_shape",
961+ "bevy_time",
962+ "bevy_transform",
963+ "bevy_utils",
964+ "bevy_window",
965+]
966+
967+[[package]]
968+name = "bevy_gizmos_macros"
969+version = "0.20.0"
970+source = "registry+https://github.com/rust-lang/crates.io-index"
971+checksum = "501e72c4ac31caef17ef9e627dee212d2107b95402a891ec6f0fc4107dd0cdf4"
972+dependencies = [
973+ "bevy_macro_utils",
974+ "quote",
975+ "syn 2.0.119",
976+]
977+
978+[[package]]
979+name = "bevy_gizmos_render"
980+version = "0.20.0"
981+source = "registry+https://github.com/rust-lang/crates.io-index"
982+checksum = "42f5be0c9f114dc9b2c929076517d088e059b971edec5dfff4d5a225df6796df"
983+dependencies = [
984+ "bevy_app",
985+ "bevy_asset",
986+ "bevy_camera",
987+ "bevy_color",
988+ "bevy_core_pipeline",
989+ "bevy_ecs",
990+ "bevy_extract",
991+ "bevy_gizmos",
992+ "bevy_image",
993+ "bevy_log",
994+ "bevy_material",
995+ "bevy_math",
996+ "bevy_mesh",
997+ "bevy_pbr",
998+ "bevy_reflect",
999+ "bevy_render",
1000+ "bevy_shader",
1001+ "bevy_shape",
1002+ "bevy_sprite_render",
1003+ "bevy_transform",
1004+ "bevy_utils",
1005+ "bytemuck",
1006+ "tracing",
1007+]
1008+
1009+[[package]]
1010+name = "bevy_gltf"
1011+version = "0.20.0"
1012+source = "registry+https://github.com/rust-lang/crates.io-index"
1013+checksum = "2b5c4e1779a522f706853f75fc11107a032d4e4f92d26fbef4c36e825d00afdf"
1014+dependencies = [
1015+ "async-lock",
1016+ "base64",
1017+ "bevy_animation",
1018+ "bevy_app",
1019+ "bevy_asset",
1020+ "bevy_camera",
1021+ "bevy_color",
1022+ "bevy_curve",
1023+ "bevy_ecs",
1024+ "bevy_image",
1025+ "bevy_light",
1026+ "bevy_material",
1027+ "bevy_math",
1028+ "bevy_mesh",
1029+ "bevy_platform",
1030+ "bevy_reflect",
1031+ "bevy_tasks",
1032+ "bevy_transform",
1033+ "bevy_world_serialization",
1034+ "fixedbitset",
1035+ "gltf",
1036+ "itertools 0.14.0",
1037+ "percent-encoding",
1038+ "serde",
1039+ "serde_json",
1040+ "smallvec",
1041+ "thiserror 2.0.21",
1042+ "tracing",
1043+ "wgpu-types",
1044+]
1045+
1046+[[package]]
1047+name = "bevy_image"
1048+version = "0.20.0"
1049+source = "registry+https://github.com/rust-lang/crates.io-index"
1050+checksum = "bb818dd8d705809d54adea08e346edce81a51ddbf06406ddf12a72ee467a3855"
1051+dependencies = [
1052+ "bevy_app",
1053+ "bevy_asset",
1054+ "bevy_color",
1055+ "bevy_ecs",
1056+ "bevy_math",
1057+ "bevy_platform",
1058+ "bevy_reflect",
1059+ "bevy_utils",
1060+ "bitflags 2.13.2",
1061+ "bytemuck",
1062+ "futures-lite",
1063+ "guillotiere",
1064+ "half",
1065+ "image",
1066+ "ktx2",
1067+ "rectangle-pack",
1068+ "ruzstd",
1069+ "serde",
1070+ "thiserror 2.0.21",
1071+ "tracing",
1072+ "wgpu-types",
1073+]
1074+
1075+[[package]]
1076+name = "bevy_input"
1077+version = "0.20.0"
1078+source = "registry+https://github.com/rust-lang/crates.io-index"
1079+checksum = "261ca5cc8a0bf228bfe4e841570db18a3ab1d034ce089772b8ec49c163ae74ea"
1080+dependencies = [
1081+ "bevy_app",
1082+ "bevy_ecs",
1083+ "bevy_math",
1084+ "bevy_platform",
1085+ "bevy_reflect",
1086+ "derive_more",
1087+ "log",
1088+ "smol_str",
1089+ "thiserror 2.0.21",
1090+]
1091+
1092+[[package]]
1093+name = "bevy_input_focus"
1094+version = "0.20.0"
1095+source = "registry+https://github.com/rust-lang/crates.io-index"
1096+checksum = "83c81d369d0ab3ec17ba14bab1e07da7cacf3751a3104a93b1a3cd99d887887b"
1097+dependencies = [
1098+ "bevy_app",
1099+ "bevy_camera",
1100+ "bevy_ecs",
1101+ "bevy_input",
1102+ "bevy_math",
1103+ "bevy_picking",
1104+ "bevy_reflect",
1105+ "bevy_window",
1106+ "log",
1107+ "thiserror 2.0.21",
1108+]
1109+
1110+[[package]]
1111+name = "bevy_internal"
1112+version = "0.20.0"
1113+source = "registry+https://github.com/rust-lang/crates.io-index"
1114+checksum = "a4ed1cb58d1761426a077a8aff55e6a2e0cdfd19e411211d4b0217409330bb84"
1115+dependencies = [
1116+ "bevy_a11y",
1117+ "bevy_android",
1118+ "bevy_animation",
1119+ "bevy_anti_alias",
1120+ "bevy_app",
1121+ "bevy_asset",
1122+ "bevy_audio",
1123+ "bevy_camera",
1124+ "bevy_clipboard",
1125+ "bevy_color",
1126+ "bevy_core_pipeline",
1127+ "bevy_curve",
1128+ "bevy_derive",
1129+ "bevy_dev_tools",
1130+ "bevy_diagnostic",
1131+ "bevy_ecs",
1132+ "bevy_extract",
1133+ "bevy_feathers",
1134+ "bevy_gilrs",
1135+ "bevy_gizmos",
1136+ "bevy_gizmos_render",
1137+ "bevy_gltf",
1138+ "bevy_image",
1139+ "bevy_input",
1140+ "bevy_input_focus",
1141+ "bevy_light",
1142+ "bevy_log",
1143+ "bevy_material",
1144+ "bevy_math",
1145+ "bevy_mesh",
1146+ "bevy_pbr",
1147+ "bevy_picking",
1148+ "bevy_platform",
1149+ "bevy_post_process",
1150+ "bevy_ptr",
1151+ "bevy_reflect",
1152+ "bevy_render",
1153+ "bevy_scene",
1154+ "bevy_shader",
1155+ "bevy_shape",
1156+ "bevy_sprite",
1157+ "bevy_sprite_render",
1158+ "bevy_state",
1159+ "bevy_tasks",
1160+ "bevy_text",
1161+ "bevy_time",
1162+ "bevy_transform",
1163+ "bevy_ui",
1164+ "bevy_ui_render",
1165+ "bevy_ui_widgets",
1166+ "bevy_utils",
1167+ "bevy_window",
1168+ "bevy_winit",
1169+ "bevy_world_serialization",
1170+]
1171+
1172+[[package]]
1173+name = "bevy_light"
1174+version = "0.20.0"
1175+source = "registry+https://github.com/rust-lang/crates.io-index"
1176+checksum = "529d5ec7db637bbce7d016b2bfd0798362ad67118de8e9d37aaac24ecb3337cd"
1177+dependencies = [
1178+ "bevy_app",
1179+ "bevy_asset",
1180+ "bevy_camera",
1181+ "bevy_color",
1182+ "bevy_curve",
1183+ "bevy_ecs",
1184+ "bevy_gizmos",
1185+ "bevy_image",
1186+ "bevy_log",
1187+ "bevy_math",
1188+ "bevy_mesh",
1189+ "bevy_platform",
1190+ "bevy_reflect",
1191+ "bevy_shape",
1192+ "bevy_transform",
1193+ "bevy_utils",
1194+ "half",
1195+ "smallvec",
1196+ "tracing",
1197+ "wgpu-types",
1198+]
1199+
1200+[[package]]
1201+name = "bevy_log"
1202+version = "0.20.0"
1203+source = "registry+https://github.com/rust-lang/crates.io-index"
1204+checksum = "a87d5152292b0e581a589cffb6b7e83e0afe345279d4126545ce7b786bd8a47a"
1205+dependencies = [
1206+ "android_log-sys",
1207+ "bevy_app",
1208+ "bevy_ecs",
1209+ "bevy_platform",
1210+ "bevy_utils",
1211+ "tracing",
1212+ "tracing-log",
1213+ "tracing-oslog",
1214+ "tracing-subscriber",
1215+ "tracing-wasm",
1216+]
1217+
1218+[[package]]
1219+name = "bevy_macro_utils"
1220+version = "0.20.0"
1221+source = "registry+https://github.com/rust-lang/crates.io-index"
1222+checksum = "c0d03a948df65138e30917d91237797d7e38763135ebacd0f28c891e1a3b2b52"
1223+dependencies = [
1224+ "proc-macro2",
1225+ "quote",
1226+ "syn 2.0.119",
1227+ "toml_edit",
1228+]
1229+
1230+[[package]]
1231+name = "bevy_material"
1232+version = "0.20.0"
1233+source = "registry+https://github.com/rust-lang/crates.io-index"
1234+checksum = "5be7ee4b2f4764e8d58a59afb47a3ba8bae36f955f409f08c658cace2808ef40"
1235+dependencies = [
1236+ "bevy_asset",
1237+ "bevy_derive",
1238+ "bevy_ecs",
1239+ "bevy_material_macros",
1240+ "bevy_mesh",
1241+ "bevy_platform",
1242+ "bevy_reflect",
1243+ "bevy_shader",
1244+ "bevy_utils",
1245+ "encase",
1246+ "smallvec",
1247+ "thiserror 2.0.21",
1248+ "tracing",
1249+ "variadics_please",
1250+ "wgpu-types",
1251+]
1252+
1253+[[package]]
1254+name = "bevy_material_macros"
1255+version = "0.20.0"
1256+source = "registry+https://github.com/rust-lang/crates.io-index"
1257+checksum = "70551fa201e1416ab44968631b7ce6320c194acfdb652a1971ec6882af122333"
1258+dependencies = [
1259+ "bevy_macro_utils",
1260+ "quote",
1261+ "syn 2.0.119",
1262+]
1263+
1264+[[package]]
1265+name = "bevy_math"
1266+version = "0.20.0"
1267+source = "registry+https://github.com/rust-lang/crates.io-index"
1268+checksum = "598cbdcec4d0f0d966905996240ac76f77a644c583f95fb612d4f59f5f649038"
1269+dependencies = [
1270+ "approx",
1271+ "bevy_reflect",
1272+ "derive_more",
1273+ "glam",
1274+ "libm",
1275+ "rand",
1276+ "serde",
1277+ "thiserror 2.0.21",
1278+ "variadics_please",
1279+]
1280+
1281+[[package]]
1282+name = "bevy_mesh"
1283+version = "0.20.0"
1284+source = "registry+https://github.com/rust-lang/crates.io-index"
1285+checksum = "09358ac9a3ede5855568c10eaba6bcf126bf86639e786fb21b413457ebec5f26"
1286+dependencies = [
1287+ "bevy_app",
1288+ "bevy_asset",
1289+ "bevy_derive",
1290+ "bevy_ecs",
1291+ "bevy_encase_derive",
1292+ "bevy_math",
1293+ "bevy_mikktspace",
1294+ "bevy_platform",
1295+ "bevy_reflect",
1296+ "bevy_shape",
1297+ "bevy_transform",
1298+ "bitflags 2.13.2",
1299+ "bytemuck",
1300+ "derive_more",
1301+ "encase",
1302+ "glam",
1303+ "half",
1304+ "hexasphere",
1305+ "serde",
1306+ "thiserror 2.0.21",
1307+ "tracing",
1308+ "wgpu-types",
1309+]
1310+
1311+[[package]]
1312+name = "bevy_mikktspace"
1313+version = "1.0.0"
1314+source = "registry+https://github.com/rust-lang/crates.io-index"
1315+checksum = "bff34eb29ff4b8a8688bc7299f14fb6b597461ca80fec03ed7d22939ab33e48f"
1316+
1317+[[package]]
1318+name = "bevy_pbr"
1319+version = "0.20.0"
1320+source = "registry+https://github.com/rust-lang/crates.io-index"
1321+checksum = "fb760932d1e683e7c00011f5c99e4e1cc893646a3a7b7224da6daf9bfa94853d"
1322+dependencies = [
1323+ "arrayvec",
1324+ "bevy_app",
1325+ "bevy_asset",
1326+ "bevy_camera",
1327+ "bevy_color",
1328+ "bevy_core_pipeline",
1329+ "bevy_derive",
1330+ "bevy_diagnostic",
1331+ "bevy_ecs",
1332+ "bevy_extract",
1333+ "bevy_gltf",
1334+ "bevy_image",
1335+ "bevy_light",
1336+ "bevy_log",
1337+ "bevy_material",
1338+ "bevy_math",
1339+ "bevy_mesh",
1340+ "bevy_platform",
1341+ "bevy_reflect",
1342+ "bevy_render",
1343+ "bevy_shader",
1344+ "bevy_shape",
1345+ "bevy_tasks",
1346+ "bevy_transform",
1347+ "bevy_utils",
1348+ "bitflags 2.13.2",
1349+ "bytemuck",
1350+ "derive_more",
1351+ "fixedbitset",
1352+ "indexmap",
1353+ "nonmax",
1354+ "offset-allocator",
1355+ "smallvec",
1356+ "static_assertions",
1357+ "thiserror 2.0.21",
1358+ "tracing",
1359+ "wgpu-types",
1360+]
1361+
1362+[[package]]
1363+name = "bevy_picking"
1364+version = "0.20.0"
1365+source = "registry+https://github.com/rust-lang/crates.io-index"
1366+checksum = "47a04fb644c62a57a4f338f5cd8b61519c569139742eafe87dccb523e4b7cf2e"
1367+dependencies = [
1368+ "bevy_app",
1369+ "bevy_asset",
1370+ "bevy_camera",
1371+ "bevy_derive",
1372+ "bevy_ecs",
1373+ "bevy_input",
1374+ "bevy_math",
1375+ "bevy_mesh",
1376+ "bevy_platform",
1377+ "bevy_reflect",
1378+ "bevy_shape",
1379+ "bevy_time",
1380+ "bevy_transform",
1381+ "bevy_window",
1382+ "crossbeam-channel",
1383+ "tracing",
1384+ "uuid",
1385+]
1386+
1387+[[package]]
1388+name = "bevy_platform"
1389+version = "0.20.0"
1390+source = "registry+https://github.com/rust-lang/crates.io-index"
1391+checksum = "000bc467d1b344b6609fcf217a9b08d349d49c8e85dc4179fb7656f2b6e3db47"
1392+dependencies = [
1393+ "bytemuck",
1394+ "critical-section",
1395+ "foldhash 0.2.0",
1396+ "futures-channel",
1397+ "futures-lite",
1398+ "hashbrown 0.16.1",
1399+ "js-sys",
1400+ "portable-atomic",
1401+ "portable-atomic-util",
1402+ "serde",
1403+ "spin",
1404+ "wasm-bindgen",
1405+ "wasm-bindgen-futures",
1406+ "web-time",
1407+ "windows-sys 0.61.2",
1408+]
1409+
1410+[[package]]
1411+name = "bevy_post_process"
1412+version = "0.20.0"
1413+source = "registry+https://github.com/rust-lang/crates.io-index"
1414+checksum = "d684c2ac93e94d9b7ba767ce02ea435ef244677a24746241726de2aa552ba1a4"
1415+dependencies = [
1416+ "bevy_app",
1417+ "bevy_asset",
1418+ "bevy_camera",
1419+ "bevy_color",
1420+ "bevy_core_pipeline",
1421+ "bevy_curve",
1422+ "bevy_derive",
1423+ "bevy_ecs",
1424+ "bevy_extract",
1425+ "bevy_image",
1426+ "bevy_math",
1427+ "bevy_platform",
1428+ "bevy_reflect",
1429+ "bevy_render",
1430+ "bevy_shader",
1431+ "bevy_utils",
1432+ "smallvec",
1433+ "thiserror 2.0.21",
1434+ "tracing",
1435+]
1436+
1437+[[package]]
1438+name = "bevy_ptr"
1439+version = "0.20.0"
1440+source = "registry+https://github.com/rust-lang/crates.io-index"
1441+checksum = "41935a00c02004753bd7ed5094754397800b3f673bf15553bb007b06216872d5"
1442+
1443+[[package]]
1444+name = "bevy_reflect"
1445+version = "0.20.0"
1446+source = "registry+https://github.com/rust-lang/crates.io-index"
1447+checksum = "46eecc733575b873deedcc37639e36290092388657091b3321fa6e073e7818e6"
1448+dependencies = [
1449+ "assert_type_match",
1450+ "bevy_platform",
1451+ "bevy_ptr",
1452+ "bevy_reflect_derive",
1453+ "bevy_utils",
1454+ "derive_more",
1455+ "disqualified",
1456+ "downcast-rs 2.0.2",
1457+ "erased-serde",
1458+ "foldhash 0.2.0",
1459+ "glam",
1460+ "indexmap",
1461+ "inventory",
1462+ "petgraph",
1463+ "serde",
1464+ "smallvec",
1465+ "smol_str",
1466+ "thiserror 2.0.21",
1467+ "uuid",
1468+ "variadics_please",
1469+ "wgpu-types",
1470+]
1471+
1472+[[package]]
1473+name = "bevy_reflect_derive"
1474+version = "0.20.0"
1475+source = "registry+https://github.com/rust-lang/crates.io-index"
1476+checksum = "dfaa1e315676c625ed8d30ba8a671ebf917cad6355320295b9802a8cbc06853b"
1477+dependencies = [
1478+ "bevy_macro_utils",
1479+ "indexmap",
1480+ "proc-macro2",
1481+ "quote",
1482+ "syn 2.0.119",
1483+ "uuid",
1484+]
1485+
1486+[[package]]
1487+name = "bevy_render"
1488+version = "0.20.0"
1489+source = "registry+https://github.com/rust-lang/crates.io-index"
1490+checksum = "5f438a921fd3ef82cc09ccf5e0cd8f1214dcae6286890f9d4acba0409d9a61a8"
1491+dependencies = [
1492+ "async-channel",
1493+ "bevy_app",
1494+ "bevy_asset",
1495+ "bevy_camera",
1496+ "bevy_color",
1497+ "bevy_derive",
1498+ "bevy_diagnostic",
1499+ "bevy_ecs",
1500+ "bevy_encase_derive",
1501+ "bevy_extract",
1502+ "bevy_extract_macros",
1503+ "bevy_image",
1504+ "bevy_log",
1505+ "bevy_material",
1506+ "bevy_material_macros",
1507+ "bevy_math",
1508+ "bevy_mesh",
1509+ "bevy_platform",
1510+ "bevy_reflect",
1511+ "bevy_render_macros",
1512+ "bevy_shader",
1513+ "bevy_shape",
1514+ "bevy_tasks",
1515+ "bevy_time",
1516+ "bevy_transform",
1517+ "bevy_utils",
1518+ "bevy_window",
1519+ "bitflags 2.13.2",
1520+ "bytemuck",
1521+ "derive_more",
1522+ "downcast-rs 2.0.2",
1523+ "encase",
1524+ "glam",
1525+ "image",
1526+ "indexmap",
1527+ "itertools 0.14.0",
1528+ "js-sys",
1529+ "nonmax",
1530+ "offset-allocator",
1531+ "send_wrapper",
1532+ "smallvec",
1533+ "static_assertions",
1534+ "thiserror 2.0.21",
1535+ "tracing",
1536+ "variadics_please",
1537+ "wasm-bindgen",
1538+ "weak-table",
1539+ "web-sys",
1540+ "wgpu",
1541+ "wgpu-types",
1542+]
1543+
1544+[[package]]
1545+name = "bevy_render_macros"
1546+version = "0.20.0"
1547+source = "registry+https://github.com/rust-lang/crates.io-index"
1548+checksum = "119ca6d445eba5c9976c658f29bac854094b27c27624aa92c4d9668c319618d0"
1549+dependencies = [
1550+ "bevy_extract_macros",
1551+ "bevy_macro_utils",
1552+ "proc-macro2",
1553+ "quote",
1554+ "syn 2.0.119",
1555+]
1556+
1557+[[package]]
1558+name = "bevy_scene"
1559+version = "0.20.0"
1560+source = "registry+https://github.com/rust-lang/crates.io-index"
1561+checksum = "98c4b1677c948e4c1453883f4441136003c53fd9caa44e0f7d78b37618bdb9ad"
1562+dependencies = [
1563+ "bevy_app",
1564+ "bevy_asset",
1565+ "bevy_derive",
1566+ "bevy_ecs",
1567+ "bevy_log",
1568+ "bevy_platform",
1569+ "bevy_reflect",
1570+ "bevy_scene_macros",
1571+ "bevy_utils",
1572+ "smallvec",
1573+ "thiserror 2.0.21",
1574+ "tracing",
1575+ "variadics_please",
1576+]
1577+
1578+[[package]]
1579+name = "bevy_scene_macros"
1580+version = "0.20.0"
1581+source = "registry+https://github.com/rust-lang/crates.io-index"
1582+checksum = "d4da846d8418ca6e38943707c88075a4a0b8f6eea0fd286d33a024d0257439d0"
1583+dependencies = [
1584+ "bevy_ecs_macro_logic",
1585+ "bevy_macro_utils",
1586+ "proc-macro2",
1587+ "quote",
1588+ "syn 2.0.119",
1589+]
1590+
1591+[[package]]
1592+name = "bevy_shader"
1593+version = "0.20.0"
1594+source = "registry+https://github.com/rust-lang/crates.io-index"
1595+checksum = "c2becafd54079da13835d6a42fc743e305d6270c27a91de613afe6e3f4b5de19"
1596+dependencies = [
1597+ "bevy_asset",
1598+ "bevy_platform",
1599+ "bevy_reflect",
1600+ "bevy_utils",
1601+ "serde",
1602+ "thiserror 2.0.21",
1603+ "tracing",
1604+ "wesl",
1605+ "wgpu-types",
1606+]
1607+
1608+[[package]]
1609+name = "bevy_shape"
1610+version = "0.20.0"
1611+source = "registry+https://github.com/rust-lang/crates.io-index"
1612+checksum = "aa8b6096ad1ec7dfe1af8e51d7cfa7de1a9e0a3bd02be58a061092c5e1ff1eb1"
1613+dependencies = [
1614+ "arrayvec",
1615+ "bevy_math",
1616+ "bevy_reflect",
1617+ "derive_more",
1618+ "rand",
1619+ "rand_distr",
1620+ "serde",
1621+ "thiserror 2.0.21",
1622+]
1623+
1624+[[package]]
1625+name = "bevy_sprite"
1626+version = "0.20.0"
1627+source = "registry+https://github.com/rust-lang/crates.io-index"
1628+checksum = "24dc4f69160513952a1969a3df5b4a2c729acfe0caf773854acea4a8c71f0918"
1629+dependencies = [
1630+ "bevy_app",
1631+ "bevy_asset",
1632+ "bevy_camera",
1633+ "bevy_color",
1634+ "bevy_derive",
1635+ "bevy_ecs",
1636+ "bevy_image",
1637+ "bevy_log",
1638+ "bevy_math",
1639+ "bevy_mesh",
1640+ "bevy_picking",
1641+ "bevy_reflect",
1642+ "bevy_text",
1643+ "bevy_transform",
1644+ "bevy_window",
1645+ "radsort",
1646+ "tracing",
1647+ "wgpu-types",
1648+]
1649+
1650+[[package]]
1651+name = "bevy_sprite_render"
1652+version = "0.20.0"
1653+source = "registry+https://github.com/rust-lang/crates.io-index"
1654+checksum = "8918649806697740b61d3fd0559cb8c7de2ade5046aacf8abbef20e49ea1de0c"
1655+dependencies = [
1656+ "bevy_app",
1657+ "bevy_asset",
1658+ "bevy_camera",
1659+ "bevy_color",
1660+ "bevy_core_pipeline",
1661+ "bevy_derive",
1662+ "bevy_ecs",
1663+ "bevy_extract",
1664+ "bevy_image",
1665+ "bevy_material",
1666+ "bevy_math",
1667+ "bevy_mesh",
1668+ "bevy_platform",
1669+ "bevy_reflect",
1670+ "bevy_render",
1671+ "bevy_shader",
1672+ "bevy_shape",
1673+ "bevy_sprite",
1674+ "bevy_text",
1675+ "bevy_transform",
1676+ "bevy_utils",
1677+ "bitflags 2.13.2",
1678+ "bytemuck",
1679+ "derive_more",
1680+ "fixedbitset",
1681+ "nonmax",
1682+ "smallvec",
1683+ "static_assertions",
1684+ "tracing",
1685+]
1686+
1687+[[package]]
1688+name = "bevy_state"
1689+version = "0.20.0"
1690+source = "registry+https://github.com/rust-lang/crates.io-index"
1691+checksum = "09292e08e1eb34d2dd915630fb3c04ba75220c7819943c9f213d3a5f9a8be1e8"
1692+dependencies = [
1693+ "bevy_app",
1694+ "bevy_ecs",
1695+ "bevy_platform",
1696+ "bevy_reflect",
1697+ "bevy_state_macros",
1698+ "bevy_utils",
1699+ "log",
1700+ "variadics_please",
1701+]
1702+
1703+[[package]]
1704+name = "bevy_state_macros"
1705+version = "0.20.0"
1706+source = "registry+https://github.com/rust-lang/crates.io-index"
1707+checksum = "fec1a8f6a253e39ddf7e447b1b9286caacb205ed8e619e6fb9a2e010d58dd04b"
1708+dependencies = [
1709+ "bevy_macro_utils",
1710+ "quote",
1711+ "syn 2.0.119",
1712+]
1713+
1714+[[package]]
1715+name = "bevy_tasks"
1716+version = "0.20.0"
1717+source = "registry+https://github.com/rust-lang/crates.io-index"
1718+checksum = "fbd8116f12dc50bde3758a72fba85e1f4c00e6c66d0ad58bdc46c0c0690829a8"
1719+dependencies = [
1720+ "async-channel",
1721+ "async-executor",
1722+ "async-task",
1723+ "atomic-waker",
1724+ "bevy_platform",
1725+ "concurrent-queue",
1726+ "crossbeam-queue",
1727+ "derive_more",
1728+ "futures-lite",
1729+ "heapless",
1730+ "web-task",
1731+]
1732+
1733+[[package]]
1734+name = "bevy_text"
1735+version = "0.20.0"
1736+source = "registry+https://github.com/rust-lang/crates.io-index"
1737+checksum = "119d2b37ce3f5ea5a5b9092a7c9eec8d3734de62592d2869bd1d925976f34d05"
1738+dependencies = [
1739+ "bevy_app",
1740+ "bevy_asset",
1741+ "bevy_clipboard",
1742+ "bevy_color",
1743+ "bevy_derive",
1744+ "bevy_ecs",
1745+ "bevy_image",
1746+ "bevy_log",
1747+ "bevy_math",
1748+ "bevy_platform",
1749+ "bevy_reflect",
1750+ "bevy_utils",
1751+ "parley",
1752+ "serde",
1753+ "smallvec",
1754+ "smol_str",
1755+ "swash",
1756+ "sys-locale",
1757+ "thiserror 2.0.21",
1758+ "tracing",
1759+ "wgpu-types",
1760+]
1761+
1762+[[package]]
1763+name = "bevy_time"
1764+version = "0.20.0"
1765+source = "registry+https://github.com/rust-lang/crates.io-index"
1766+checksum = "13901174b792bb7848d8e088075f0009ea409b99179934c0d5bdd2b95622694e"
1767+dependencies = [
1768+ "bevy_app",
1769+ "bevy_ecs",
1770+ "bevy_platform",
1771+ "bevy_reflect",
1772+ "crossbeam-channel",
1773+ "log",
1774+ "serde",
1775+]
1776+
1777+[[package]]
1778+name = "bevy_transform"
1779+version = "0.20.0"
1780+source = "registry+https://github.com/rust-lang/crates.io-index"
1781+checksum = "83379023d77a0739569a5bcb859eed652781a1b3271e94a86dfbb56fc5d067e0"
1782+dependencies = [
1783+ "bevy_app",
1784+ "bevy_ecs",
1785+ "bevy_math",
1786+ "bevy_reflect",
1787+ "bevy_tasks",
1788+ "bevy_utils",
1789+ "derive_more",
1790+ "serde",
1791+ "thiserror 2.0.21",
1792+]
1793+
1794+[[package]]
1795+name = "bevy_ui"
1796+version = "0.20.0"
1797+source = "registry+https://github.com/rust-lang/crates.io-index"
1798+checksum = "7926fba78f133376db0cba73a054db6931952379b5bfdc63f2fe9ba0c3b96c39"
1799+dependencies = [
1800+ "accesskit",
1801+ "bevy_a11y",
1802+ "bevy_app",
1803+ "bevy_asset",
1804+ "bevy_camera",
1805+ "bevy_color",
1806+ "bevy_derive",
1807+ "bevy_ecs",
1808+ "bevy_image",
1809+ "bevy_input",
1810+ "bevy_input_focus",
1811+ "bevy_log",
1812+ "bevy_math",
1813+ "bevy_picking",
1814+ "bevy_platform",
1815+ "bevy_reflect",
1816+ "bevy_sprite",
1817+ "bevy_text",
1818+ "bevy_time",
1819+ "bevy_transform",
1820+ "bevy_utils",
1821+ "bevy_window",
1822+ "derive_more",
1823+ "parley",
1824+ "smallvec",
1825+ "swash",
1826+ "taffy",
1827+ "thiserror 2.0.21",
1828+ "tracing",
1829+ "uuid",
1830+]
1831+
1832+[[package]]
1833+name = "bevy_ui_render"
1834+version = "0.20.0"
1835+source = "registry+https://github.com/rust-lang/crates.io-index"
1836+checksum = "620b51b51eb8e7d8b2362ba96263142829560d9aa254e2f28032570667c6b0fb"
1837+dependencies = [
1838+ "bevy_a11y",
1839+ "bevy_app",
1840+ "bevy_asset",
1841+ "bevy_camera",
1842+ "bevy_color",
1843+ "bevy_core_pipeline",
1844+ "bevy_derive",
1845+ "bevy_ecs",
1846+ "bevy_extract",
1847+ "bevy_image",
1848+ "bevy_input_focus",
1849+ "bevy_math",
1850+ "bevy_mesh",
1851+ "bevy_platform",
1852+ "bevy_reflect",
1853+ "bevy_render",
1854+ "bevy_shader",
1855+ "bevy_sprite",
1856+ "bevy_sprite_render",
1857+ "bevy_text",
1858+ "bevy_transform",
1859+ "bevy_ui",
1860+ "bevy_utils",
1861+ "bytemuck",
1862+ "derive_more",
1863+ "indexmap",
1864+ "smallvec",
1865+ "tracing",
1866+]
1867+
1868+[[package]]
1869+name = "bevy_ui_widgets"
1870+version = "0.20.0"
1871+source = "registry+https://github.com/rust-lang/crates.io-index"
1872+checksum = "6442cd402df6a54f0e51ed8c1bd004c8f9c6715d0f8045e33c68ea9aebb1ce16"
1873+dependencies = [
1874+ "accesskit",
1875+ "bevy_a11y",
1876+ "bevy_app",
1877+ "bevy_camera",
1878+ "bevy_ecs",
1879+ "bevy_input",
1880+ "bevy_input_focus",
1881+ "bevy_log",
1882+ "bevy_math",
1883+ "bevy_picking",
1884+ "bevy_platform",
1885+ "bevy_reflect",
1886+ "bevy_text",
1887+ "bevy_time",
1888+ "bevy_ui",
1889+ "bevy_window",
1890+ "parley",
1891+ "smol_str",
1892+ "web-sys",
1893+]
1894+
1895+[[package]]
1896+name = "bevy_utils"
1897+version = "0.20.0"
1898+source = "registry+https://github.com/rust-lang/crates.io-index"
1899+checksum = "5cbd58495039d4e63e6fcfef1242fecab33ffe62b4a5e010467e69e790879812"
1900+dependencies = [
1901+ "async-channel",
1902+ "bevy_platform",
1903+ "disqualified",
1904+ "indexmap",
1905+ "thread_local",
1906+]
1907+
1908+[[package]]
1909+name = "bevy_window"
1910+version = "0.20.0"
1911+source = "registry+https://github.com/rust-lang/crates.io-index"
1912+checksum = "dc9a83f3cbaa04155b5dc9b247819c0e215aee754451a4324b82ddeb80dc53f1"
1913+dependencies = [
1914+ "bevy_app",
1915+ "bevy_asset",
1916+ "bevy_ecs",
1917+ "bevy_image",
1918+ "bevy_input",
1919+ "bevy_math",
1920+ "bevy_platform",
1921+ "bevy_reflect",
1922+ "log",
1923+ "raw-window-handle",
1924+ "serde",
1925+]
1926+
1927+[[package]]
1928+name = "bevy_winit"
1929+version = "0.20.0"
1930+source = "registry+https://github.com/rust-lang/crates.io-index"
1931+checksum = "1ef0a5a55524e793ab13536ef244229fa66a4839fae6564df2aa4b3c13956a82"
1932+dependencies = [
1933+ "accesskit",
1934+ "accesskit_winit",
1935+ "approx",
1936+ "bevy_a11y",
1937+ "bevy_android",
1938+ "bevy_app",
1939+ "bevy_asset",
1940+ "bevy_derive",
1941+ "bevy_ecs",
1942+ "bevy_image",
1943+ "bevy_input",
1944+ "bevy_input_focus",
1945+ "bevy_log",
1946+ "bevy_math",
1947+ "bevy_platform",
1948+ "bevy_reflect",
1949+ "bevy_tasks",
1950+ "bevy_window",
1951+ "bytemuck",
1952+ "js-sys",
1953+ "tracing",
1954+ "wasm-bindgen",
1955+ "web-sys",
1956+ "wgpu-types",
1957+ "winit",
1958+]
1959+
1960+[[package]]
1961+name = "bevy_world_serialization"
1962+version = "0.20.0"
1963+source = "registry+https://github.com/rust-lang/crates.io-index"
1964+checksum = "eef3a23ed3899c88467ce27a0420a1dadeb543981c2e1b9617f6ecf6e5fce1bf"
1965+dependencies = [
1966+ "bevy_app",
1967+ "bevy_asset",
1968+ "bevy_camera",
1969+ "bevy_derive",
1970+ "bevy_ecs",
1971+ "bevy_platform",
1972+ "bevy_reflect",
1973+ "bevy_transform",
1974+ "bevy_utils",
1975+ "derive_more",
1976+ "ron",
1977+ "serde",
1978+ "thiserror 2.0.21",
1979+ "uuid",
1980+]
1981+
1982+[[package]]
1983+name = "bit-set"
1984+version = "0.10.0"
1985+source = "registry+https://github.com/rust-lang/crates.io-index"
1986+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
1987+dependencies = [
1988+ "bit-vec",
1989+]
1990+
1991+[[package]]
1992+name = "bit-vec"
1993+version = "0.9.1"
1994+source = "registry+https://github.com/rust-lang/crates.io-index"
1995+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
1996+
1997+[[package]]
1998+name = "bitflags"
1999+version = "1.3.2"
2000+source = "registry+https://github.com/rust-lang/crates.io-index"
Cargo.tomladded+21 -0
@@ -0,0 +1,21 @@
1+[package]
2+name = "iron_lifeline"
3+version = "0.1.0"
4+edition = "2024"
5+
6+[dependencies]
7+bevy = { version = "0.20", features = ["wav"] }
8+directories = "6.0.0"
9+rand = "0.10"
10+serde = { version = "1.0.229", features = ["derive"] }
11+toml = "1.1.8"
12+
13+[lints.rust]
14+unsafe_code = "forbid"
15+
16+[profile.dev]
17+debug = "line-tables-only"
18+opt-level = 1
19+
20+[profile.dev.package."*"]
21+opt-level = 3
DESIGN.mdadded+35 -0
@@ -0,0 +1,35 @@
1+# Iron Lifeline
2+
3+## Premise
4+You are the railway commander of a fictional nation at war. Fictional countries only, no real history.
5+
6+## Core loop
7+- Lay track between nodes, buy trains, assign routes as ordered stops with load/unload flags.
8+- Trains: Light (fast, small), Heavy (slow, big), Hospital (wounded only).
9+- Factories make ammo, farms make food, the capital and cities make troops.
10+- Front sectors consume ammo, food and troops and produce wounded.
11+- Supply ratio pushes the front line forward or back.
12+- Wounded must reach cities or the capital (hospitals).
13+- Cities eat food. Hungry cities produce less: feed the war or your own people.
14+- Enemy air raids damage track near the front. Damaged track blocks trains until repaired.
15+- A weekly budget arrives from the War Ministry; trains cost upkeep.
16+
17+## Time
18+Real-time with pause. Speeds 1x, 2x, 4x. One game hour = 0.5 real seconds at 1x.
19+
20+## Victory and defeat
21+- Victory: every front sector advances to the end of the line.
22+- Defeat: any front sector collapses.
23+
24+## Balance targets
25+- One Heavy plus one Light per front sector should hold that sector.
26+- About 4 trains plus track should be affordable in the first two weeks.
27+
28+## Later
29+- A 5-operation campaign with unlocks. Target length 4-6 hours.
30+
31+## Art direction
32+Military campaign map: paper, ink, pins, red front line.
33+
34+## Content rules
35+No illegal activity, no atrocities. The critique lives in the mechanics (the hunger tension, the wounded backlog, the budget), not in depictions.
archive/night_mail/DESIGN.mdadded+38 -0
@@ -0,0 +1,38 @@
1+# Night Mail: Design
2+
3+Night Mail is a side-view train-driving roguelite. You drive a steam mail train across a continent at night, carrying the post from station to station.
4+
5+## Core driving
6+
7+- Throttle controls power. Speed builds slowly with weight and grade.
8+- Shovel coal into the firebox by hand. A cold firebox loses pressure, a full one wastes coal.
9+- Boiler pressure limits power. Keep it in the green band or the engine loses steam.
10+- Brakes are a held control. Braking too late on a curve is how you lose the hull.
11+- Speed limits on curves are enforced. Overspeed damages the hull and the mail.
12+- Grades matter: climbing with a heavy consist drains pressure, descending needs brakes.
13+
14+## Stations
15+
16+- Deliver mail bags addressed to the station you are at.
17+- Buy coal and water with mail money.
18+- Attach or detach cars (mail car, sleeper, workshop, tender). Each car adds mass and length, which changes acceleration, braking distance and fuel burn.
19+
20+## Later (not in milestone 1)
21+
22+- Branching route map between stations, with a choice of fast or safe lines.
23+- Short events on the road: rockslide, blizzard, stranded travellers to pick up.
24+- Three regions, each with its own climate, grades and station types.
25+- Runs last about 30 to 45 minutes. Unlocks carry between runs and take 4 to 6 hours or more to finish.
26+- No illegal activity anywhere in the game. The job is carrying the post, not smuggling.
27+
28+## Milestone 1 (now)
29+
30+One procedural leg of track, 6000 m, with a start station, an end station, 1 to 2 intermediate stations, curves and grades between them. The goal is to test whether driving feels good before anything else is built.
31+
32+## Code layout
33+
34+- `src/model.rs`: shared types (Train, Consist, Track, Phase, messages).
35+- `src/train.rs`: physics and driving controls.
36+- `src/world.rs`: track drawing and camera.
37+- `src/stations.rs`: station stops, mail and coal trade.
38+- `src/hud.rs`: gauges and text.
archive/night_mail/src/autopilot.rsadded+280 -0
@@ -0,0 +1,280 @@
1+//! Debug autopilot for verification runs, enabled with `--autopilot`.
2+//!
3+//! It presses the same keys a player would (W/S, Space, F, Enter) by writing to
4+//! `ButtonInput` before the control systems read it, so the real control path
5+//! is exercised. `--record <dir>` saves a screenshot every 0.25 s of real time,
6+//! and `--quit-after <secs>` exits after that much real time.
7+
8+use std::path::PathBuf;
9+
10+use bevy::app::AppExit;
11+use bevy::prelude::*;
12+use bevy::render::view::window::screenshot::{Screenshot, save_to_disk};
13+
14+use crate::model::{ControlInput, FeatureKind, Money, Phase, Track, Train};
15+
16+const CRUISE_THROTTLE: f32 = 0.8;
17+const APPROACH_THROTTLE: f32 = 0.5;
18+/// Distance before a curve or station at which the throttle is eased off, m.
19+const APPROACH_M: f32 = 250.0;
20+/// Features further ahead than this are ignored when planning speed, m.
21+const LOOK_AHEAD_M: f32 = 400.0;
22+/// Deceleration the planner assumes, m/s^2. The real brake gives about 2.5.
23+const PLAN_DECEL: f32 = 0.4;
24+/// The stop point sits this far into a platform, m.
25+const STOP_OFFSET_M: f32 = 40.0;
26+/// Shovel while the firebox is below this.
27+const FIREBOX_MIN: f32 = 0.55;
28+/// Seconds to wait at a platform, and on the leg-complete panel, before moving on.
29+const WAIT_SECS: f32 = 2.0;
30+const RECORD_EVERY: f32 = 0.25;
31+/// Coal bought at a platform while the tender holds less than this, kg.
32+const COAL_FLOOR: f32 = 600.0;
33+/// Price of one coal purchase, as in stations.rs.
34+const COAL_PRICE: i64 = 20;
35+
36+/// Builds the plugin when the args contain `--autopilot`, otherwise `None`.
37+pub fn from_args(args: &[String]) -> Option<AutopilotPlugin> {
38+ if !args.iter().any(|a| a == "--autopilot") {
39+ return None;
40+ }
41+ Some(AutopilotPlugin {
42+ record: value_of(args, "--record").map(PathBuf::from),
43+ quit_after: value_of(args, "--quit-after").and_then(|v| v.parse().ok()),
44+ })
45+}
46+
47+fn value_of<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
48+ args.iter()
49+ .position(|a| a == flag)
50+ .and_then(|i| args.get(i + 1))
51+ .map(String::as_str)
52+}
53+
54+pub struct AutopilotPlugin {
55+ pub record: Option<PathBuf>,
56+ pub quit_after: Option<f32>,
57+}
58+
59+impl Plugin for AutopilotPlugin {
60+ fn build(&self, app: &mut App) {
61+ app.init_resource::<Pilot>()
62+ .add_systems(Update, pilot.before(ControlInput));
63+
64+ if let Some(dir) = &self.record {
65+ app.insert_resource(Recorder {
66+ dir: dir.clone(),
67+ next_at: 0.0,
68+ frame: 0,
69+ })
70+ .add_systems(Update, record_frames);
71+ }
72+ if let Some(secs) = self.quit_after {
73+ app.insert_resource(QuitAfter(secs))
74+ .add_systems(Update, quit_when_done);
75+ }
76+ }
77+}
78+
79+/// The autopilot's own memory between frames.
80+#[derive(Resource, Default)]
81+struct Pilot {
82+ /// Phase seen last frame, to detect transitions.
83+ phase: Option<Phase>,
84+ /// Seconds spent in the current phase.
85+ timer: f32,
86+ /// Start of the platform the train last stopped at, so it does not stop there again.
87+ visited: Option<f32>,
88+ /// Hysteresis state for the brake.
89+ braking: bool,
90+ /// Whether the leg-complete Enter press has been sent.
91+ enter_sent: bool,
92+ /// Seconds since the autopilot started, and when the next status line is due.
93+ clock: f32,
94+ next_log: f32,
95+ /// When the next coal purchase press may happen, in `timer` seconds.
96+ buy_at: f32,
97+}
98+
99+/// Decides this frame's keys from the train state and the track ahead.
100+fn pilot(
101+ time: Res<Time>,
102+ phase: Res<State<Phase>>,
103+ track: Res<Track>,
104+ train: Res<Train>,
105+ money: Res<Money>,
106+ mut keys: ResMut<ButtonInput<KeyCode>>,
107+ mut pilot: ResMut<Pilot>,
108+) {
109+ let phase = *phase.get();
110+ if pilot.phase.is_none() {
111+ let stops: Vec<String> = track
112+ .features
113+ .iter()
114+ .filter_map(|f| match &f.kind {
115+ FeatureKind::Station { name, .. } => Some(format!("{name} at {:.0} m", f.at)),
116+ _ => None,
117+ })
118+ .collect();
119+ info!("autopilot: track length {:.0} m, stations: {}", track.length, stops.join(", "));
120+ }
121+ if pilot.phase != Some(phase) {
122+ info!("autopilot: {phase:?} at {:.0} m", train.distance);
123+ match phase {
124+ Phase::AtStation => {
125+ pilot.visited = track.station_at(train.distance).map(|f| f.at);
126+ }
127+ Phase::Driving if pilot.phase == Some(Phase::LegComplete) => {
128+ // The next leg has new stations, so the old stop no longer applies.
129+ pilot.visited = None;
130+ }
131+ _ => {}
132+ }
133+ pilot.phase = Some(phase);
134+ pilot.timer = 0.0;
135+ pilot.buy_at = 0.0;
136+ pilot.enter_sent = false;
137+ }
138+ pilot.timer += time.delta_secs();
139+ pilot.clock += time.delta_secs();
140+ if pilot.clock >= pilot.next_log {
141+ pilot.next_log = pilot.clock + 5.0;
142+ info!(
143+ "autopilot t={:.0}s {phase:?} d={:.0} m v={:.1} m/s throttle={:.2} firebox={:.2} pressure={:.0} coal={:.0} hull={:.0}",
144+ pilot.clock, train.distance, train.speed, train.throttle, train.firebox,
145+ train.pressure, train.coal, train.hull
146+ );
147+ }
148+
149+ let mut throttle = 0.0;
150+ let mut brake = false;
151+ let mut enter = false;
152+ let mut buy = false;
153+ match phase {
154+ Phase::Driving => {
155+ let (allowed, approaching) = plan(&track, &train, pilot.visited);
156+ let v = train.speed;
157+ if v > allowed {
158+ pilot.braking = true;
159+ } else if v < allowed - 1.0 {
160+ pilot.braking = false;
161+ }
162+ brake = pilot.braking;
163+ throttle = if approaching {
164+ APPROACH_THROTTLE
165+ } else {
166+ CRUISE_THROTTLE
167+ };
168+ if brake || v > allowed - 1.0 {
169+ throttle = 0.0;
170+ }
171+ }
172+ Phase::AtStation => {
173+ pilot.braking = false;
174+ // Top up the tender while waiting, a press every 0.2 s.
175+ if pilot.timer >= 1.0 && pilot.timer >= pilot.buy_at
176+ && train.coal < COAL_FLOOR && money.0 >= COAL_PRICE
177+ {
178+ buy = true;
179+ pilot.buy_at = pilot.timer + 0.2;
180+ }
181+ if pilot.timer >= WAIT_SECS {
182+ throttle = CRUISE_THROTTLE;
183+ }
184+ }
185+ Phase::LegComplete => {
186+ if pilot.timer >= WAIT_SECS && !pilot.enter_sent {
187+ enter = true;
188+ pilot.enter_sent = true;
189+ }
190+ }
191+ }
192+
193+ set_key(&mut keys, KeyCode::KeyW, throttle > train.throttle + 0.01);
194+ set_key(&mut keys, KeyCode::KeyS, throttle < train.throttle - 0.01);
195+ set_key(&mut keys, KeyCode::Space, brake);
196+ set_key(
197+ &mut keys,
198+ KeyCode::KeyF,
199+ train.firebox < FIREBOX_MIN && train.coal > 0.0,
200+ );
201+ set_key(&mut keys, KeyCode::Enter, enter);
202+ set_key(&mut keys, KeyCode::KeyC, buy);
203+}
204+
205+fn set_key(keys: &mut ButtonInput<KeyCode>, key: KeyCode, down: bool) {
206+ if down {
207+ keys.press(key);
208+ } else {
209+ keys.release(key);
210+ }
211+}
212+
213+/// The speed the train may hold at its position, and whether a curve or
214+/// station is within `APPROACH_M`. Curves cap speed to their limit; the next
215+/// unvisited platform caps speed so the train can stop `STOP_OFFSET_M` into it.
216+fn plan(track: &Track, train: &Train, visited: Option<f32>) -> (f32, bool) {
217+ let d = train.distance;
218+ let mut allowed = f32::INFINITY;
219+ let mut approaching = false;
220+ for f in &track.features {
221+ let ahead = f.at - d;
222+ if ahead > LOOK_AHEAD_M {
223+ break;
224+ }
225+ if f.end() < d {
226+ continue;
227+ }
228+ match &f.kind {
229+ FeatureKind::SpeedLimit { limit, .. } => {
230+ approaching |= ahead <= APPROACH_M;
231+ let cap = if ahead <= 0.0 {
232+ limit - 0.5
233+ } else {
234+ (limit * limit + 2.0 * PLAN_DECEL * ahead).sqrt()
235+ };
236+ allowed = allowed.min(cap);
237+ }
238+ FeatureKind::Station { .. } => {
239+ // The start station is not a stop, and a visited platform is passed.
240+ if f.at <= 0.0 || visited == Some(f.at) {
241+ continue;
242+ }
243+ approaching |= ahead <= APPROACH_M;
244+ let remaining = f.at + STOP_OFFSET_M - d;
245+ allowed = allowed.min((2.0 * PLAN_DECEL * remaining.max(0.0)).sqrt());
246+ }
247+ FeatureKind::Grade { .. } => {}
248+ }
249+ }
250+ (allowed, approaching)
251+}
252+
253+#[derive(Resource)]
254+struct Recorder {
255+ dir: PathBuf,
256+ next_at: f32,
257+ frame: u32,
258+}
259+
260+fn record_frames(mut commands: Commands, time: Res<Time<Real>>, mut rec: ResMut<Recorder>) {
261+ let now = time.elapsed_secs();
262+ if now < rec.next_at {
263+ return;
264+ }
265+ rec.next_at = now + RECORD_EVERY;
266+ let path = rec.dir.join(format!("frame_{:05}.png", rec.frame));
267+ rec.frame += 1;
268+ commands
269+ .spawn(Screenshot::primary_window())
270+ .observe(save_to_disk(path));
271+}
272+
273+#[derive(Resource)]
274+struct QuitAfter(f32);
275+
276+fn quit_when_done(time: Res<Time<Real>>, quit: Res<QuitAfter>, mut exit: MessageWriter<AppExit>) {
277+ if time.elapsed_secs() >= quit.0 {
278+ exit.write(AppExit::Success);
279+ }
280+}
archive/night_mail/src/hud.rsadded+382 -0
@@ -0,0 +1,382 @@
1+//! Driving HUD: cab gauges, top-left status, overspeed warning and controls legend.
2+
3+use bevy::ecs::system::SystemParam;
4+use bevy::prelude::*;
5+
6+use crate::model::{Feature, FeatureKind, MailBags, Money, Overspeed, Phase, Physics, Track, Train};
7+use crate::train::is_venting;
8+
9+/// Body text size in logical pixels.
10+const FONT: f32 = 15.0;
11+/// How long the overspeed warning stays on screen, in seconds.
12+const FLASH_SECS: f32 = 1.5;
13+/// Width of the label column in the cab rows.
14+const LABEL_WIDTH: f32 = 92.0;
15+
16+const PANEL_BG: Color = Color::srgba(0.03, 0.03, 0.06, 0.8);
17+const BAR_BG: Color = Color::srgba(0.14, 0.13, 0.12, 0.95);
18+const TEXT: Color = Color::srgb(0.93, 0.91, 0.85);
19+const DIM: Color = Color::srgb(0.62, 0.58, 0.5);
20+const BRASS: Color = Color::srgb(0.95, 0.72, 0.32);
21+const AMBER: Color = Color::srgb(1.0, 0.68, 0.18);
22+const ORANGE: Color = Color::srgb(1.0, 0.5, 0.12);
23+const RED: Color = Color::srgb(1.0, 0.3, 0.25);
24+const YELLOW: Color = Color::srgb(1.0, 0.92, 0.35);
25+
26+pub struct HudPlugin;
27+
28+impl Plugin for HudPlugin {
29+ fn build(&self, app: &mut App) {
30+ app.init_resource::<OverspeedFlash>()
31+ .add_systems(Startup, setup_hud)
32+ .add_systems(Update, update_hud.after(Physics));
33+ }
34+}
35+
36+/// A text entity whose contents are refreshed every frame.
37+#[derive(Component, Clone, Copy)]
38+enum Readout {
39+ Speed,
40+ Limit,
41+ PressureLabel,
42+ Coal,
43+ Money,
44+ Bags,
45+ Next,
46+ Stop,
47+ Warning,
48+}
49+
50+/// The fill node of a gauge bar.
51+#[derive(Component, Clone, Copy)]
52+enum Bar {
53+ Throttle,
54+ Pressure,
55+ Firebox,
56+ Hull,
57+}
58+
59+/// Marks a HUD panel that is hidden once the leg is complete.
60+#[derive(Component)]
61+struct LegHidden;
62+
63+/// Seconds of overspeed warning still to show.
64+#[derive(Resource, Default)]
65+struct OverspeedFlash {
66+ remaining: f32,
67+}
68+
69+#[derive(SystemParam)]
70+struct HudInputs<'w, 's> {
71+ train: Res<'w, Train>,
72+ track: Res<'w, Track>,
73+ money: Res<'w, Money>,
74+ bags: Res<'w, MailBags>,
75+ phase: Res<'w, State<Phase>>,
76+ time: Res<'w, Time>,
77+ flash: ResMut<'w, OverspeedFlash>,
78+ overspeed: MessageReader<'w, 's, Overspeed>,
79+}
80+
81+fn text_bundle(s: impl Into<String>, colour: Color) -> (Text, TextFont, TextColor) {
82+ (
83+ Text::new(s),
84+ TextFont::from_font_size(FONT),
85+ TextColor(colour),
86+ )
87+}
88+
89+fn setup_hud(mut commands: Commands) {
90+ commands
91+ .spawn((
92+ Node {
93+ position_type: PositionType::Absolute,
94+ left: Val::Px(16.0),
95+ top: Val::Px(16.0),
96+ width: Val::Px(300.0),
97+ flex_direction: FlexDirection::Column,
98+ row_gap: Val::Px(4.0),
99+ padding: UiRect::all(Val::Px(10.0)),
100+ border_radius: BorderRadius::all(Val::Px(6.0)),
101+ ..default()
102+ },
103+ BackgroundColor(PANEL_BG),
104+ ))
105+ .with_children(|p| {
106+ p.spawn((text_bundle("Money", BRASS), Readout::Money));
107+ p.spawn((text_bundle("Mail bags", TEXT), Readout::Bags));
108+ p.spawn((text_bundle("Next", TEXT), Readout::Next));
109+ p.spawn((
110+ Text::new(""),
111+ TextFont {
112+ weight: FontWeight::BOLD,
113+ ..TextFont::from_font_size(FONT)
114+ },
115+ TextColor(YELLOW),
116+ Readout::Stop,
117+ ));
118+ });
119+
120+ commands
121+ .spawn((
122+ Node {
123+ position_type: PositionType::Absolute,
124+ left: Val::Px(16.0),
125+ bottom: Val::Px(16.0),
126+ width: Val::Px(320.0),
127+ flex_direction: FlexDirection::Column,
128+ row_gap: Val::Px(6.0),
129+ padding: UiRect::all(Val::Px(10.0)),
130+ border_radius: BorderRadius::all(Val::Px(6.0)),
131+ ..default()
132+ },
133+ BackgroundColor(PANEL_BG),
134+ LegHidden,
135+ ))
136+ .with_children(|p| {
137+ p.spawn(row()).with_children(|r| {
138+ r.spawn((
139+ label("SPEED", DIM),
140+ Node {
141+ width: Val::Px(LABEL_WIDTH),
142+ ..default()
143+ },
144+ ));
145+ r.spawn((text_bundle("0 km/h", TEXT), Readout::Speed));
146+ r.spawn((text_bundle("", DIM), Readout::Limit));
147+ });
148+ bar_row(p, label("THROTTLE", DIM), Bar::Throttle);
149+ bar_row(
150+ p,
151+ (text_bundle("PRESSURE", DIM), Readout::PressureLabel),
152+ Bar::Pressure,
153+ );
154+ bar_row(p, label("FIREBOX", DIM), Bar::Firebox);
155+ p.spawn((text_bundle("COAL", DIM), Readout::Coal));
156+ bar_row(p, label("HULL", DIM), Bar::Hull);
157+ });
158+
159+ commands
160+ .spawn((
161+ Node {
162+ position_type: PositionType::Absolute,
163+ right: Val::Px(16.0),
164+ bottom: Val::Px(16.0),
165+ padding: UiRect::all(Val::Px(8.0)),
166+ border_radius: BorderRadius::all(Val::Px(6.0)),
167+ ..default()
168+ },
169+ BackgroundColor(PANEL_BG),
170+ ))
171+ .with_child(text_bundle(
172+ "W/S throttle, Space brake, F shovel coal",
173+ DIM,
174+ ));
175+
176+ commands
177+ .spawn((
178+ Node {
179+ position_type: PositionType::Absolute,
180+ left: Val::Px(0.0),
181+ right: Val::Px(0.0),
182+ top: Val::Percent(55.0),
183+ justify_content: JustifyContent::Center,
184+ ..default()
185+ },
186+ LegHidden,
187+ ))
188+ .with_child((
189+ Text::new(""),
190+ TextFont {
191+ weight: FontWeight::BOLD,
192+ ..TextFont::from_font_size(20.0)
193+ },
194+ TextColor(RED),
195+ Readout::Warning,
196+ ));
197+}
198+
199+fn row() -> Node {
200+ Node {
201+ flex_direction: FlexDirection::Row,
202+ align_items: AlignItems::Center,
203+ column_gap: Val::Px(8.0),
204+ ..default()
205+ }
206+}
207+
208+fn label(s: &str, colour: Color) -> (Text, TextFont, TextColor) {
209+ text_bundle(s, colour)
210+}
211+
212+/// A row with a label on the left and a gauge bar filling the rest.
213+fn bar_row(p: &mut ChildSpawnerCommands, label: impl Bundle, kind: Bar) {
214+ p.spawn(row()).with_children(|r| {
215+ r.spawn((
216+ label,
217+ Node {
218+ width: Val::Px(LABEL_WIDTH),
219+ ..default()
220+ },
221+ ));
222+ r.spawn((
223+ Node {
224+ flex_grow: 1.0,
225+ height: Val::Px(12.0),
226+ ..default()
227+ },
228+ BackgroundColor(BAR_BG),
229+ ))
230+ .with_child((
231+ Node {
232+ width: Val::Percent(0.0),
233+ height: Val::Percent(100.0),
234+ ..default()
235+ },
236+ BackgroundColor(BRASS),
237+ kind,
238+ ));
239+ });
240+}
241+
242+fn update_hud(
243+ mut inputs: HudInputs<'_, '_>,
244+ mut readouts: Query<(&Readout, &mut Text, &mut TextColor)>,
245+ mut bars: Query<(&Bar, &mut Node, &mut BackgroundColor)>,
246+ mut hidden: Query<&mut Visibility, With<LegHidden>>,
247+) {
248+ if inputs.overspeed.read().count() > 0 {
249+ inputs.flash.remaining = FLASH_SECS;
250+ }
251+ inputs.flash.remaining = (inputs.flash.remaining - inputs.time.delta_secs()).max(0.0);
252+ let flashing = inputs.flash.remaining > 0.0;
253+
254+ let train = &*inputs.train;
255+ let limit = inputs.track.speed_limit_at(train.distance);
256+ let over_limit = limit.is_some_and(|l| train.speed > l);
257+ let venting = is_venting(train);
258+ // The leg's first station is where the train starts, not a stop.
259+ let at_platform = *inputs.phase.get() == Phase::Driving
260+ && inputs
261+ .track
262+ .station_at(train.distance)
263+ .is_some_and(|f| f.at > 0.0);
264+ let next_line = match inputs.track.next_feature(train.distance) {
265+ Some(f) => format!("Next: {}", describe_next(f, train.distance)),
266+ None => "Next: end of leg".to_string(),
267+ };
268+
269+ for (readout, mut text, mut colour) in &mut readouts {
270+ let (value, col): (String, Color) = match readout {
271+ Readout::Speed => (
272+ format!("{:.0} km/h", kmh(train.speed)),
273+ if over_limit { RED } else { TEXT },
274+ ),
275+ Readout::Limit => (
276+ limit
277+ .map(|l| format!("limit {:.0}", kmh(l)))
278+ .unwrap_or_default(),
279+ DIM,
280+ ),
281+ Readout::PressureLabel => {
282+ if venting {
283+ ("VENTING".to_string(), RED)
284+ } else {
285+ ("PRESSURE".to_string(), DIM)
286+ }
287+ }
288+ Readout::Coal => (format!("COAL {:.0} kg", train.coal), TEXT),
289+ Readout::Money => (format!("Money ${}", inputs.money.0), BRASS),
290+ Readout::Bags => (format!("Mail bags: {}", inputs.bags.bags.len()), TEXT),
291+ Readout::Next => (next_line.clone(), TEXT),
292+ Readout::Stop => (
293+ if at_platform {
294+ "STOP HERE to deliver mail".to_string()
295+ } else {
296+ String::new()
297+ },
298+ YELLOW,
299+ ),
300+ Readout::Warning => (
301+ if flashing {
302+ "TOO FAST FOR THE CURVE!".to_string()
303+ } else {
304+ String::new()
305+ },
306+ RED,
307+ ),
308+ };
309+ if text.0 != value {
310+ text.0 = value;
311+ }
312+ colour.0 = col;
313+ }
314+
315+ for (bar, mut node, mut colour) in &mut bars {
316+ let (percent, col) = match bar {
317+ Bar::Throttle => (train.throttle * 100.0, BRASS),
318+ Bar::Pressure => (
319+ train.pressure,
320+ if train.pressure > 90.0 { RED } else { AMBER },
321+ ),
322+ Bar::Firebox => (train.firebox * 100.0, ORANGE),
323+ Bar::Hull => (train.hull, hull_colour(train.hull)),
324+ };
325+ node.width = Val::Percent(percent.clamp(0.0, 100.0));
326+ colour.0 = col;
327+ }
328+
329+ let want = if *inputs.phase.get() == Phase::LegComplete {
330+ Visibility::Hidden
331+ } else {
332+ Visibility::Inherited
333+ };
334+ for mut vis in &mut hidden {
335+ vis.set_if_neq(want);
336+ }
337+}
338+
339+/// Green when the hull is sound, shading to red as it fails.
340+fn hull_colour(hull: f32) -> Color {
341+ let t = (hull / 100.0).clamp(0.0, 1.0);
342+ Color::srgb(1.0 - t, 0.25 + 0.6 * t, 0.25)
343+}
344+
345+fn kmh(metres_per_second: f32) -> f32 {
346+ metres_per_second * 3.6
347+}
348+
349+/// Text for the next feature ahead, e.g. "Curve 54 km/h in 320 m".
350+fn describe_next(f: &Feature, distance: f32) -> String {
351+ let away = format_distance((f.at - distance).max(0.0));
352+ match &f.kind {
353+ FeatureKind::SpeedLimit { limit, .. } => {
354+ format!("Curve {:.0} km/h in {away}", kmh(*limit))
355+ }
356+ FeatureKind::Grade { slope, .. } => {
357+ let pct = trim_zero(format!("{:.1}", slope.abs() * 100.0));
358+ if *slope >= 0.0 {
359+ format!("Hill +{pct}% in {away}")
360+ } else {
361+ format!("Descent -{pct}% in {away}")
362+ }
363+ }
364+ FeatureKind::Station { name, .. } => format!("Station {name} in {away}"),
365+ }
366+}
367+
368+/// Metres under 1000, otherwise kilometres with one decimal.
369+fn format_distance(metres: f32) -> String {
370+ if metres < 1000.0 {
371+ format!("{metres:.0} m")
372+ } else {
373+ format!("{:.1} km", metres / 1000.0)
374+ }
375+}
376+
377+fn trim_zero(s: String) -> String {
378+ match s.strip_suffix(".0") {
379+ Some(t) => t.to_string(),
380+ None => s,
381+ }
382+}
archive/night_mail/src/main.rsadded+74 -0
@@ -0,0 +1,74 @@
1+#![forbid(unsafe_code)]
2+
3+mod autopilot;
4+mod hud;
5+mod model;
6+mod stations;
7+mod train;
8+mod world;
9+
10+use bevy::prelude::*;
11+use bevy::window::WindowResolution;
12+
13+use hud::HudPlugin;
14+use model::{
15+ ControlInput, Consist, FeatureKind, MailBags, Money, Overspeed, Phase, Physics, Track, Train,
16+};
17+use stations::StationsPlugin;
18+use train::TrainPlugin;
19+use world::WorldPlugin;
20+
21+fn main() {
22+ let args: Vec<String> = std::env::args().collect();
23+ let seed: u64 = rand::random();
24+ let track = Track::generate(seed);
25+
26+ // Mail bags are addressed to the stations after the start.
27+ let destinations: Vec<String> = track
28+ .features
29+ .iter()
30+ .filter(|f| f.at > 0.0)
31+ .filter_map(|f| match &f.kind {
32+ FeatureKind::Station { name, .. } => Some(name.clone()),
33+ _ => None,
34+ })
35+ .collect();
36+ let bags = MailBags {
37+ bags: (0..3)
38+ .map(|i| destinations[i % destinations.len()].clone())
39+ .collect(),
40+ };
41+
42+ let mut app = App::new();
43+ app.add_plugins(DefaultPlugins.set(WindowPlugin {
44+ primary_window: Some(Window {
45+ title: "Night Mail".into(),
46+ resolution: WindowResolution::new(1280, 720),
47+ ..default()
48+ }),
49+ ..default()
50+ }))
51+ .insert_resource(ClearColor(Color::srgb(0.03, 0.04, 0.09)))
52+ .init_state::<Phase>()
53+ .insert_resource(Train::default())
54+ .insert_resource(Consist::default())
55+ .insert_resource(track)
56+ .insert_resource(bags)
57+ .insert_resource(Money::default())
58+ .add_message::<Overspeed>()
59+ .configure_sets(Update, (ControlInput, Physics).chain())
60+ .add_systems(Startup, spawn_camera)
61+ .add_plugins((TrainPlugin, WorldPlugin, StationsPlugin, HudPlugin));
62+
63+ // Debug only: `--autopilot` drives the train, with optional `--record <dir>`
64+ // and `--quit-after <secs>`. See autopilot.rs.
65+ if let Some(plugin) = autopilot::from_args(&args) {
66+ app.add_plugins(plugin);
67+ }
68+
69+ app.run();
70+}
71+
72+fn spawn_camera(mut commands: Commands) {
73+ commands.spawn(Camera2d);
74+}
archive/night_mail/src/model.rsadded+434 -0
@@ -0,0 +1,434 @@
1+//! Shared data types for Night Mail. Every other module builds on these.
2+
3+use bevy::prelude::{Message, Resource, States, SystemSet};
4+use rand::rngs::StdRng;
5+use rand::{RngExt, SeedableRng};
6+
7+/// Pixels drawn per metre of track.
8+pub const PX_PER_M: f32 = 8.0;
9+
10+/// Length of the single milestone-1 leg, in metres.
11+const LEG_LENGTH: f32 = 6000.0;
12+
13+/// Live state of the train.
14+#[derive(Resource, Clone, Debug, PartialEq)]
15+pub struct Train {
16+ /// Metres along the track.
17+ pub distance: f32,
18+ /// Metres per second.
19+ pub speed: f32,
20+ /// 0..1.
21+ pub throttle: f32,
22+ pub braking: bool,
23+ /// 0..1, how much coal is burning.
24+ pub firebox: f32,
25+ /// 0..100.
26+ pub pressure: f32,
27+ /// kg of coal in the tender.
28+ pub coal: f32,
29+ /// 0..100.
30+ pub hull: f32,
31+}
32+
33+impl Default for Train {
34+ fn default() -> Self {
35+ Self {
36+ distance: 0.0,
37+ speed: 0.0,
38+ throttle: 0.0,
39+ braking: false,
40+ firebox: 0.3,
41+ pressure: 40.0,
42+ coal: 800.0,
43+ hull: 100.0,
44+ }
45+ }
46+}
47+
48+/// A kind of rolling stock that can be attached to the train.
49+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50+pub enum CarKind {
51+ Locomotive,
52+ Tender,
53+ MailCar,
54+}
55+
56+impl CarKind {
57+ /// Mass in tonnes. The tender holds only its own 20 t; coal is added
58+ /// separately by `Consist::total_mass`.
59+ pub fn mass(&self) -> f32 {
60+ match self {
61+ CarKind::Locomotive => 60.0,
62+ CarKind::Tender => 20.0,
63+ CarKind::MailCar => 25.0,
64+ }
65+ }
66+
67+ /// Length in metres.
68+ pub fn length(&self) -> f32 {
69+ match self {
70+ CarKind::Locomotive => 14.0,
71+ CarKind::Tender => 8.0,
72+ CarKind::MailCar => 16.0,
73+ }
74+ }
75+}
76+
77+/// The ordered list of cars currently coupled to the locomotive.
78+#[derive(Resource, Clone, Debug, PartialEq)]
79+pub struct Consist(pub Vec<CarKind>);
80+
81+impl Default for Consist {
82+ fn default() -> Self {
83+ Consist(vec![CarKind::Locomotive, CarKind::Tender, CarKind::MailCar])
84+ }
85+}
86+
87+impl Consist {
88+ /// Total mass in tonnes, including `coal_kg` of coal in the tender.
89+ pub fn total_mass(&self, coal_kg: f32) -> f32 {
90+ let cars: f32 = self.0.iter().map(|c| c.mass()).sum();
91+ cars + coal_kg / 1000.0
92+ }
93+}
94+
95+/// Something placed along the track.
96+#[derive(Clone, Debug)]
97+pub enum FeatureKind {
98+ Station {
99+ name: String,
100+ /// Metres of platform, starting at `Feature::at`.
101+ platform_len: f32,
102+ },
103+ SpeedLimit {
104+ /// Metres per second.
105+ limit: f32,
106+ len: f32,
107+ },
108+ Grade {
109+ /// Rise per metre, e.g. 0.02 is a 2% climb.
110+ slope: f32,
111+ len: f32,
112+ },
113+}
114+
115+/// A feature anchored at a distance along the track.
116+#[derive(Clone, Debug)]
117+pub struct Feature {
118+ /// Metres along the track where the feature starts.
119+ pub at: f32,
120+ pub kind: FeatureKind,
121+}
122+
123+impl Feature {
124+ /// Distance at which this feature stops applying.
125+ pub fn end(&self) -> f32 {
126+ match &self.kind {
127+ FeatureKind::Station { platform_len, .. } => self.at + platform_len,
128+ FeatureKind::SpeedLimit { len, .. } | FeatureKind::Grade { len, .. } => self.at + len,
129+ }
130+ }
131+}
132+
133+/// The whole leg of track, with its features sorted by `at`.
134+#[derive(Resource, Clone, Debug)]
135+pub struct Track {
136+ pub features: Vec<Feature>,
137+ /// Total length in metres.
138+ pub length: f32,
139+}
140+
141+const STATION_NAMES: [&str; 8] = [
142+ "Lowmere Central",
143+ "Harrowgate Sidings",
144+ "Millbrook Halt",
145+ "Cinderford North",
146+ "Porthaven Cross",
147+ "Kestle Junction",
148+ "Thornbury Moor",
149+ "Ravensdale",
150+];
151+
152+/// Gap between a station zone and any feature, so features never touch a platform.
153+const STATION_PAD: f32 = 150.0;
154+const STATION_PLATFORM: f32 = 120.0;
155+
156+impl Track {
157+ /// Builds a deterministic leg of track from `seed`.
158+ pub fn generate(seed: u64) -> Track {
159+ let mut rng = StdRng::seed_from_u64(seed);
160+
161+ // Pick distinct station names.
162+ let mut names: Vec<&str> = Vec::new();
163+ while names.len() < 4 {
164+ let n = STATION_NAMES[rng.random_range(0..STATION_NAMES.len())];
165+ if !names.contains(&n) {
166+ names.push(n);
167+ }
168+ }
169+
170+ // Start and end stations are fixed; 1-2 intermediate stations sit in
171+ // roughly equal bands with some jitter.
172+ let mut stations: Vec<(f32, String)> = vec![(0.0, names[0].to_string())];
173+ let intermediates = rng.random_range(1..=2usize);
174+ for i in 0..intermediates {
175+ let centre = (i + 1) as f32 * LEG_LENGTH / (intermediates + 1) as f32;
176+ let at = centre + rng.random_range(-400.0..400.0);
177+ stations.push((at, names[1 + i].to_string()));
178+ }
179+ stations.push((LEG_LENGTH, names[3].to_string()));
180+
181+ // Forbidden zones around each platform.
182+ let zones: Vec<(f32, f32)> = stations
183+ .iter()
184+ .map(|(at, _)| (at - STATION_PAD, at + STATION_PLATFORM + STATION_PAD))
185+ .collect();
186+
187+ let mut features: Vec<Feature> = stations
188+ .iter()
189+ .map(|(at, name)| Feature {
190+ at: *at,
191+ kind: FeatureKind::Station {
192+ name: name.clone(),
193+ platform_len: STATION_PLATFORM,
194+ },
195+ })
196+ .collect();
197+
198+ // Sweep along the leg, dropping curves and grades between stations.
199+ let mut cursor = 200.0_f32;
200+ while cursor < LEG_LENGTH {
201+ if let Some(zone) = zones.iter().find(|z| cursor >= z.0 && cursor < z.1) {
202+ cursor = zone.1;
203+ continue;
204+ }
205+ let next_zone_start = zones
206+ .iter()
207+ .map(|z| z.0)
208+ .filter(|s| *s > cursor)
209+ .fold(LEG_LENGTH, f32::min);
210+
211+ let is_curve = rng.random_range(0.0..1.0) < 0.6;
212+ let kind = if is_curve {
213+ FeatureKind::SpeedLimit {
214+ limit: rng.random_range(10.0..20.0),
215+ len: rng.random_range(100.0..300.0),
216+ }
217+ } else {
218+ FeatureKind::Grade {
219+ slope: rng.random_range(-0.03..0.03),
220+ len: rng.random_range(200.0..600.0),
221+ }
222+ };
223+ let len = match &kind {
224+ FeatureKind::SpeedLimit { len, .. } | FeatureKind::Grade { len, .. } => *len,
225+ FeatureKind::Station { platform_len, .. } => *platform_len,
226+ };
227+
228+ if cursor + len > next_zone_start {
229+ // Does not fit before the next station zone: jump to it.
230+ cursor = next_zone_start;
231+ continue;
232+ }
233+
234+ features.push(Feature { at: cursor, kind });
235+ cursor += len + rng.random_range(60.0..400.0);
236+ }
237+
238+ features.sort_by(|a, b| a.at.total_cmp(&b.at));
239+ Track {
240+ features,
241+ length: LEG_LENGTH,
242+ }
243+ }
244+
245+ /// Speed limit in m/s applying at distance `d`, if any.
246+ pub fn speed_limit_at(&self, d: f32) -> Option<f32> {
247+ self.features.iter().find_map(|f| match f.kind {
248+ FeatureKind::SpeedLimit { limit, .. } if d >= f.at && d < f.end() => Some(limit),
249+ _ => None,
250+ })
251+ }
252+
253+ /// Grade (rise per metre) at distance `d`; 0 where there is none.
254+ pub fn grade_at(&self, d: f32) -> f32 {
255+ self.features
256+ .iter()
257+ .find_map(|f| match f.kind {
258+ FeatureKind::Grade { slope, .. } if d >= f.at && d < f.end() => Some(slope),
259+ _ => None,
260+ })
261+ .unwrap_or(0.0)
262+ }
263+
264+ /// The station whose platform span contains `d`, if the train is there.
265+ pub fn station_at(&self, d: f32) -> Option<&Feature> {
266+ self.features
267+ .iter()
268+ .find(|f| matches!(f.kind, FeatureKind::Station { .. }) && d >= f.at && d <= f.end())
269+ }
270+
271+ /// The first feature starting strictly after `d`.
272+ pub fn next_feature(&self, d: f32) -> Option<&Feature> {
273+ self.features.iter().find(|f| f.at > d)
274+ }
275+}
276+
277+/// Mail bags on board, each addressed to a destination station name.
278+#[derive(Resource, Clone, Debug, Default)]
279+pub struct MailBags {
280+ /// Destination station names.
281+ pub bags: Vec<String>,
282+}
283+
284+/// Company cash in pounds-ish units.
285+#[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)]
286+pub struct Money(pub i64);
287+
288+impl Default for Money {
289+ fn default() -> Self {
290+ Money(200)
291+ }
292+}
293+
294+/// Top-level game phase.
295+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, States, Hash)]
296+pub enum Phase {
297+ #[default]
298+ Driving,
299+ AtStation,
300+ LegComplete,
301+}
302+
303+/// Sent when the train exceeds the current speed limit (rate-limited).
304+#[derive(Message)]
305+pub struct Overspeed;
306+
307+/// Orders systems that read driver controls (keys) before anything that acts
308+/// on them. The debug autopilot writes its key presses before this set.
309+#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
310+pub struct ControlInput;
311+
312+/// Train physics. Stations, HUD and camera read the train after this set.
313+#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
314+pub struct Physics;
315+
316+#[cfg(test)]
317+mod tests {
318+ use super::*;
319+
320+ const SEEDS: std::ops::Range<u64> = 0..50;
321+
322+ fn extent(f: &Feature) -> (f32, f32) {
323+ (f.at, f.end())
324+ }
325+
326+ #[test]
327+ fn features_are_sorted_and_non_overlapping() {
328+ for seed in SEEDS {
329+ let track = Track::generate(seed);
330+ for pair in track.features.windows(2) {
331+ assert!(pair[0].at <= pair[1].at, "seed {seed}: not sorted");
332+ let (_, prev_end) = extent(&pair[0]);
333+ assert!(
334+ pair[1].at >= prev_end,
335+ "seed {seed}: overlap at {} (prev ends {prev_end})",
336+ pair[1].at
337+ );
338+ }
339+ }
340+ }
341+
342+ #[test]
343+ fn stations_at_both_ends() {
344+ for seed in SEEDS {
345+ let track = Track::generate(seed);
346+ let first = track.features.first().expect("has features");
347+ assert_eq!(first.at, 0.0);
348+ assert!(matches!(first.kind, FeatureKind::Station { .. }));
349+ let last_station = track
350+ .features
351+ .iter()
352+ .rfind(|f| matches!(f.kind, FeatureKind::Station { .. }))
353+ .expect("has stations");
354+ assert_eq!(last_station.at, track.length);
355+ assert_eq!(track.length, LEG_LENGTH);
356+
357+ let stations = track
358+ .features
359+ .iter()
360+ .filter(|f| matches!(f.kind, FeatureKind::Station { .. }))
361+ .count();
362+ assert!((3..=4).contains(&stations), "seed {seed}: {stations} stations");
363+ }
364+ }
365+
366+ #[test]
367+ fn features_stay_within_leg() {
368+ for seed in SEEDS {
369+ let track = Track::generate(seed);
370+ for f in &track.features {
371+ assert!(f.at >= 0.0 && f.end() <= track.length + 120.0, "seed {seed}");
372+ }
373+ }
374+ }
375+
376+ #[test]
377+ fn queries_work() {
378+ for seed in SEEDS {
379+ let track = Track::generate(seed);
380+
381+ // Start station covers distance 0.
382+ let start = track.station_at(0.0).expect("start station at 0");
383+ assert_eq!(start.at, 0.0);
384+
385+ // Every curve and grade is found at its own start.
386+ for f in &track.features {
387+ match &f.kind {
388+ FeatureKind::SpeedLimit { limit, .. } => {
389+ assert_eq!(track.speed_limit_at(f.at), Some(*limit));
390+ }
391+ FeatureKind::Grade { slope, .. } => {
392+ assert_eq!(track.grade_at(f.at), *slope);
393+ }
394+ FeatureKind::Station { .. } => {
395+ assert!(track.station_at(f.at).is_some());
396+ }
397+ }
398+ }
399+
400+ // Sweep the whole leg without panicking.
401+ let mut d = -10.0;
402+ while d < track.length + 10.0 {
403+ let _ = track.speed_limit_at(d);
404+ let _ = track.grade_at(d);
405+ let _ = track.station_at(d);
406+ let _ = track.next_feature(d);
407+ d += 7.0;
408+ }
409+
410+ // No features at or beyond the track end.
411+ assert!(track.next_feature(track.length).is_none());
412+ assert!(track.grade_at(-100.0) == 0.0);
413+ assert!(track.speed_limit_at(-100.0).is_none());
414+ assert!(track.next_feature(-1.0).is_some());
415+ }
416+ }
417+
418+ #[test]
419+ fn same_seed_same_track() {
420+ let a = Track::generate(42);
421+ let b = Track::generate(42);
422+ assert_eq!(a.features.len(), b.features.len());
423+ for (x, y) in a.features.iter().zip(&b.features) {
424+ assert_eq!(x.at, y.at);
425+ }
426+ }
427+
428+ #[test]
429+ fn consist_mass_and_length() {
430+ let c = Consist::default();
431+ assert_eq!(c.total_mass(0.0), 60.0 + 20.0 + 25.0);
432+ assert_eq!(c.total_mass(800.0), 105.0 + 0.8);
433+ }
434+}
archive/night_mail/src/stations.rsadded+347 -0
@@ -0,0 +1,347 @@
1+//! Station stops, mail delivery, coal and repair trade, and the leg-complete flow.
2+
3+use bevy::prelude::*;
4+
5+use crate::model::{ControlInput, FeatureKind, MailBags, Money, Phase, Physics, Track, Train};
6+
7+/// Pay per delivered mail bag.
8+const BAG_PAY: i64 = 60;
9+/// Coal bought per purchase, in kg.
10+const COAL_LOAD: f32 = 100.0;
11+const COAL_PRICE: i64 = 20;
12+const COAL_CAP: f32 = 1500.0;
13+/// Hull repaired per purchase.
14+const REPAIR_AMOUNT: f32 = 10.0;
15+const REPAIR_PRICE: i64 = 30;
16+const HULL_CAP: f32 = 100.0;
17+/// Speed (m/s) below which the train may pull into a platform.
18+const ARRIVE_SPEED: f32 = 0.3;
19+/// Speed (m/s) above which the train departs from a platform.
20+const DEPART_SPEED: f32 = 1.0;
21+
22+const PANEL_FONT: f32 = 18.0;
23+
24+pub struct StationsPlugin;
25+
26+impl Plugin for StationsPlugin {
27+ fn build(&self, app: &mut App) {
28+ app.init_resource::<StopLog>()
29+ .add_systems(
30+ Update,
31+ check_arrival
32+ .run_if(in_state(Phase::Driving))
33+ .after(Physics),
34+ )
35+ .add_systems(OnEnter(Phase::AtStation), spawn_station_panel)
36+ .add_systems(
37+ Update,
38+ (
39+ station_actions.in_set(ControlInput),
40+ depart_when_moving.after(Physics),
41+ )
42+ .run_if(in_state(Phase::AtStation)),
43+ )
44+ .add_systems(OnEnter(Phase::LegComplete), spawn_leg_panel)
45+ .add_systems(
46+ Update,
47+ next_leg
48+ .in_set(ControlInput)
49+ .run_if(in_state(Phase::LegComplete)),
50+ );
51+ }
52+}
53+
54+/// Stop bookkeeping, shared between the arrival and the panels.
55+#[derive(Resource, Default)]
56+pub struct StopLog {
57+ /// Last station the train stopped at. `None` at the start of a leg, where
58+ /// the start station at distance 0 is treated as visited.
59+ visited: Option<String>,
60+ /// Name of the station the current panel is for.
61+ station: String,
62+ delivered: usize,
63+ earned: i64,
64+ picked_up: usize,
65+ /// Result line of the last coal or repair purchase.
66+ notice: String,
67+}
68+
69+/// Marks the text line that shows the result of the last purchase.
70+#[derive(Component)]
71+struct NoticeText;
72+
73+/// Names of all stations strictly after distance `after`.
74+fn onward_stations(track: &Track, after: f32) -> Vec<String> {
75+ track
76+ .features
77+ .iter()
78+ .filter(|f| f.at > after)
79+ .filter_map(|f| match &f.kind {
80+ FeatureKind::Station { name, .. } => Some(name.clone()),
81+ _ => None,
82+ })
83+ .collect()
84+}
85+
86+/// Pulls the train into a station when it is slow enough inside a platform.
87+fn check_arrival(
88+ mut train: ResMut<Train>,
89+ track: Res<Track>,
90+ mut bags: ResMut<MailBags>,
91+ mut money: ResMut<Money>,
92+ mut log: ResMut<StopLog>,
93+ mut next: ResMut<NextState<Phase>>,
94+) {
95+ if train.speed >= ARRIVE_SPEED {
96+ return;
97+ }
98+ let Some(station) = track.station_at(train.distance) else {
99+ return;
100+ };
101+ let FeatureKind::Station { name, .. } = &station.kind else {
102+ return;
103+ };
104+ if station.at <= 0.0 || log.visited.as_deref() == Some(name.as_str()) {
105+ return;
106+ }
107+
108+ let last_station_at = track
109+ .features
110+ .iter()
111+ .filter(|f| matches!(f.kind, FeatureKind::Station { .. }))
112+ .map(|f| f.at)
113+ .fold(f32::MIN, f32::max);
114+ let is_last = station.at >= last_station_at;
115+
116+ // Deliver every bag addressed here.
117+ let delivered = bags.bags.iter().filter(|b| *b == name).count();
118+ bags.bags.retain(|b| b != name);
119+ let earned = delivered as i64 * BAG_PAY;
120+ money.0 += earned;
121+
122+ // Pick up 1-2 new bags for stations further down the line.
123+ let onward = onward_stations(&track, station.at);
124+ let mut picked_up = 0;
125+ if !onward.is_empty() {
126+ let count = rand::random_range(1..=2usize);
127+ for _ in 0..count {
128+ let idx = rand::random_range(0..onward.len());
129+ bags.bags.push(onward[idx].clone());
130+ picked_up += 1;
131+ }
132+ }
133+
134+ log.visited = Some(name.clone());
135+ log.station = name.clone();
136+ log.delivered = delivered;
137+ log.earned = earned;
138+ log.picked_up = picked_up;
139+ log.notice.clear();
140+
141+ // Stopped at the platform: the throttle must be opened again to leave.
142+ train.throttle = 0.0;
143+ next.set(if is_last {
144+ Phase::LegComplete
145+ } else {
146+ Phase::AtStation
147+ });
148+}
149+
150+/// Builds the station panel. Despawned automatically on leaving `AtStation`.
151+fn spawn_station_panel(mut commands: Commands, log: Res<StopLog>) {
152+ let summary = format!(
153+ "Delivered {} {} (+${}). Picked up {} {}.",
154+ log.delivered,
155+ bag_word(log.delivered),
156+ log.earned,
157+ log.picked_up,
158+ bag_word(log.picked_up)
159+ );
160+ commands
161+ .spawn((
162+ Node {
163+ position_type: PositionType::Absolute,
164+ left: px(0.0),
165+ right: px(0.0),
166+ top: px(24.0),
167+ justify_content: JustifyContent::Center,
168+ ..default()
169+ },
170+ DespawnOnExit(Phase::AtStation),
171+ ))
172+ .with_children(|root| {
173+ root.spawn((
174+ Node {
175+ flex_direction: FlexDirection::Column,
176+ row_gap: px(6.0),
177+ padding: UiRect::all(px(14.0)),
178+ ..default()
179+ },
180+ BackgroundColor(Color::srgba(0.02, 0.03, 0.06, 0.85)),
181+ ))
182+ .with_children(|panel| {
183+ line(panel, log.station.clone());
184+ line(panel, summary);
185+ line(panel, "[C] Buy 100 kg coal - $20 [R] Repair 10 hull - $30".into());
186+ panel.spawn((
187+ Text::new(String::new()),
188+ TextFont {
189+ font_size: PANEL_FONT.into(),
190+ ..default()
191+ },
192+ NoticeText,
193+ ));
194+ line(panel, "Open the throttle (W) to depart.".into());
195+ });
196+ });
197+}
198+
199+fn bag_word(n: usize) -> &'static str {
200+ if n == 1 { "bag" } else { "bags" }
201+}
202+
203+fn line(parent: &mut ChildSpawnerCommands, text: String) {
204+ parent.spawn((
205+ Text::new(text),
206+ TextFont {
207+ font_size: PANEL_FONT.into(),
208+ ..default()
209+ },
210+ ));
211+}
212+
213+/// Handles the coal and repair purchases while the train is at a platform.
214+fn station_actions(
215+ keys: Res<ButtonInput<KeyCode>>,
216+ mut train: ResMut<Train>,
217+ mut money: ResMut<Money>,
218+ mut log: ResMut<StopLog>,
219+ mut notice: Query<&mut Text, With<NoticeText>>,
220+) {
221+ let result = if keys.just_pressed(KeyCode::KeyC) {
222+ Some(buy_coal(&mut train, &mut money))
223+ } else if keys.just_pressed(KeyCode::KeyR) {
224+ Some(repair_hull(&mut train, &mut money))
225+ } else {
226+ None
227+ };
228+ if let Some(msg) = result {
229+ log.notice = msg;
230+ for mut text in &mut notice {
231+ text.0 = log.notice.clone();
232+ }
233+ }
234+}
235+
236+fn buy_coal(train: &mut Train, money: &mut Money) -> String {
237+ if train.coal >= COAL_CAP {
238+ return "The tender is already full.".into();
239+ }
240+ if money.0 < COAL_PRICE {
241+ return "Not enough money for coal.".into();
242+ }
243+ money.0 -= COAL_PRICE;
244+ train.coal = (train.coal + COAL_LOAD).min(COAL_CAP);
245+ format!("Loaded coal. Tender now {:.0} kg.", train.coal)
246+}
247+
248+fn repair_hull(train: &mut Train, money: &mut Money) -> String {
249+ if train.hull >= HULL_CAP {
250+ return "The hull is already sound.".into();
251+ }
252+ if money.0 < REPAIR_PRICE {
253+ return "Not enough money for repairs.".into();
254+ }
255+ money.0 -= REPAIR_PRICE;
256+ train.hull = (train.hull + REPAIR_AMOUNT).min(HULL_CAP);
257+ format!("Repaired hull. Now {:.0}.", train.hull)
258+}
259+
260+/// Leaves the platform once the throttle has the train moving.
261+fn depart_when_moving(train: Res<Train>, mut next: ResMut<NextState<Phase>>) {
262+ if train.speed > DEPART_SPEED {
263+ next.set(Phase::Driving);
264+ }
265+}
266+
267+/// Builds the leg-complete panel. Despawned automatically on leaving `LegComplete`.
268+fn spawn_leg_panel(mut commands: Commands, money: Res<Money>, train: Res<Train>) {
269+ let lines = [
270+ format!("Money: ${}", money.0),
271+ format!("Hull: {:.0}", train.hull),
272+ "Press Enter for the next leg".to_string(),
273+ ];
274+ commands
275+ .spawn((
276+ Node {
277+ position_type: PositionType::Absolute,
278+ left: px(0.0),
279+ right: px(0.0),
280+ top: px(0.0),
281+ bottom: px(0.0),
282+ justify_content: JustifyContent::Center,
283+ align_items: AlignItems::Center,
284+ ..default()
285+ },
286+ DespawnOnExit(Phase::LegComplete),
287+ ))
288+ .with_children(|root| {
289+ root.spawn((
290+ Node {
291+ flex_direction: FlexDirection::Column,
292+ align_items: AlignItems::Center,
293+ row_gap: px(12.0),
294+ padding: UiRect::all(px(32.0)),
295+ ..default()
296+ },
297+ BackgroundColor(Color::srgba(0.02, 0.03, 0.06, 0.92)),
298+ ))
299+ .with_children(|panel| {
300+ panel.spawn((
301+ Text::new("Leg complete!"),
302+ TextFont {
303+ font_size: 36.0.into(),
304+ ..default()
305+ },
306+ ));
307+ for text in lines {
308+ line(panel, text);
309+ }
310+ });
311+ });
312+}
313+
314+/// Starts a fresh leg with new track and mail, keeping coal, hull and pressure.
315+/// Replacing `Track` here is what makes `world::build_track_visuals` rebuild.
316+pub fn next_leg(
317+ keys: Res<ButtonInput<KeyCode>>,
318+ mut track: ResMut<Track>,
319+ mut train: ResMut<Train>,
320+ mut bags: ResMut<MailBags>,
321+ mut log: ResMut<StopLog>,
322+ mut next: ResMut<NextState<Phase>>,
323+) {
324+ if !(keys.just_pressed(KeyCode::Enter) || keys.just_pressed(KeyCode::NumpadEnter)) {
325+ return;
326+ }
327+
328+ *track = Track::generate(rand::random());
329+
330+ train.distance = 0.0;
331+ train.speed = 0.0;
332+ train.throttle = 0.0;
333+
334+ // Undelivered bags belonged to the old leg's stations, so they are dropped.
335+ let destinations = onward_stations(&track, 0.0);
336+ bags.bags.clear();
337+ if !destinations.is_empty() {
338+ let count = rand::random_range(2..=3usize);
339+ for _ in 0..count {
340+ let idx = rand::random_range(0..destinations.len());
341+ bags.bags.push(destinations[idx].clone());
342+ }
343+ }
344+
345+ *log = StopLog::default();
346+ next.set(Phase::Driving);
347+}
archive/night_mail/src/train.rsadded+238 -0
@@ -0,0 +1,238 @@
1+//! Driver input and train physics.
2+
3+use bevy::prelude::*;
4+
5+use crate::model::{ControlInput, Consist, Overspeed, Phase, Physics, Track, Train};
6+
7+const GRAVITY: f32 = 9.81;
8+/// Throttle change per second while a key is held.
9+const THROTTLE_RATE: f32 = 0.6;
10+/// Maximum braking force, newtons.
11+const BRAKE_FORCE: f32 = 260_000.0;
12+/// Tractive force at full throttle and full pressure, newtons.
13+const TRACTIVE_FORCE: f32 = 180_000.0;
14+/// Coal moved from the tender per second while shovelling, kg.
15+const SHOVEL_KG_PER_S: f32 = 40.0;
16+/// Firebox fraction added per second while shovelling.
17+const SHOVEL_FIREBOX_PER_S: f32 = 0.25;
18+/// Firebox fraction burned per second.
19+const FIREBOX_BURN_PER_S: f32 = 0.02;
20+/// Pressure gained per second per unit of firebox.
21+const PRESSURE_GAIN: f32 = 14.0;
22+/// Pressure lost per second per unit of throttle (before the speed term).
23+const PRESSURE_LOSS: f32 = 6.0;
24+/// Rolling resistance coefficient.
25+const ROLLING_COEF: f32 = 0.002;
26+/// Air resistance, newtons per (m/s)^2.
27+const AIR_COEF: f32 = 25.0;
28+/// Speed over the limit tolerated before overspeed bites, m/s.
29+const OVERSPEED_MARGIN: f32 = 1.0;
30+/// Hull damage per second per m/s over the limit.
31+const OVERSPEED_HULL_RATE: f32 = 3.0;
32+/// Minimum time between `Overspeed` messages, seconds.
33+const OVERSPEED_MSG_INTERVAL: f32 = 0.5;
34+
35+pub struct TrainPlugin;
36+
37+impl Plugin for TrainPlugin {
38+ fn build(&self, app: &mut App) {
39+ app.add_systems(
40+ Update,
41+ drive
42+ .run_if(driving_or_at_station)
43+ .after(ControlInput)
44+ .in_set(Physics),
45+ )
46+ .add_systems(Update, report_overspeed.after(Physics));
47+ }
48+}
49+
50+/// True while the train is moving under control: driving or at a platform.
51+fn driving_or_at_station(phase: Option<Res<State<Phase>>>) -> bool {
52+ phase.is_some_and(|p| matches!(**p, Phase::Driving | Phase::AtStation))
53+}
54+
55+/// True when boiler pressure is at the top of its range and steam is wasted.
56+pub fn is_venting(train: &Train) -> bool {
57+ train.pressure >= 99.5 && train.firebox > 0.5
58+}
59+
60+/// Reads controls, then advances the boiler, motion and overspeed checks.
61+fn drive(
62+ time: Res<Time>,
63+ keys: Res<ButtonInput<KeyCode>>,
64+ phase: Res<State<Phase>>,
65+ track: Res<Track>,
66+ consist: Res<Consist>,
67+ mut train: ResMut<Train>,
68+) {
69+ let dt = time.delta_secs();
70+
71+ // Controls.
72+ let raise = keys.pressed(KeyCode::KeyW) || keys.pressed(KeyCode::ArrowUp);
73+ let lower = keys.pressed(KeyCode::KeyS) || keys.pressed(KeyCode::ArrowDown);
74+ if raise {
75+ train.throttle += THROTTLE_RATE * dt;
76+ }
77+ if lower {
78+ train.throttle -= THROTTLE_RATE * dt;
79+ }
80+ train.throttle = train.throttle.clamp(0.0, 1.0);
81+ // At a platform with the throttle closed the train is held, so a grade
82+ // cannot roll it out before the driver opens the throttle.
83+ let parked = *phase.get() == Phase::AtStation && train.throttle <= 0.0;
84+ train.braking = keys.pressed(KeyCode::Space) || parked;
85+
86+ if keys.pressed(KeyCode::KeyF) && train.coal > 0.0 && train.firebox < 1.0 {
87+ let kg = (SHOVEL_KG_PER_S * dt).min(train.coal);
88+ train.coal -= kg;
89+ train.firebox = (train.firebox + SHOVEL_FIREBOX_PER_S * dt).min(1.0);
90+ }
91+
92+ // Boiler.
93+ update_boiler(&mut train, dt);
94+
95+ // Motion.
96+ let mass = consist.total_mass(train.coal).max(1.0) * 1000.0;
97+ let grade = track.grade_at(train.distance);
98+ step(&mut train, mass, grade, dt);
99+ if train.distance >= track.length {
100+ // The leg's end is a buffer stop.
101+ train.distance = track.length;
102+ train.speed = 0.0;
103+ }
104+
105+ // Overspeed damages the hull.
106+ if let Some(limit) = track.speed_limit_at(train.distance)
107+ && train.speed > limit + OVERSPEED_MARGIN
108+ {
109+ let over = train.speed - limit;
110+ train.hull = (train.hull - over * dt * OVERSPEED_HULL_RATE).max(0.0);
111+ }
112+}
113+
114+/// Tells the HUD when the train is over a limit, at most once per interval.
115+fn report_overspeed(
116+ time: Res<Time>,
117+ track: Res<Track>,
118+ train: Res<Train>,
119+ mut overspeed: MessageWriter<Overspeed>,
120+ mut cooldown: Local<f32>,
121+) {
122+ *cooldown -= time.delta_secs();
123+ if let Some(limit) = track.speed_limit_at(train.distance)
124+ && train.speed > limit + OVERSPEED_MARGIN
125+ && *cooldown <= 0.0
126+ {
127+ overspeed.write(Overspeed);
128+ *cooldown = OVERSPEED_MSG_INTERVAL;
129+ }
130+}
131+
132+/// Burns the firebox and moves pressure up or down.
133+pub fn update_boiler(train: &mut Train, dt: f32) {
134+ train.firebox = (train.firebox - FIREBOX_BURN_PER_S * dt).clamp(0.0, 1.0);
135+ let gain = train.firebox * PRESSURE_GAIN * dt;
136+ let loss = train.throttle * (0.5 + train.speed / 25.0) * PRESSURE_LOSS * dt;
137+ train.pressure = (train.pressure + gain - loss).clamp(0.0, 100.0);
138+}
139+
140+/// Advances speed and distance by one step of `dt` seconds.
141+///
142+/// `mass` is in kg and `grade` is rise per metre (positive climbs). Resistive
143+/// forces only oppose motion, and speed never goes negative.
144+pub fn step(train: &mut Train, mass: f32, grade: f32, dt: f32) {
145+ let v = train.speed;
146+ let speed_factor = (1.0 - v / 40.0).max(0.1);
147+ let tractive =
148+ train.throttle * (train.pressure / 100.0) * TRACTIVE_FORCE * speed_factor;
149+ let rolling = if v > 0.0 {
150+ ROLLING_COEF * mass * GRAVITY
151+ } else {
152+ 0.0
153+ };
154+ let air = AIR_COEF * v * v;
155+ let gravity = mass * GRAVITY * grade;
156+ let brake = if train.braking { BRAKE_FORCE } else { 0.0 };
157+
158+ let net = tractive - rolling - air - gravity - brake;
159+ let accel = net / mass;
160+ train.speed = (v + accel * dt).max(0.0);
161+ train.distance += train.speed * dt;
162+}
163+
164+#[cfg(test)]
165+mod tests {
166+ use super::*;
167+
168+ const MASS: f32 = 105_000.0;
169+
170+ fn running() -> Train {
171+ Train {
172+ pressure: 100.0,
173+ firebox: 0.8,
174+ throttle: 1.0,
175+ ..Train::default()
176+ }
177+ }
178+
179+ #[test]
180+ fn accelerates_on_the_flat() {
181+ let mut t = running();
182+ for _ in 0..100 {
183+ step(&mut t, MASS, 0.0, 0.1);
184+ }
185+ assert!(t.speed > 5.0, "speed {}", t.speed);
186+ assert!(t.distance > 0.0);
187+ }
188+
189+ #[test]
190+ fn braking_stops_without_reversing() {
191+ let mut t = running();
192+ t.throttle = 0.0;
193+ t.speed = 20.0;
194+ t.braking = true;
195+ for _ in 0..400 {
196+ step(&mut t, MASS, 0.0, 0.05);
197+ assert!(t.speed >= 0.0, "speed went negative: {}", t.speed);
198+ }
199+ assert_eq!(t.speed, 0.0);
200+ }
201+
202+ #[test]
203+ fn downhill_accelerates_from_rest() {
204+ let mut t = Train {
205+ throttle: 0.0,
206+ ..Train::default()
207+ };
208+ for _ in 0..20 {
209+ step(&mut t, MASS, -0.03, 0.1);
210+ }
211+ assert!(t.speed > 0.0, "speed {}", t.speed);
212+ }
213+
214+ #[test]
215+ fn uphill_at_rest_stays_put() {
216+ let mut t = Train {
217+ throttle: 0.0,
218+ ..Train::default()
219+ };
220+ for _ in 0..20 {
221+ step(&mut t, MASS, 0.03, 0.1);
222+ assert_eq!(t.speed, 0.0);
223+ }
224+ assert_eq!(t.distance, 0.0);
225+ }
226+
227+ #[test]
228+ fn venting_flags_full_hot_boiler() {
229+ let mut t = Train {
230+ pressure: 99.8,
231+ firebox: 0.8,
232+ ..Train::default()
233+ };
234+ assert!(is_venting(&t));
235+ t.firebox = 0.2;
236+ assert!(!is_venting(&t));
237+ }
238+}
archive/night_mail/src/world.rsadded+808 -0
@@ -0,0 +1,808 @@
1+//! World visuals and camera: the train's cars, headlight and smoke, the rail
2+//! line with track features, and the parallax night backdrop.
3+
4+use bevy::asset::RenderAssetUsages;
5+use bevy::mesh::PrimitiveTopology;
6+use bevy::prelude::*;
7+use rand::rngs::StdRng;
8+use rand::{RngExt, SeedableRng};
9+
10+use crate::model::{CarKind, Consist, FeatureKind, PX_PER_M, Physics, Track, Train};
11+use crate::stations::next_leg;
12+
13+/// Y of the rail line in world space.
14+const RAIL_Y: f32 = -150.0;
15+/// Vertical distance between the two rail lines.
16+const RAIL_GAP: f32 = 5.0;
17+/// Car body height in pixels.
18+const BODY_H: f32 = 40.0;
19+/// Y of the car body centre. The body bottom sits 6 px above the rail.
20+const BODY_CENTRE_Y: f32 = RAIL_Y + 6.0 + BODY_H / 2.0;
21+/// One metre of gap between cars.
22+const CAR_GAP: f32 = PX_PER_M;
23+/// Camera offset so the locomotive sits left of centre.
24+const CAM_LEAD: f32 = 250.0;
25+/// Half the visible width, with margin.
26+const VIEW_HALF: f32 = 900.0;
27+/// Entities further than this from the camera are hidden.
28+const CULL_RANGE: f32 = VIEW_HALF + 600.0;
29+const PUFF_LIFE: f32 = 3.0;
30+const MAX_PUFFS: usize = 150;
31+/// Telegraph pole spacing, 50 m.
32+const POLE_EVERY: f32 = 50.0 * PX_PER_M;
33+/// Sleeper spacing, 2 m.
34+const SLEEPER_EVERY: f32 = 2.0 * PX_PER_M;
35+/// Warning sign distance before a speed limit, metres.
36+const WARN_DIST_M: f32 = 200.0;
37+const STAR_TILE: f32 = 1200.0;
38+const MOUNTAIN_TILE: f32 = 1600.0;
39+/// Copies of each repeating layer. Enough to cover the view at any offset.
40+const TILE_COPIES: usize = 4;
41+const STAR_FACTOR: f32 = 0.05;
42+const MOUNTAIN_FACTOR: f32 = 0.2;
43+
44+pub struct WorldPlugin;
45+
46+impl Plugin for WorldPlugin {
47+ fn build(&self, app: &mut App) {
48+ app.insert_resource(Smoke {
49+ acc: 0.0,
50+ rng: StdRng::seed_from_u64(0x0050_CCE7),
51+ })
52+ .add_systems(Startup, setup_world)
53+ .add_systems(
54+ Update,
55+ (
56+ follow_camera,
57+ follow_ground,
58+ update_parallax,
59+ update_car_positions,
60+ sync_train_cars,
61+ // `next_leg` replaces `Track`; the rebuild must see that same
62+ // frame's change, so it runs after it.
63+ build_track_visuals.after(next_leg),
64+ cull_world,
65+ spawn_smoke,
66+ update_puffs,
67+ draw_track_gizmos,
68+ )
69+ .after(Physics),
70+ );
71+ }
72+}
73+
74+/// A car root entity. `index` is its position in the `Consist`.
75+#[derive(Component)]
76+struct Car {
77+ index: usize,
78+}
79+
80+/// A smoke puff. Its colour lives in its `MeshMaterial2d<ColorMaterial>`.
81+#[derive(Component)]
82+struct Puff {
83+ age: f32,
84+ vel: Vec2,
85+}
86+
87+/// A layer tile copy that moves with the parallax factor.
88+#[derive(Component)]
89+struct Parallax {
90+ factor: f32,
91+ tile_w: f32,
92+ copy: usize,
93+}
94+
95+/// Keeps a sprite centred horizontally on the camera.
96+#[derive(Component)]
97+struct FollowCamX;
98+
99+/// World x (px) used to hide entities far from the camera.
100+#[derive(Component)]
101+struct WorldX(f32);
102+
103+/// Anything built from the track. Despawned and rebuilt when `Track` changes.
104+#[derive(Component)]
105+struct TrackVisual;
106+
107+/// Shared handles, inserted at startup.
108+#[derive(Resource)]
109+struct WorldAssets {
110+ circle: Handle<Mesh>,
111+ wheel_mat: Handle<ColorMaterial>,
112+ glow_mat: Handle<ColorMaterial>,
113+ cone: Handle<Mesh>,
114+ cone_mat: Handle<ColorMaterial>,
115+ arrow: Handle<Mesh>,
116+ up_mat: Handle<ColorMaterial>,
117+ down_mat: Handle<ColorMaterial>,
118+ tree: Handle<Mesh>,
119+ tree_mat: Handle<ColorMaterial>,
120+}
121+
122+/// Smoke emitter state.
123+#[derive(Resource)]
124+struct Smoke {
125+ /// Fractional puffs owed from the emission rate.
126+ acc: f32,
127+ rng: StdRng,
128+}
129+
130+/// Camera x in world px. The locomotive sits left of centre.
131+fn cam_x(train: &Train) -> f32 {
132+ train.distance * PX_PER_M + CAM_LEAD
133+}
134+
135+/// World x of tile copy `copy` for a layer with the given factor.
136+///
137+/// The layer moves at `factor` of the camera's screen speed, so its world
138+/// offset is `(1 - factor) * cam`. Tiles are placed on whole multiples of
139+/// `tile_w` so the repeats line up with the visible range.
140+fn tile_x(cam: f32, factor: f32, tile_w: f32, copy: usize) -> f32 {
141+ let m0 = ((factor * cam - VIEW_HALF) / tile_w).floor();
142+ (1.0 - factor) * cam + (m0 + copy as f32) * tile_w
143+}
144+
145+fn triangle(points: [[f32; 2]; 3]) -> Mesh {
146+ let pos: Vec<[f32; 3]> = points.iter().map(|p| [p[0], p[1], 0.0]).collect();
147+ Mesh::new(
148+ PrimitiveTopology::TriangleList,
149+ RenderAssetUsages::default(),
150+ )
151+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)
152+}
153+
154+/// A stacked three-tier pine, base on y = 0, 60 px tall.
155+fn pine_mesh() -> Mesh {
156+ let tiers: [[[f32; 2]; 3]; 3] = [
157+ [[-14.0, 0.0], [14.0, 0.0], [0.0, 30.0]],
158+ [[-11.0, 14.0], [11.0, 14.0], [0.0, 44.0]],
159+ [[-7.0, 30.0], [7.0, 30.0], [0.0, 60.0]],
160+ ];
161+ let pos: Vec<[f32; 3]> = tiers
162+ .iter()
163+ .flat_map(|t| t.iter().map(|p| [p[0], p[1], 0.0]))
164+ .collect();
165+ Mesh::new(
166+ PrimitiveTopology::TriangleList,
167+ RenderAssetUsages::default(),
168+ )
169+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)
170+}
171+
172+/// One repeating mountain tile, `MOUNTAIN_TILE` px wide. The height is a sum
173+/// of integer harmonics of the tile width, so the tile joins seamlessly.
174+fn mountain_mesh() -> Mesh {
175+ const N: usize = 80;
176+ let step = MOUNTAIN_TILE / N as f32;
177+ let base = -120.0;
178+ let bottom = base - 400.0;
179+ let height = |x: f32| {
180+ let t = std::f32::consts::TAU * x / MOUNTAIN_TILE;
181+ 150.0
182+ + 70.0 * t.sin()
183+ + 40.0 * (3.0 * t + 1.1).sin()
184+ + 25.0 * (7.0 * t + 2.3).sin()
185+ + 12.0 * (13.0 * t + 0.4).sin()
186+ };
187+ let mut pos: Vec<[f32; 3]> = Vec::with_capacity(N * 6);
188+ for i in 0..N {
189+ let x0 = i as f32 * step;
190+ let x1 = x0 + step;
191+ let y0 = base + height(x0);
192+ let y1 = base + height(x1);
193+ pos.extend([
194+ [x0, bottom, 0.0],
195+ [x1, bottom, 0.0],
196+ [x1, y1, 0.0],
197+ [x0, bottom, 0.0],
198+ [x1, y1, 0.0],
199+ [x0, y0, 0.0],
200+ ]);
201+ }
202+ Mesh::new(
203+ PrimitiveTopology::TriangleList,
204+ RenderAssetUsages::default(),
205+ )
206+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)
207+}
208+
209+fn car_colour(kind: CarKind) -> Color {
210+ match kind {
211+ CarKind::Locomotive => Color::srgb(0.07, 0.07, 0.09),
212+ CarKind::Tender => Color::srgb(0.24, 0.25, 0.28),
213+ CarKind::MailCar => Color::srgb(0.5, 0.09, 0.1),
214+ }
215+}
216+
217+/// Centre x of each car in the consist, with the front car's nose at `front_px`.
218+fn car_centres(front_px: f32, consist: &Consist) -> Vec<f32> {
219+ let mut front = front_px;
220+ consist
221+ .0
222+ .iter()
223+ .map(|kind| {
224+ let half = kind.length() * PX_PER_M * 0.5;
225+ let centre = front - half;
226+ front = centre - half - CAR_GAP;
227+ centre
228+ })
229+ .collect()
230+}
231+
232+fn setup_world(
233+ mut commands: Commands,
234+ mut meshes: ResMut<Assets<Mesh>>,
235+ mut materials: ResMut<Assets<ColorMaterial>>,
236+) {
237+ let assets = WorldAssets {
238+ circle: meshes.add(Circle::new(1.0)),
239+ wheel_mat: materials.add(ColorMaterial::from(Color::srgb(0.02, 0.02, 0.025))),
240+ glow_mat: materials.add(ColorMaterial::from(Color::srgba(1.0, 0.8, 0.45, 0.22))),
241+ cone: meshes.add(triangle([[0.0, 0.0], [440.0, 100.0], [440.0, -100.0]])),
242+ cone_mat: materials.add(ColorMaterial::from(Color::srgba(1.0, 0.9, 0.55, 0.14))),
243+ arrow: meshes.add(triangle([[-4.0, -3.0], [4.0, -3.0], [0.0, 4.0]])),
244+ up_mat: materials.add(ColorMaterial::from(Color::srgb(1.0, 0.6, 0.25))),
245+ down_mat: materials.add(ColorMaterial::from(Color::srgb(0.5, 0.75, 1.0))),
246+ tree: meshes.add(pine_mesh()),
247+ tree_mat: materials.add(ColorMaterial::from(Color::srgb(0.03, 0.07, 0.07))),
248+ };
249+
250+ // Ground and ballast, centred under the camera each frame.
251+ let ground_top = RAIL_Y - 17.0;
252+ commands.spawn((
253+ FollowCamX,
254+ Sprite::from_color(Color::srgb(0.03, 0.04, 0.06), Vec2::new(6000.0, 300.0)),
255+ Transform::from_xyz(0.0, ground_top - 150.0, -30.0),
256+ ));
257+ commands.spawn((
258+ FollowCamX,
259+ Sprite::from_color(Color::srgb(0.08, 0.08, 0.11), Vec2::new(6000.0, 10.0)),
260+ Transform::from_xyz(0.0, RAIL_Y - 12.0, -29.0),
261+ ));
262+
263+ // Stars: one layout, repeated across the tile copies.
264+ let mut rng = StdRng::seed_from_u64(0x57A2);
265+ let stars: Vec<(Vec2, f32)> = (0..90)
266+ .map(|_| {
267+ (
268+ Vec2::new(
269+ rng.random_range(0.0..STAR_TILE),
270+ rng.random_range(20.0..340.0),
271+ ),
272+ rng.random_range(0.35..1.0),
273+ )
274+ })
275+ .collect();
276+ for copy in 0..TILE_COPIES {
277+ commands
278+ .spawn((
279+ Parallax {
280+ factor: STAR_FACTOR,
281+ tile_w: STAR_TILE,
282+ copy,
283+ },
284+ Transform::from_xyz(0.0, 0.0, -50.0),
285+ Visibility::default(),
286+ ))
287+ .with_children(|p| {
288+ for &(pos, alpha) in &stars {
289+ p.spawn((
290+ Sprite::from_color(Color::srgba(0.9, 0.92, 1.0, alpha), Vec2::splat(1.6)),
291+ Transform::from_translation(pos.extend(0.0)),
292+ ));
293+ }
294+ });
295+ }
296+
297+ // Distant mountain silhouette.
298+ let mountain = meshes.add(mountain_mesh());
299+ let mountain_mat = materials.add(ColorMaterial::from(Color::srgb(0.1, 0.13, 0.22)));
300+ for copy in 0..TILE_COPIES {
301+ commands.spawn((
302+ Parallax {
303+ factor: MOUNTAIN_FACTOR,
304+ tile_w: MOUNTAIN_TILE,
305+ copy,
306+ },
307+ Mesh2d(mountain.clone()),
308+ MeshMaterial2d(mountain_mat.clone()),
309+ Transform::from_xyz(0.0, 0.0, -40.0),
310+ ));
311+ }
312+
313+ commands.insert_resource(assets);
314+}
315+
316+/// Spawns one car with its wheels, details and headlight. Local coordinates
317+/// are relative to the car's centre.
318+fn spawn_car(
319+ commands: &mut Commands,
320+ assets: &WorldAssets,
321+ index: usize,
322+ kind: CarKind,
323+ is_last: bool,
324+) {
325+ let len_px = kind.length() * PX_PER_M;
326+ let half = len_px * 0.5;
327+ let wheel_y = RAIL_Y - BODY_CENTRE_Y;
328+
329+ let root = commands
330+ .spawn((
331+ Car { index },
332+ Sprite::from_color(car_colour(kind), Vec2::new(len_px, BODY_H)),
333+ Transform::from_xyz(0.0, BODY_CENTRE_Y, 0.0),
334+ ))
335+ .id();
336+
337+ commands.entity(root).with_children(|c| {
338+ // Wheels, about one per 4 m.
339+ let wheels = ((kind.length() / 4.0).round() as usize).max(2);
340+ let spacing = len_px / wheels as f32;
341+ for i in 0..wheels {
342+ let x = -half + spacing * (i as f32 + 0.5);
343+ c.spawn((
344+ Mesh2d(assets.circle.clone()),
345+ MeshMaterial2d(assets.wheel_mat.clone()),
346+ Transform::from_xyz(x, wheel_y, 0.2).with_scale(Vec3::splat(6.0)),
347+ ));
348+ }
349+
350+ // Coupling to the next car in the gap.
351+ if !is_last {
352+ c.spawn((
353+ Sprite::from_color(Color::srgb(0.05, 0.05, 0.06), Vec2::new(CAR_GAP, 4.0)),
354+ Transform::from_xyz(-half - CAR_GAP * 0.5, -14.0, 0.05),
355+ ));
356+ }
357+
358+ match kind {
359+ CarKind::Locomotive => {
360+ // Brass stripe.
361+ c.spawn((
362+ Sprite::from_color(Color::srgb(0.82, 0.6, 0.22), Vec2::new(len_px - 4.0, 3.0)),
363+ Transform::from_xyz(0.0, 4.0, 0.1),
364+ ));
365+ // Chimney with a brass cap.
366+ c.spawn((
367+ Sprite::from_color(Color::srgb(0.04, 0.04, 0.05), Vec2::new(8.0, 14.0)),
368+ Transform::from_xyz(half - 30.0, BODY_H * 0.5 + 7.0, 0.1),
369+ ));
370+ c.spawn((
371+ Sprite::from_color(Color::srgb(0.82, 0.6, 0.22), Vec2::new(12.0, 4.0)),
372+ Transform::from_xyz(half - 30.0, BODY_H * 0.5 + 16.0, 0.1),
373+ ));
374+ // Headlamp and translucent cone reaching ahead.
375+ c.spawn((
376+ Sprite::from_color(Color::srgb(1.0, 0.95, 0.7), Vec2::new(3.0, 6.0)),
377+ Transform::from_xyz(half - 1.0, -6.0, 0.2),
378+ ));
379+ c.spawn((
380+ Mesh2d(assets.cone.clone()),
381+ MeshMaterial2d(assets.cone_mat.clone()),
382+ Transform::from_xyz(half - 1.0, -6.0, 0.15),
383+ ));
384+ }
385+ CarKind::MailCar => {
386+ // Lit windows, one per 3 m.
387+ let windows = (kind.length() / 3.0).floor() as usize;
388+ let spacing = len_px / windows as f32;
389+ for i in 0..windows {
390+ let x = -half + spacing * (i as f32 + 0.5);
391+ c.spawn((
392+ Sprite::from_color(Color::srgb(1.0, 0.86, 0.45), Vec2::new(8.0, 10.0)),
393+ Transform::from_xyz(x, 2.0, 0.1),
394+ ));
395+ }
396+ }
397+ CarKind::Tender => {}
398+ }
399+ });
400+}
401+
402+/// Rebuilds the car entities whenever the consist differs from last frame.
403+fn sync_train_cars(
404+ mut commands: Commands,
405+ consist: Res<Consist>,
406+ assets: Res<WorldAssets>,
407+ existing: Query<Entity, With<Car>>,
408+ mut last: Local<Option<Consist>>,
409+) {
410+ if last.as_ref() == Some(&*consist) {
411+ return;
412+ }
413+ for e in &existing {
414+ commands.entity(e).despawn();
415+ }
416+ let count = consist.0.len();
417+ for (i, kind) in consist.0.iter().enumerate() {
418+ spawn_car(&mut commands, &assets, i, *kind, i + 1 == count);
419+ }
420+ *last = Some(consist.clone());
421+}
422+
423+/// Places each car from the front (the train's distance) backwards.
424+fn update_car_positions(
425+ train: Res<Train>,
426+ consist: Res<Consist>,
427+ mut cars: Query<(&Car, &mut Transform)>,
428+) {
429+ let centres = car_centres(train.distance * PX_PER_M, &consist);
430+ for (car, mut t) in &mut cars {
431+ if let Some(&x) = centres.get(car.index) {
432+ t.translation.x = x;
433+ }
434+ }
435+}
436+
437+fn spawn_smoke(
438+ mut commands: Commands,
439+ time: Res<Time>,
440+ train: Res<Train>,
441+ assets: Res<WorldAssets>,
442+ mut materials: ResMut<Assets<ColorMaterial>>,
443+ mut smoke: ResMut<Smoke>,
444+ puffs: Query<(), With<Puff>>,
445+) {
446+ let rate = 1.5 + 12.0 * train.throttle * train.pressure / 100.0;
447+ smoke.acc += rate * time.delta_secs();
448+
449+ let mut room = MAX_PUFFS.saturating_sub(puffs.iter().count());
450+ let origin = Vec2::new(
451+ train.distance * PX_PER_M - 30.0,
452+ BODY_CENTRE_Y + BODY_H * 0.5 + 16.0,
453+ );
454+ while smoke.acc >= 1.0 {
455+ smoke.acc -= 1.0;
456+ if room == 0 {
457+ smoke.acc = 0.0;
458+ break;
459+ }
460+ room -= 1;
461+
462+ let jitter = Vec2::new(
463+ smoke.rng.random_range(-3.0..3.0),
464+ smoke.rng.random_range(-2.0..2.0),
465+ );
466+ let vel = Vec2::new(
467+ smoke.rng.random_range(-45.0..-25.0),
468+ smoke.rng.random_range(18.0..34.0),
469+ );
470+ let mat = materials.add(ColorMaterial::from(Color::srgba(0.55, 0.57, 0.64, 0.0)));
471+ commands.spawn((
472+ Puff { age: 0.0, vel },
473+ Mesh2d(assets.circle.clone()),
474+ MeshMaterial2d(mat),
475+ Transform::from_translation((origin + jitter).extend(6.0)).with_scale(Vec3::splat(4.0)),
476+ ));
477+ }
478+}
479+
480+/// Drifts puffs back and up, grows and fades them, and despawns them after
481+/// `PUFF_LIFE` seconds.
482+fn update_puffs(
483+ mut commands: Commands,
484+ time: Res<Time>,
485+ mut materials: ResMut<Assets<ColorMaterial>>,
486+ mut puffs: Query<(
487+ Entity,
488+ &mut Puff,
489+ &mut Transform,
490+ &MeshMaterial2d<ColorMaterial>,
491+ )>,
492+) {
493+ let dt = time.delta_secs();
494+ for (e, mut puff, mut t, mat) in &mut puffs {
495+ puff.age += dt;
496+ if puff.age >= PUFF_LIFE {
497+ commands.entity(e).despawn();
498+ continue;
499+ }
500+ let k = puff.age / PUFF_LIFE;
501+ t.translation.x += puff.vel.x * dt;
502+ t.translation.y += puff.vel.y * dt;
503+ t.scale = Vec3::splat(4.0 + 16.0 * k);
504+ if let Some(mut m) = materials.get_mut(mat.0.id()) {
505+ m.color = Color::srgba(0.55, 0.57, 0.64, 0.42 * (1.0 - k));
506+ }
507+ }
508+}
509+
510+fn follow_camera(train: Res<Train>, mut cams: Query<&mut Transform, With<Camera2d>>) {
511+ let x = cam_x(&train);
512+ for mut t in &mut cams {
513+ t.translation.x = x;
514+ t.translation.y = 0.0;
515+ }
516+}
517+
518+fn follow_ground(train: Res<Train>, mut ground: Query<&mut Transform, With<FollowCamX>>) {
519+ let x = cam_x(&train);
520+ for mut t in &mut ground {
521+ t.translation.x = x;
522+ }
523+}
524+
525+fn update_parallax(train: Res<Train>, mut layers: Query<(&Parallax, &mut Transform)>) {
526+ let cam = cam_x(&train);
527+ for (layer, mut t) in &mut layers {
528+ t.translation.x = tile_x(cam, layer.factor, layer.tile_w, layer.copy);
529+ }
530+}
531+
532+/// Hides world-placed entities that are far from the camera.
533+fn cull_world(train: Res<Train>, mut q: Query<(&WorldX, &mut Visibility)>) {
534+ let cam = cam_x(&train);
535+ for (wx, mut vis) in &mut q {
536+ let want = if (wx.0 - cam).abs() <= CULL_RANGE {
537+ Visibility::Inherited
538+ } else {
539+ Visibility::Hidden
540+ };
541+ if *vis != want {
542+ *vis = want;
543+ }
544+ }
545+}
546+
547+fn spawn_root(commands: &mut Commands, x: f32) -> Entity {
548+ commands
549+ .spawn((
550+ TrackVisual,
551+ WorldX(x),
552+ Transform::from_xyz(x, 0.0, 0.0),
553+ Visibility::Hidden,
554+ ))
555+ .id()
556+}
557+
558+/// A rail-side sign post, from the rail up to y = -70.
559+fn sign_post(p: &mut ChildSpawnerCommands, x: f32) {
560+ p.spawn((
561+ Sprite::from_color(Color::srgb(0.42, 0.42, 0.48), Vec2::new(3.0, 80.0)),
562+ Transform::from_xyz(x, RAIL_Y + 40.0, -12.0),
563+ ));
564+}
565+
566+fn spawn_limit_sign(commands: &mut Commands, x: f32, kmh: i32, warning: bool) {
567+ let root = spawn_root(commands, x);
568+ let (board, ink) = if warning {
569+ (Color::srgb(1.0, 0.72, 0.22), Color::srgb(0.6, 0.05, 0.05))
570+ } else {
571+ (Color::srgb(0.92, 0.92, 0.86), Color::srgb(0.06, 0.06, 0.1))
572+ };
573+ commands.entity(root).with_children(|p| {
574+ sign_post(p, 0.0);
575+ p.spawn((
576+ Sprite::from_color(board, Vec2::splat(26.0)),
577+ Transform::from_xyz(0.0, -80.0, -11.0),
578+ ));
579+ p.spawn((
580+ Text2d::new(kmh.to_string()),
581+ TextFont::from_font_size(14.0),
582+ TextColor(ink),
583+ Transform::from_xyz(0.0, -80.0, -10.5),
584+ ));
585+ });
586+}
587+
588+fn spawn_end_sign(commands: &mut Commands, x: f32) {
589+ let root = spawn_root(commands, x);
590+ commands.entity(root).with_children(|p| {
591+ sign_post(p, 0.0);
592+ p.spawn((
593+ Sprite::from_color(Color::srgb(0.55, 0.58, 0.64), Vec2::splat(26.0)),
594+ Transform::from_xyz(0.0, -80.0, -11.0),
595+ ));
596+ p.spawn((
597+ Text2d::new("END"),
598+ TextFont::from_font_size(10.0),
599+ TextColor(Color::srgb(0.98, 0.98, 1.0)),
600+ Transform::from_xyz(0.0, -80.0, -10.5),
601+ ));
602+ });
603+}
604+
605+fn spawn_grade_sign(commands: &mut Commands, assets: &WorldAssets, x: f32, slope: f32) {
606+ let root = spawn_root(commands, x);
607+ let percent = (slope.abs() * 100.0).round() as i32;
608+ let (arrow_mat, flip) = if slope >= 0.0 {
609+ (assets.up_mat.clone(), 0.0)
610+ } else {
611+ (assets.down_mat.clone(), std::f32::consts::PI)
612+ };
613+ let arrow = assets.arrow.clone();
614+ commands.entity(root).with_children(|p| {
615+ sign_post(p, 0.0);
616+ p.spawn((
617+ Sprite::from_color(Color::srgb(0.12, 0.13, 0.18), Vec2::new(46.0, 18.0)),
618+ Transform::from_xyz(0.0, -80.0, -11.0),
619+ ));
620+ p.spawn((
621+ Mesh2d(arrow),
622+ MeshMaterial2d(arrow_mat),
623+ Transform::from_xyz(-14.0, -80.0, -10.5)
624+ .with_scale(Vec3::splat(1.2))
625+ .with_rotation(Quat::from_rotation_z(flip)),
626+ ));
627+ p.spawn((
628+ Text2d::new(format!("{percent}%")),
629+ TextFont::from_font_size(12.0),
630+ TextColor(Color::srgb(0.95, 0.95, 0.85)),
631+ Transform::from_xyz(6.0, -80.0, -10.5),
632+ ));
633+ });
634+}
635+
636+fn spawn_station(commands: &mut Commands, assets: &WorldAssets, x: f32, name: &str, len_px: f32) {
637+ let root = spawn_root(commands, x);
638+ let lamps = 4;
639+ commands.entity(root).with_children(|p| {
640+ p.spawn((
641+ Sprite::from_color(Color::srgb(0.62, 0.64, 0.68), Vec2::new(len_px, 12.0)),
642+ Transform::from_xyz(len_px * 0.5, RAIL_Y, -15.0),
643+ ));
644+ for i in 0..lamps {
645+ let lx = (i as f32 + 0.5) * len_px / lamps as f32;
646+ p.spawn((
647+ Sprite::from_color(Color::srgb(0.15, 0.15, 0.18), Vec2::new(3.0, 70.0)),
648+ Transform::from_xyz(lx, RAIL_Y + 6.0 + 35.0, -12.0),
649+ ));
650+ p.spawn((
651+ Sprite::from_color(Color::srgb(1.0, 0.85, 0.4), Vec2::splat(6.0)),
652+ Transform::from_xyz(lx, -74.0, -11.0),
653+ ));
654+ p.spawn((
655+ Mesh2d(assets.circle.clone()),
656+ MeshMaterial2d(assets.glow_mat.clone()),
657+ Transform::from_xyz(lx, -74.0, -11.5).with_scale(Vec3::splat(26.0)),
658+ ));
659+ }
660+ p.spawn((
661+ Text2d::new(name),
662+ TextFont::from_font_size(18.0),
663+ TextColor(Color::srgb(1.0, 0.88, 0.6)),
664+ Transform::from_xyz(len_px * 0.5, -48.0, -10.0),
665+ ));
666+ });
667+}
668+
669+/// Builds the track visuals once, and again whenever `Track` is replaced.
670+fn build_track_visuals(
671+ mut commands: Commands,
672+ track: Res<Track>,
673+ assets: Res<WorldAssets>,
674+ existing: Query<Entity, With<TrackVisual>>,
675+) {
676+ if !track.is_changed() {
677+ return;
678+ }
679+ for e in &existing {
680+ commands.entity(e).despawn();
681+ }
682+
683+ let end_px = track.length * PX_PER_M;
684+
685+ // Telegraph poles every 50 m, with a crossbar.
686+ let poles = (end_px / POLE_EVERY).floor() as usize;
687+ for k in 0..=poles {
688+ let x = k as f32 * POLE_EVERY;
689+ let root = spawn_root(&mut commands, x);
690+ commands.entity(root).with_children(|p| {
691+ p.spawn((
692+ Sprite::from_color(Color::srgb(0.06, 0.05, 0.05), Vec2::new(4.0, 120.0)),
693+ Transform::from_xyz(0.0, RAIL_Y + 60.0, -20.0),
694+ ));
695+ p.spawn((
696+ Sprite::from_color(Color::srgb(0.06, 0.05, 0.05), Vec2::new(34.0, 3.0)),
697+ Transform::from_xyz(0.0, RAIL_Y + 114.0, -19.9),
698+ ));
699+ });
700+ }
701+
702+ // Tree silhouettes on random spacing, kept off the platforms.
703+ let seed = track
704+ .features
705+ .iter()
706+ .map(|f| f.at as u64)
707+ .sum::<u64>()
708+ .wrapping_add(0x7EE5);
709+ let mut rng = StdRng::seed_from_u64(seed);
710+ let mut px = 120.0;
711+ while px < end_px {
712+ let near_station = track.features.iter().any(|f| {
713+ matches!(f.kind, FeatureKind::Station { .. })
714+ && px >= f.at * PX_PER_M - 60.0
715+ && px <= f.end() * PX_PER_M + 60.0
716+ });
717+ if !near_station {
718+ let s = rng.random_range(0.8..1.5);
719+ commands.spawn((
720+ TrackVisual,
721+ WorldX(px),
722+ Mesh2d(assets.tree.clone()),
723+ MeshMaterial2d(assets.tree_mat.clone()),
724+ Transform::from_xyz(px, RAIL_Y - 8.0, -21.0).with_scale(Vec3::new(s, s, 1.0)),
725+ Visibility::Hidden,
726+ ));
727+ }
728+ px += rng.random_range(160.0..460.0);
729+ }
730+
731+ // Track features.
732+ for f in &track.features {
733+ let x = f.at * PX_PER_M;
734+ match &f.kind {
735+ FeatureKind::SpeedLimit { limit, len } => {
736+ let kmh = (limit * 3.6).round() as i32;
737+ let warn_x = (f.at - WARN_DIST_M) * PX_PER_M;
738+ spawn_limit_sign(&mut commands, x, kmh, false);
739+ spawn_limit_sign(&mut commands, warn_x, kmh, true);
740+ spawn_end_sign(&mut commands, (f.at + len) * PX_PER_M);
741+ }
742+ FeatureKind::Grade { slope, .. } => {
743+ spawn_grade_sign(&mut commands, &assets, x, *slope);
744+ }
745+ FeatureKind::Station { name, platform_len } => {
746+ spawn_station(&mut commands, &assets, x, name, platform_len * PX_PER_M);
747+ }
748+ }
749+ }
750+}
751+
752+/// Immediate-mode drawing for the rails, curve tint, sleepers and wires,
753+/// limited to the visible range.
754+fn draw_track_gizmos(mut gizmos: Gizmos, train: Res<Train>, track: Res<Track>) {
755+ let cam = cam_x(&train);
756+ let end_px = track.length * PX_PER_M;
757+ let left = (cam - VIEW_HALF).max(-40.0);
758+ let right = (cam + VIEW_HALF).min(end_px + 40.0);
759+ if right <= left {
760+ return;
761+ }
762+
763+ let steel = Color::srgb(0.42, 0.48, 0.6);
764+ let tint = Color::srgb(0.66, 0.52, 0.3);
765+ let sleeper = Color::srgb(0.22, 0.16, 0.12);
766+ let wire = Color::srgb(0.25, 0.25, 0.3);
767+ let rail_ys = [RAIL_Y, RAIL_Y - RAIL_GAP];
768+
769+ for y in rail_ys {
770+ gizmos.line_2d(Vec2::new(left, y), Vec2::new(right, y), steel);
771+ }
772+
773+ // Curve sections get a slightly different rail tint.
774+ for f in &track.features {
775+ if let FeatureKind::SpeedLimit { .. } = &f.kind {
776+ let a = (f.at * PX_PER_M).max(left);
777+ let b = (f.end() * PX_PER_M).min(right);
778+ if b > a {
779+ for y in rail_ys {
780+ gizmos.line_2d(Vec2::new(a, y), Vec2::new(b, y), tint);
781+ }
782+ }
783+ }
784+ }
785+
786+ // Sleepers every 2 m, under the rails.
787+ let mut x = (left / SLEEPER_EVERY).floor() * SLEEPER_EVERY;
788+ while x <= right {
789+ gizmos.line_2d(
790+ Vec2::new(x, RAIL_Y + 2.0),
791+ Vec2::new(x, RAIL_Y - RAIL_GAP - 4.0),
792+ sleeper,
793+ );
794+ x += SLEEPER_EVERY;
795+ }
796+
797+ // Telegraph wires sagging between neighbouring poles.
798+ let max_pole = (end_px / POLE_EVERY).floor() as i64;
799+ let k0 = ((left / POLE_EVERY).floor() as i64).max(0);
800+ let k1 = ((right / POLE_EVERY).ceil() as i64).min(max_pole);
801+ for k in k0..k1 {
802+ let x0 = k as f32 * POLE_EVERY;
803+ let x1 = x0 + POLE_EVERY;
804+ let xm = (x0 + x1) * 0.5;
805+ gizmos.line_2d(Vec2::new(x0, -36.0), Vec2::new(xm, -44.0), wire);
806+ gizmos.line_2d(Vec2::new(xm, -44.0), Vec2::new(x1, -36.0), wire);
807+ }
808+}
archive/trucking/DESIGN.mdadded+22 -0
@@ -0,0 +1,22 @@
1+# Cargo: Design
2+
3+Cargo is a 2D logistics sim. You run trucks between cities under a government whose rules change every quarter.
4+
5+## Core loop
6+
7+1. Contracts appear at cities on the contract board.
8+2. The player accepts one with keys 1-5.
9+3. An idle truck drives to the pickup city, loads, then drives to the destination.
10+4. On delivery you are paid, minus the tariff for that quarter.
11+
12+## Quarterly regulations
13+
14+A quarter is 30 game days (one day is two real seconds). Every quarter the regulations change:
15+
16+- Random embargoes ban certain cargo. Contracts for embargoed cargo disappear, and a truck carrying embargoed cargo that reaches a checkpoint has its shipment turned back.
17+- The tariff percentage shifts.
18+- New checkpoints appear on roads. Every loaded truck crossing a checkpoint is inspected: it pays the inspection fee and waits a few seconds.
19+
20+## The critique
21+
22+The rules keep tightening. Each quarter the tariff, embargoes, checkpoints and inspection fees change, so the business has to keep adapting to stay profitable.
archive/trucking/src/contracts.rsadded+136 -0
@@ -0,0 +1,136 @@
1+use bevy::prelude::*;
2+
3+use crate::model::{
4+ ALL_CARGO, AcceptContract, CargoKind, CityId, Contract, ContractBoard, GameClock,
5+ QuarterChanged, Regulations, RoadNetwork, Truck,
6+};
7+use crate::regulations::on_quarter_changed;
8+
9+const MAX_OPEN: usize = 5;
10+const ACCEPT_KEYS: [KeyCode; 5] = [
11+ KeyCode::Digit1,
12+ KeyCode::Digit2,
13+ KeyCode::Digit3,
14+ KeyCode::Digit4,
15+ KeyCode::Digit5,
16+];
17+
18+pub struct ContractsPlugin;
19+
20+impl Plugin for ContractsPlugin {
21+ fn build(&self, app: &mut App) {
22+ app.add_systems(
23+ Update,
24+ (generate_contracts, read_accept_keys, apply_accept_contracts).chain(),
25+ )
26+ .add_systems(Update, drop_embargoed_contracts.after(on_quarter_changed));
27+ }
28+}
29+
30+/// On each new day: drop expired contracts, and on even days add one more if the board has room.
31+fn generate_contracts(
32+ clock: Res<GameClock>,
33+ net: Res<RoadNetwork>,
34+ regs: Res<Regulations>,
35+ mut board: ResMut<ContractBoard>,
36+ mut last_day: Local<u32>,
37+) {
38+ if clock.day == *last_day {
39+ return;
40+ }
41+ *last_day = clock.day;
42+ let day = clock.day;
43+
44+ board.open.retain(|c| day <= c.deadline_day);
45+
46+ if !day.is_multiple_of(2) || board.open.len() >= MAX_OPEN {
47+ return;
48+ }
49+ if let Some(contract) = new_contract(&net, &regs, day) {
50+ board.open.push(contract);
51+ }
52+}
53+
54+/// When the quarter changes, contracts for newly embargoed cargo disappear from the board.
55+fn drop_embargoed_contracts(
56+ mut quarters: MessageReader<QuarterChanged>,
57+ regs: Res<Regulations>,
58+ mut board: ResMut<ContractBoard>,
59+) {
60+ if quarters.read().count() == 0 {
61+ return;
62+ }
63+ board.open.retain(|c| !regs.embargoed.contains(&c.cargo));
64+}
65+
66+/// Keys 1-5 write an `AcceptContract` request for the open contract at that index.
67+fn read_accept_keys(keys: Res<ButtonInput<KeyCode>>, mut requests: MessageWriter<AcceptContract>) {
68+ if let Some(index) = ACCEPT_KEYS.iter().position(|&k| keys.just_pressed(k)) {
69+ requests.write(AcceptContract(index));
70+ }
71+}
72+
73+/// Applies `AcceptContract` requests: the contract at that index goes to the first idle truck.
74+pub fn apply_accept_contracts(
75+ mut requests: MessageReader<AcceptContract>,
76+ net: Res<RoadNetwork>,
77+ mut board: ResMut<ContractBoard>,
78+ mut trucks: Query<&mut Truck>,
79+) {
80+ for AcceptContract(index) in requests.read() {
81+ let index = *index;
82+ if index >= board.open.len() {
83+ continue;
84+ }
85+ let Some(mut truck) = trucks.iter_mut().find(|t| t.job.is_none()) else {
86+ continue;
87+ };
88+
89+ let contract = board.open.remove(index);
90+ let at = truck.at;
91+ // The path skips the first city because the truck is already there. An empty path means the truck is at pickup.
92+ truck.path = net
93+ .shortest_path(at, contract.from)
94+ .map(|p| p.into_iter().skip(1).collect())
95+ .unwrap_or_default();
96+ truck.loaded = false;
97+ truck.job = Some(contract);
98+ }
99+}
100+
101+fn new_contract(net: &RoadNetwork, regs: &Regulations, day: u32) -> Option<Contract> {
102+ let available: Vec<CargoKind> = ALL_CARGO
103+ .iter()
104+ .copied()
105+ .filter(|c| !regs.embargoed.contains(c))
106+ .collect();
107+ if available.is_empty() {
108+ return None;
109+ }
110+ let n = net.cities.len();
111+ let from = rand::random_range(0..n);
112+ let to = (from + rand::random_range(1..n)) % n;
113+ let cargo = available[rand::random_range(0..available.len())];
114+
115+ let path = net.shortest_path(CityId(from), CityId(to))?;
116+ let length = path_length(net, &path);
117+
118+ Some(Contract {
119+ cargo,
120+ from: CityId(from),
121+ to: CityId(to),
122+ pay: cargo.base_pay() + (length / 2.0) as i64,
123+ deadline_day: day + 10 + (length / 50.0) as u32,
124+ })
125+}
126+
127+fn path_length(net: &RoadNetwork, path: &[CityId]) -> f32 {
128+ path.windows(2)
129+ .filter_map(|w| {
130+ net.roads
131+ .iter()
132+ .find(|r| (r.a, r.b) == (w[0], w[1]) || (r.a, r.b) == (w[1], w[0]))
133+ })
134+ .map(|r| r.length)
135+ .sum()
136+}
archive/trucking/src/demo.rsadded+380 -0
@@ -0,0 +1,380 @@
1+//! Self-playing demo: a bot accepts contracts and narrates the rules as subtitles.
2+//! With `--record <dir>` it also saves a screenshot every 0.1 real seconds.
3+
4+use std::collections::{HashMap, VecDeque};
5+use std::path::PathBuf;
6+
7+use bevy::app::AppExit;
8+use bevy::ecs::system::SystemParam;
9+use bevy::prelude::*;
10+use bevy::render::view::screenshot::{Screenshot, save_to_disk};
11+
12+use crate::contracts::apply_accept_contracts;
13+use crate::model::{
14+ AcceptContract, CargoKind, CityId, ContractBoard, Delivered, Inspected, QuarterChanged,
15+ Regulations, Returned, RoadNetwork, Truck,
16+};
17+use crate::regulations::on_quarter_changed;
18+use crate::trucks::TruckLabel;
19+
20+/// Game speed while the demo runs: one quarter (30 days) takes about 30 real seconds.
21+const DEMO_SPEED: f32 = 2.0;
22+/// Each caption stays on screen at least this long (real seconds).
23+const MIN_SHOW_SECS: f32 = 3.5;
24+/// The bot starts acting once the four intro captions have played.
25+const INTRO_SECS: f32 = 14.0;
26+/// Real seconds from the first quarter change to the closing caption.
27+const LOOP_CAPTION_SECS: f32 = 8.0;
28+/// Real seconds the closing caption stays before a recording exits.
29+const OUTRO_HOLD_SECS: f32 = 4.0;
30+const CAPTURE_INTERVAL_SECS: f32 = 0.1;
31+const SUBTITLE_BOTTOM_PX: f32 = 80.0;
32+const SUBTITLE_FONT_SIZE: f32 = 22.0;
33+
34+const INTRO: [&str; 4] = [
35+ "Welcome to Cargo. You run a trucking company between these cities.",
36+ "Red crosses mark customs checkpoints on roads.",
37+ "Top-left: your money and the current government rules: tariff, embargoed goods, inspection fee.",
38+ "Right: available contracts. Normally you press 1-5 to accept one. I'll play for you.",
39+];
40+const WAITING_CAPTION: &str = "Waiting for contracts to appear... (one appears every 2 days)";
41+const CUSTOMS_CAPTION: &str =
42+ "Customs checkpoint: every loaded truck is inspected. We pay a $X fee and lose time.";
43+const FINAL_CAPTION: &str = "That's the loop: take contracts, plan around the rules, and keep the business alive as the rules tighten. Thanks for watching.";
44+
45+pub struct DemoPlugin {
46+ pub record_dir: Option<PathBuf>,
47+}
48+
49+impl Plugin for DemoPlugin {
50+ fn build(&self, app: &mut App) {
51+ let mut subtitle = Subtitle::default();
52+ for line in INTRO {
53+ subtitle.say(line);
54+ }
55+ app.insert_resource(subtitle)
56+ .add_systems(Startup, (set_demo_speed, spawn_subtitle_ui))
57+ .add_systems(
58+ Update,
59+ (
60+ update_subtitle,
61+ narrate
62+ .after(on_quarter_changed)
63+ .before(apply_accept_contracts),
64+ ),
65+ );
66+
67+ if let Some(dir) = &self.record_dir {
68+ std::fs::create_dir_all(dir).expect("failed to create the frames directory");
69+ app.insert_resource(Recorder {
70+ dir: dir.clone(),
71+ frame: 0,
72+ timer: Timer::from_seconds(CAPTURE_INTERVAL_SECS, TimerMode::Repeating),
73+ stop: false,
74+ })
75+ .add_systems(Update, capture_frames);
76+ }
77+ }
78+}
79+
80+// ---------------------------------------------------------------------------
81+// Subtitles
82+// ---------------------------------------------------------------------------
83+
84+#[derive(Resource, Default)]
85+struct Subtitle {
86+ queue: VecDeque<String>,
87+ current: Option<String>,
88+ shown_at: f32,
89+ /// Set by `show_final`: the caption stays up and the queue is ignored.
90+ hold: bool,
91+}
92+
93+impl Subtitle {
94+ fn say(&mut self, text: impl Into<String>) {
95+ self.queue.push_back(text.into());
96+ }
97+
98+ /// Drops everything queued and shows `text` now, for good.
99+ fn show_final(&mut self, text: &str, now: f32) {
100+ self.queue.clear();
101+ self.current = Some(text.to_string());
102+ self.shown_at = now;
103+ self.hold = true;
104+ }
105+
106+ fn current_text(&self) -> Option<&str> {
107+ self.current.as_deref()
108+ }
109+
110+ fn shown_for(&self, now: f32) -> f32 {
111+ now - self.shown_at
112+ }
113+
114+ /// Replaces the current caption with the next queued one once it has been shown long enough.
115+ fn advance(&mut self, now: f32) {
116+ if self.hold {
117+ return;
118+ }
119+ let due = self.current.is_none() || self.shown_for(now) >= MIN_SHOW_SECS;
120+ if due && let Some(next) = self.queue.pop_front() {
121+ self.current = Some(next);
122+ self.shown_at = now;
123+ }
124+ }
125+}
126+
127+#[derive(Component)]
128+struct SubtitleText;
129+
130+fn set_demo_speed(mut time: ResMut<Time<Virtual>>) {
131+ time.set_relative_speed(DEMO_SPEED);
132+}
133+
134+fn spawn_subtitle_ui(mut commands: Commands) {
135+ commands.spawn((
136+ Node {
137+ position_type: PositionType::Absolute,
138+ left: Val::Px(0.0),
139+ right: Val::Px(0.0),
140+ bottom: Val::Px(SUBTITLE_BOTTOM_PX),
141+ justify_content: JustifyContent::Center,
142+ ..default()
143+ },
144+ children![(
145+ Node {
146+ padding: UiRect::axes(Val::Px(16.0), Val::Px(10.0)),
147+ max_width: Val::Percent(80.0),
148+ ..default()
149+ },
150+ BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.7)),
151+ Text::new(""),
152+ TextFont::from_font_size(SUBTITLE_FONT_SIZE),
153+ TextColor(Color::WHITE),
154+ TextLayout::new(Justify::Center, LineBreak::WordBoundary),
155+ SubtitleText,
156+ )],
157+ ));
158+}
159+
160+fn update_subtitle(
161+ time: Res<Time<Real>>,
162+ mut subtitle: ResMut<Subtitle>,
163+ mut texts: Query<&mut Text, With<SubtitleText>>,
164+) {
165+ subtitle.advance(time.elapsed_secs());
166+ let shown = subtitle.current_text().unwrap_or("").to_string();
167+ for mut text in &mut texts {
168+ if text.0 != shown {
169+ text.0.clone_from(&shown);
170+ }
171+ }
172+}
173+
174+// ---------------------------------------------------------------------------
175+// Bot
176+// ---------------------------------------------------------------------------
177+
178+/// Remembers what the bot has already narrated, so each event is captioned once.
179+#[derive(Default)]
180+struct Bot {
181+ waiting_announced: bool,
182+ first_accept_done: bool,
183+ first_quarter_at: Option<f32>,
184+ /// When the closing caption appeared (real seconds).
185+ outro_at: Option<f32>,
186+ finished: bool,
187+ loaded: HashMap<usize, bool>,
188+}
189+
190+#[derive(SystemParam)]
191+struct Ctx<'w, 's> {
192+ real: Res<'w, Time<Real>>,
193+ regs: Res<'w, Regulations>,
194+ net: Res<'w, RoadNetwork>,
195+ board: Res<'w, ContractBoard>,
196+ trucks: Query<'w, 's, (&'static TruckLabel, &'static Truck)>,
197+ delivered: MessageReader<'w, 's, Delivered>,
198+ quarters: MessageReader<'w, 's, QuarterChanged>,
199+ inspected: MessageReader<'w, 's, Inspected>,
200+ returned: MessageReader<'w, 's, Returned>,
201+ accept: MessageWriter<'w, AcceptContract>,
202+ exit: MessageWriter<'w, AppExit>,
203+ subtitle: ResMut<'w, Subtitle>,
204+ recorder: Option<ResMut<'w, Recorder>>,
205+}
206+
207+fn city_name(net: &RoadNetwork, id: CityId) -> String {
208+ net.cities
209+ .get(id.0)
210+ .map_or_else(|| "?".to_string(), |c| c.name.clone())
211+}
212+
213+fn cargo_list(kinds: &[CargoKind]) -> String {
214+ if kinds.is_empty() {
215+ "none".to_string()
216+ } else {
217+ kinds
218+ .iter()
219+ .map(CargoKind::name)
220+ .collect::<Vec<_>>()
221+ .join(", ")
222+ }
223+}
224+
225+fn narrate(mut c: Ctx, mut bot: Local<Bot>) {
226+ let now = c.real.elapsed_secs();
227+
228+ // Deliveries.
229+ let deliveries: Vec<Delivered> = c.delivered.read().cloned().collect();
230+ for msg in &deliveries {
231+ c.subtitle.say(format!(
232+ "Delivered! Paid ${}, minus {}% government tariff = ${}.",
233+ msg.contract.pay, c.regs.tariff_pct, msg.net_pay
234+ ));
235+ }
236+
237+ // Customs inspections.
238+ for msg in c.inspected.read() {
239+ c.subtitle
240+ .say(CUSTOMS_CAPTION.replace("$X", &format!("${}", msg.fee)));
241+ }
242+
243+ // Shipments turned back because their cargo was embargoed mid-route.
244+ for msg in c.returned.read() {
245+ c.subtitle.say(format!(
246+ "Truck {}: {} is embargoed now, so customs turns the shipment back. No pay.",
247+ msg.truck,
248+ msg.cargo.name()
249+ ));
250+ }
251+
252+ // Loading: the truck turns yellow and heads to the destination.
253+ for (label, truck) in c.trucks.iter() {
254+ let was = bot.loaded.insert(label.0, truck.loaded).unwrap_or(false);
255+ if truck.loaded
256+ && !was
257+ && let Some(job) = &truck.job
258+ {
259+ c.subtitle.say(format!(
260+ "Truck {} loaded the {}. It turns yellow while carrying cargo. Now driving to {}.",
261+ label.0,
262+ job.cargo.name(),
263+ city_name(&c.net, job.to)
264+ ));
265+ }
266+ }
267+
268+ // Quarter changes: the new rules are already applied (ordered after on_quarter_changed).
269+ for QuarterChanged(_) in c.quarters.read() {
270+ c.subtitle.say(format!(
271+ "A new quarter. The government changed the rules: tariff is now {}%, embargoed: {}. \
272+ Contracts for embargoed goods disappear, and shipments on the road get turned back. \
273+ There are now {} checkpoints, and inspection fees are ${}. Each quarter the screws tighten.",
274+ c.regs.tariff_pct,
275+ cargo_list(&c.regs.embargoed),
276+ c.regs.checkpoints.len(),
277+ c.regs.inspection_fee
278+ ));
279+ if bot.first_quarter_at.is_none() {
280+ bot.first_quarter_at = Some(now);
281+ }
282+ }
283+
284+ // Closing caption, then exit a few seconds later when recording.
285+ if let Some(t) = bot.first_quarter_at
286+ && bot.outro_at.is_none()
287+ && now - t >= LOOP_CAPTION_SECS
288+ {
289+ c.subtitle.show_final(FINAL_CAPTION, now);
290+ bot.outro_at = Some(now);
291+ }
292+ if let Some(t) = bot.outro_at
293+ && !bot.finished
294+ && now - t >= OUTRO_HOLD_SECS
295+ {
296+ bot.finished = true;
297+ if let Some(recorder) = c.recorder.as_mut() {
298+ recorder.stop = true;
299+ c.exit.write(AppExit::Success);
300+ }
301+ }
302+
303+ if now < INTRO_SECS {
304+ return;
305+ }
306+
307+ // Accepting contracts.
308+ if c.board.open.is_empty() && !bot.waiting_announced {
309+ c.subtitle.say(WAITING_CAPTION);
310+ bot.waiting_announced = true;
311+ }
312+
313+ let mut idle: Vec<usize> = c
314+ .trucks
315+ .iter()
316+ .filter(|(_, t)| t.job.is_none())
317+ .map(|(l, _)| l.0)
318+ .collect();
319+ idle.sort_unstable();
320+ let Some(&truck_no) = idle.first() else {
321+ return;
322+ };
323+
324+ let legal_index = c
325+ .board
326+ .open
327+ .iter()
328+ .position(|k| !c.regs.embargoed.contains(&k.cargo));
329+ let Some(index) = legal_index else {
330+ return;
331+ };
332+
333+ let (cargo, from, to, pay) = {
334+ let k = &c.board.open[index];
335+ (
336+ k.cargo.name(),
337+ city_name(&c.net, k.from),
338+ city_name(&c.net, k.to),
339+ k.pay,
340+ )
341+ };
342+ if bot.first_accept_done {
343+ c.subtitle
344+ .say(format!("Truck {truck_no} takes {cargo} to {to}."));
345+ } else {
346+ c.subtitle.say(format!(
347+ "Accepting {cargo} from {from} to {to} for ${pay}. Truck {truck_no} (white square) drives to {from} to pick it up."
348+ ));
349+ bot.first_accept_done = true;
350+ }
351+ c.accept.write(AcceptContract(index));
352+}
353+
354+// ---------------------------------------------------------------------------
355+// Recording
356+// ---------------------------------------------------------------------------
357+
358+#[derive(Resource)]
359+struct Recorder {
360+ dir: PathBuf,
361+ frame: u32,
362+ timer: Timer,
363+ stop: bool,
364+}
365+
366+fn capture_frames(time: Res<Time<Real>>, mut recorder: ResMut<Recorder>, mut commands: Commands) {
367+ if recorder.stop {
368+ return;
369+ }
370+ recorder.timer.tick(time.delta());
371+ for _ in 0..recorder.timer.times_finished_this_tick() {
372+ let path = recorder
373+ .dir
374+ .join(format!("frame_{:05}.png", recorder.frame));
375+ recorder.frame += 1;
376+ commands
377+ .spawn(Screenshot::primary_window())
378+ .observe(save_to_disk(path));
379+ }
380+}
archive/trucking/src/hud.rsadded+261 -0
@@ -0,0 +1,261 @@
1+use std::collections::VecDeque;
2+
3+use bevy::ecs::system::SystemParam;
4+use bevy::prelude::*;
5+
6+use crate::model::{
7+ CargoKind, CityId, ContractBoard, Delivered, GameClock, Inspected, Money, QuarterChanged,
8+ Regulations, Returned, RoadNetwork, Truck,
9+};
10+use crate::trucks::TruckLabel;
11+
12+const FONT_SIZE: f32 = 15.0;
13+const LOG_LINES: usize = 5;
14+const MAX_CONTRACT_LINES: usize = 5;
15+
16+pub struct HudPlugin;
17+
18+impl Plugin for HudPlugin {
19+ fn build(&self, app: &mut App) {
20+ app.init_resource::<EventLog>()
21+ .add_systems(Startup, spawn_hud)
22+ .add_systems(Update, (collect_events, render_hud).chain());
23+ }
24+}
25+
26+/// Identifies which text entity a line belongs to, so the render system can update it.
27+#[derive(Component, Clone, Copy)]
28+enum HudSlot {
29+ Status,
30+ Log,
31+ Trucks,
32+ Contract(usize),
33+}
34+
35+#[derive(Resource, Default)]
36+struct EventLog {
37+ lines: VecDeque<String>,
38+}
39+
40+impl EventLog {
41+ fn push(&mut self, line: String) {
42+ self.lines.push_back(line);
43+ while self.lines.len() > LOG_LINES {
44+ self.lines.pop_front();
45+ }
46+ }
47+}
48+
49+fn text_color() -> Color {
50+ Color::srgb(0.9, 0.9, 0.9)
51+}
52+
53+fn panel(node: Node) -> impl Bundle {
54+ (
55+ Node {
56+ padding: UiRect::all(Val::Px(8.0)),
57+ flex_direction: FlexDirection::Column,
58+ row_gap: Val::Px(4.0),
59+ ..node
60+ },
61+ BackgroundColor(Color::srgba(0.05, 0.05, 0.08, 0.75)),
62+ )
63+}
64+
65+fn line(text: impl Into<String>, color: Color) -> impl Bundle {
66+ (
67+ Text::new(text),
68+ TextFont::from_font_size(FONT_SIZE),
69+ TextColor(color),
70+ )
71+}
72+
73+fn absolute(node: Node) -> Node {
74+ Node {
75+ position_type: PositionType::Absolute,
76+ ..node
77+ }
78+}
79+
80+fn spawn_hud(mut commands: Commands) {
81+ // Top-left: status panel above the event log.
82+ commands.spawn((
83+ absolute(Node {
84+ left: Val::Px(12.0),
85+ top: Val::Px(12.0),
86+ flex_direction: FlexDirection::Column,
87+ row_gap: Val::Px(8.0),
88+ ..default()
89+ }),
90+ children![
91+ (
92+ panel(Node::default()),
93+ children![(HudSlot::Status, line("", text_color()))],
94+ ),
95+ (
96+ panel(Node::default()),
97+ children![(HudSlot::Log, line("", text_color()))],
98+ ),
99+ ],
100+ ));
101+
102+ // Right: contract board.
103+ commands
104+ .spawn(absolute(Node {
105+ right: Val::Px(12.0),
106+ top: Val::Px(12.0),
107+ ..default()
108+ }))
109+ .with_children(|root| {
110+ root.spawn(panel(Node::default())).with_children(|p| {
111+ p.spawn(line("CONTRACTS (press 1-5)", text_color()));
112+ for i in 0..MAX_CONTRACT_LINES {
113+ p.spawn((HudSlot::Contract(i), line("", text_color())));
114+ }
115+ });
116+ });
117+
118+ // Bottom-left: one line per truck.
119+ commands
120+ .spawn(absolute(Node {
121+ left: Val::Px(12.0),
122+ bottom: Val::Px(12.0),
123+ ..default()
124+ }))
125+ .with_children(|root| {
126+ root.spawn(panel(Node::default())).with_children(|p| {
127+ p.spawn((HudSlot::Trucks, line("", text_color())));
128+ });
129+ });
130+}
131+
132+/// Turns messages into event log lines.
133+fn collect_events(
134+ mut log: ResMut<EventLog>,
135+ mut delivered: MessageReader<Delivered>,
136+ mut quarters: MessageReader<QuarterChanged>,
137+ mut inspected: MessageReader<Inspected>,
138+ mut returned: MessageReader<Returned>,
139+) {
140+ for msg in delivered.read() {
141+ log.push(format!(
142+ "Delivered {}: +${} after tariff",
143+ msg.contract.cargo.name(),
144+ msg.net_pay
145+ ));
146+ }
147+ for QuarterChanged(quarter) in quarters.read() {
148+ log.push(format!("Quarter {quarter}: new regulations"));
149+ }
150+ for msg in inspected.read() {
151+ log.push(format!("Truck {} inspected: -${} fee", msg.truck, msg.fee));
152+ }
153+ for msg in returned.read() {
154+ log.push(format!(
155+ "Truck {}: {} embargoed, shipment returned",
156+ msg.truck,
157+ msg.cargo.name()
158+ ));
159+ }
160+}
161+
162+fn city_name(net: &RoadNetwork, id: CityId) -> &str {
163+ net.cities.get(id.0).map_or("?", |c| c.name.as_str())
164+}
165+
166+/// Rebuilds every HUD text from the current state. Only writes when the string changed.
167+#[derive(SystemParam)]
168+struct HudData<'w> {
169+ money: Res<'w, Money>,
170+ clock: Res<'w, GameClock>,
171+ regs: Res<'w, Regulations>,
172+ net: Res<'w, RoadNetwork>,
173+ board: Res<'w, ContractBoard>,
174+ log: Res<'w, EventLog>,
175+}
176+
177+fn render_hud(
178+ hud: HudData,
179+ trucks: Query<(&TruckLabel, &Truck)>,
180+ mut slots: Query<(&HudSlot, &mut Text, &mut TextColor)>,
181+) {
182+ let HudData {
183+ money,
184+ clock,
185+ regs,
186+ net,
187+ board,
188+ log,
189+ } = &hud;
190+ let embargoed = if regs.embargoed.is_empty() {
191+ "none".to_string()
192+ } else {
193+ regs.embargoed
194+ .iter()
195+ .map(CargoKind::name)
196+ .collect::<Vec<_>>()
197+ .join(", ")
198+ };
199+ let status = format!(
200+ "Money: ${}\nDay {} Q {}\nTariff: {}%\nEmbargoed: {}\nInspection fee ${}",
201+ money.0, clock.day, clock.quarter, regs.tariff_pct, embargoed, regs.inspection_fee
202+ );
203+
204+ let log_text = log.lines.iter().cloned().collect::<Vec<_>>().join("\n");
205+
206+ let trucks_text = if trucks.is_empty() {
207+ "No trucks".to_string()
208+ } else {
209+ trucks
210+ .iter()
211+ .map(|(label, t)| {
212+ let state = match &t.job {
213+ None => "idle".to_string(),
214+ Some(c) if t.loaded => {
215+ format!("delivering {} to {}", c.cargo.name(), city_name(net, c.to))
216+ }
217+ Some(c) => format!("to pickup at {}", city_name(net, c.from)),
218+ };
219+ format!("Truck {}: {}", label.0, state)
220+ })
221+ .collect::<Vec<_>>()
222+ .join("\n")
223+ };
224+
225+ let contract_lines: Vec<(String, Color)> = board
226+ .open
227+ .iter()
228+ .take(MAX_CONTRACT_LINES)
229+ .enumerate()
230+ .map(|(i, c)| {
231+ let text = format!(
232+ "[{}] {} {} -> {} ${} due day {}",
233+ i + 1,
234+ c.cargo.name(),
235+ city_name(net, c.from),
236+ city_name(net, c.to),
237+ c.pay,
238+ c.deadline_day,
239+ );
240+ (text, text_color())
241+ })
242+ .collect();
243+
244+ for (slot, mut text, mut color) in &mut slots {
245+ let (new_text, new_color) = match *slot {
246+ HudSlot::Status => (status.clone(), text_color()),
247+ HudSlot::Log => (log_text.clone(), text_color()),
248+ HudSlot::Trucks => (trucks_text.clone(), text_color()),
249+ HudSlot::Contract(i) => contract_lines
250+ .get(i)
251+ .cloned()
252+ .unwrap_or_else(|| (String::new(), text_color())),
253+ };
254+ if text.0 != new_text {
255+ text.0 = new_text;
256+ }
257+ if color.0 != new_color {
258+ color.0 = new_color;
259+ }
260+ }
261+}
archive/trucking/src/main.rsadded+78 -0
@@ -0,0 +1,78 @@
1+#![forbid(unsafe_code)]
2+
3+mod contracts;
4+mod demo;
5+mod hud;
6+mod map;
7+mod model;
8+mod regulations;
9+mod trucks;
10+
11+use std::path::PathBuf;
12+
13+use bevy::prelude::*;
14+use bevy::window::WindowResolution;
15+
16+use contracts::ContractsPlugin;
17+use demo::DemoPlugin;
18+use hud::HudPlugin;
19+use map::MapPlugin;
20+use model::{
21+ AcceptContract, ContractBoard, Delivered, GameClock, Inspected, Money, QuarterChanged,
22+ Regulations, Returned, RoadNetwork,
23+};
24+use regulations::RegulationsPlugin;
25+use trucks::TrucksPlugin;
26+
27+fn main() {
28+ let args: Vec<String> = std::env::args().collect();
29+ let demo = args.iter().any(|a| a == "--demo");
30+ let record_dir = args
31+ .iter()
32+ .position(|a| a == "--record")
33+ .and_then(|i| args.get(i + 1))
34+ .map(PathBuf::from);
35+
36+ let resolution = if demo {
37+ WindowResolution::new(1280, 720)
38+ } else {
39+ WindowResolution::default()
40+ };
41+
42+ let mut app = App::new();
43+ app.add_plugins(DefaultPlugins.set(WindowPlugin {
44+ primary_window: Some(Window {
45+ title: "Cargo".into(),
46+ resolution,
47+ ..default()
48+ }),
49+ ..default()
50+ }))
51+ .add_systems(Startup, setup_camera)
52+ .init_resource::<Money>()
53+ .init_resource::<RoadNetwork>()
54+ .init_resource::<ContractBoard>()
55+ .init_resource::<Regulations>()
56+ .init_resource::<GameClock>()
57+ .add_message::<QuarterChanged>()
58+ .add_message::<Delivered>()
59+ .add_message::<AcceptContract>()
60+ .add_message::<Inspected>()
61+ .add_message::<Returned>()
62+ .add_plugins((
63+ MapPlugin,
64+ ContractsPlugin,
65+ TrucksPlugin,
66+ RegulationsPlugin,
67+ HudPlugin,
68+ ));
69+
70+ if demo {
71+ app.add_plugins(DemoPlugin { record_dir });
72+ }
73+ app.run();
74+}
75+
76+fn setup_camera(mut commands: Commands) {
77+ commands.spawn(Camera2d);
78+}
archive/trucking/src/map.rsadded+57 -0
@@ -0,0 +1,57 @@
1+use bevy::prelude::*;
2+
3+use crate::model::{Regulations, RoadNetwork};
4+
5+const CITY_RADIUS: f32 = 12.0;
6+const CHECKPOINT_HALF_SIZE: f32 = 6.0;
7+
8+/// Marks the label entity spawned for a city.
9+#[derive(Component)]
10+pub struct CityMarker;
11+
12+pub struct MapPlugin;
13+
14+impl Plugin for MapPlugin {
15+ fn build(&self, app: &mut App) {
16+ app.add_systems(Startup, spawn_city_labels)
17+ .add_systems(Update, draw_map);
18+ }
19+}
20+
21+fn spawn_city_labels(mut commands: Commands, net: Res<RoadNetwork>) {
22+ for city in &net.cities {
23+ commands.spawn((
24+ Text2d::new(city.name.clone()),
25+ Transform::from_xyz(city.pos.x, city.pos.y + CITY_RADIUS + 14.0, 1.0),
26+ CityMarker,
27+ ));
28+ }
29+}
30+
31+fn draw_map(mut gizmos: Gizmos, net: Res<RoadNetwork>, regs: Res<Regulations>) {
32+ let road_color = Color::srgb(0.5, 0.5, 0.5);
33+ let checkpoint_color = Color::srgb(0.9, 0.1, 0.1);
34+ let city_color = Color::srgb(0.85, 0.85, 0.85);
35+
36+ for road in &net.roads {
37+ let a = net.cities[road.a.0].pos;
38+ let b = net.cities[road.b.0].pos;
39+ gizmos.line_2d(a, b, road_color);
40+
41+ if regs.is_checkpoint(road.a, road.b) {
42+ let mid = (a + b) * 0.5;
43+ gizmos.cross_2d(
44+ Isometry2d::from_translation(mid),
45+ CHECKPOINT_HALF_SIZE,
46+ checkpoint_color,
47+ );
48+ }
49+ }
50+
51+ // Gizmos cannot fill shapes, so stack concentric rings to read as a disc.
52+ for city in &net.cities {
53+ for r in (1..=CITY_RADIUS as u32).step_by(2) {
54+ gizmos.circle_2d(Isometry2d::from_translation(city.pos), r as f32, city_color);
55+ }
56+ }
57+}
archive/trucking/src/model.rsadded+410 -0
@@ -0,0 +1,410 @@
1+use std::cmp::Ordering;
2+use std::collections::BinaryHeap;
3+
4+use bevy::prelude::*;
5+
6+// ---------------------------------------------------------------------------
7+// Economy
8+// ---------------------------------------------------------------------------
9+
10+#[derive(Resource, Debug, Clone)]
11+pub struct Money(pub i64);
12+
13+impl Default for Money {
14+ fn default() -> Self {
15+ Money(1000)
16+ }
17+}
18+
19+// ---------------------------------------------------------------------------
20+// Cities and roads
21+// ---------------------------------------------------------------------------
22+
23+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
24+pub struct CityId(pub usize);
25+
26+#[derive(Debug, Clone)]
27+pub struct CityInfo {
28+ pub name: String,
29+ pub pos: Vec2,
30+}
31+
32+#[derive(Debug, Clone)]
33+pub struct Road {
34+ pub a: CityId,
35+ pub b: CityId,
36+ pub length: f32,
37+}
38+
39+#[derive(Resource, Debug, Clone)]
40+pub struct RoadNetwork {
41+ pub cities: Vec<CityInfo>,
42+ pub roads: Vec<Road>,
43+}
44+
45+impl RoadNetwork {
46+ /// Cities directly connected to `c`, with the road length to each.
47+ pub fn neighbors(&self, c: CityId) -> Vec<(CityId, f32)> {
48+ self.roads
49+ .iter()
50+ .filter_map(|r| {
51+ if r.a == c {
52+ Some((r.b, r.length))
53+ } else if r.b == c {
54+ Some((r.a, r.length))
55+ } else {
56+ None
57+ }
58+ })
59+ .collect()
60+ }
61+
62+ /// Dijkstra over road lengths. The returned path includes both endpoints.
63+ pub fn shortest_path(&self, from: CityId, to: CityId) -> Option<Vec<CityId>> {
64+ let n = self.cities.len();
65+ if from.0 >= n || to.0 >= n {
66+ return None;
67+ }
68+ if from == to {
69+ return Some(vec![from]);
70+ }
71+
72+ let mut dist = vec![f32::INFINITY; n];
73+ let mut prev: Vec<Option<usize>> = vec![None; n];
74+ let mut heap = BinaryHeap::new();
75+
76+ dist[from.0] = 0.0;
77+ heap.push(HeapEntry {
78+ cost: 0.0,
79+ node: from.0,
80+ });
81+
82+ while let Some(HeapEntry { cost, node }) = heap.pop() {
83+ if node == to.0 {
84+ break;
85+ }
86+ if cost > dist[node] {
87+ continue;
88+ }
89+ for (next, len) in self.neighbors(CityId(node)) {
90+ let next_cost = cost + len;
91+ if next_cost < dist[next.0] {
92+ dist[next.0] = next_cost;
93+ prev[next.0] = Some(node);
94+ heap.push(HeapEntry {
95+ cost: next_cost,
96+ node: next.0,
97+ });
98+ }
99+ }
100+ }
101+
102+ if !dist[to.0].is_finite() {
103+ return None;
104+ }
105+
106+ let mut path = vec![to];
107+ let mut cur = to.0;
108+ while let Some(p) = prev[cur] {
109+ path.push(CityId(p));
110+ cur = p;
111+ }
112+ path.reverse();
113+ Some(path)
114+ }
115+}
116+
117+/// Min-heap entry for Dijkstra (BinaryHeap is a max-heap, so the ordering is reversed).
118+#[derive(Clone, Copy)]
119+struct HeapEntry {
120+ cost: f32,
121+ node: usize,
122+}
123+
124+impl PartialEq for HeapEntry {
125+ fn eq(&self, other: &Self) -> bool {
126+ self.cmp(other) == Ordering::Equal
127+ }
128+}
129+
130+impl Eq for HeapEntry {}
131+
132+impl PartialOrd for HeapEntry {
133+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
134+ Some(self.cmp(other))
135+ }
136+}
137+
138+impl Ord for HeapEntry {
139+ fn cmp(&self, other: &Self) -> Ordering {
140+ other
141+ .cost
142+ .total_cmp(&self.cost)
143+ .then_with(|| self.node.cmp(&other.node))
144+ }
145+}
146+
147+impl Default for RoadNetwork {
148+ fn default() -> Self {
149+ let city = |name: &str, x: f32, y: f32| CityInfo {
150+ name: name.to_string(),
151+ pos: Vec2::new(x, y),
152+ };
153+
154+ let cities = vec![
155+ city("Port Halvar", -420.0, 180.0), // 0
156+ city("Ostrem", -200.0, 240.0), // 1
157+ city("Vellmoor", 60.0, 260.0), // 2
158+ city("Kesten Ford", -300.0, -40.0), // 3
159+ city("Brask", 120.0, 40.0), // 4
160+ city("Iron Haven", 380.0, 200.0), // 5
161+ city("Saltmere", -460.0, -200.0), // 6
162+ city("Dunmarrow", 260.0, -190.0), // 7
163+ ];
164+
165+ let pairs: [(usize, usize); 11] = [
166+ (0, 1),
167+ (1, 2),
168+ (0, 3),
169+ (1, 3),
170+ (2, 4),
171+ (3, 4),
172+ (3, 6),
173+ (4, 5),
174+ (4, 7),
175+ (5, 7),
176+ (2, 5),
177+ ];
178+
179+ let roads = pairs
180+ .iter()
181+ .map(|&(a, b)| Road {
182+ a: CityId(a),
183+ b: CityId(b),
184+ length: cities[a].pos.distance(cities[b].pos),
185+ })
186+ .collect();
187+
188+ RoadNetwork { cities, roads }
189+ }
190+}
191+
192+// ---------------------------------------------------------------------------
193+// Cargo and contracts
194+// ---------------------------------------------------------------------------
195+
196+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
197+pub enum CargoKind {
198+ Grain,
199+ Medicine,
200+ Machinery,
201+ Fuel,
202+}
203+
204+/// Every cargo kind, used to pick contracts and embargoes.
205+pub const ALL_CARGO: [CargoKind; 4] = [
206+ CargoKind::Grain,
207+ CargoKind::Medicine,
208+ CargoKind::Machinery,
209+ CargoKind::Fuel,
210+];
211+
212+impl CargoKind {
213+ pub fn name(&self) -> &'static str {
214+ match self {
215+ CargoKind::Grain => "Grain",
216+ CargoKind::Medicine => "Medicine",
217+ CargoKind::Machinery => "Machinery",
218+ CargoKind::Fuel => "Fuel",
219+ }
220+ }
221+
222+ pub fn base_pay(&self) -> i64 {
223+ match self {
224+ CargoKind::Grain => 120,
225+ CargoKind::Medicine => 200,
226+ CargoKind::Machinery => 280,
227+ CargoKind::Fuel => 160,
228+ }
229+ }
230+}
231+
232+#[derive(Debug, Clone)]
233+pub struct Contract {
234+ pub cargo: CargoKind,
235+ pub from: CityId,
236+ pub to: CityId,
237+ pub pay: i64,
238+ pub deadline_day: u32,
239+}
240+
241+#[derive(Resource, Default, Debug)]
242+pub struct ContractBoard {
243+ pub open: Vec<Contract>,
244+}
245+
246+// ---------------------------------------------------------------------------
247+// Trucks
248+// ---------------------------------------------------------------------------
249+
250+/// `path` = remaining cities to visit; `progress` = 0..1 along the current road segment.
251+#[derive(Component, Debug, Clone)]
252+pub struct Truck {
253+ pub at: CityId,
254+ pub path: Vec<CityId>,
255+ pub progress: f32,
256+ pub job: Option<Contract>,
257+ pub loaded: bool,
258+ pub speed: f32,
259+ /// Seconds left waiting at a customs inspection; the truck does not move while > 0.
260+ pub wait: f32,
261+}
262+
263+// ---------------------------------------------------------------------------
264+// Regulations
265+// ---------------------------------------------------------------------------
266+
267+#[derive(Resource, Debug, Clone)]
268+pub struct Regulations {
269+ pub embargoed: Vec<CargoKind>,
270+ pub tariff_pct: i64,
271+ pub checkpoints: Vec<(CityId, CityId)>,
272+ pub inspection_fee: i64,
273+}
274+
275+impl Default for Regulations {
276+ fn default() -> Self {
277+ Regulations {
278+ embargoed: Vec::new(),
279+ tariff_pct: 10,
280+ checkpoints: Vec::new(),
281+ inspection_fee: 100,
282+ }
283+ }
284+}
285+
286+impl Regulations {
287+ /// Order-independent: (a, b) and (b, a) are the same road.
288+ pub fn is_checkpoint(&self, a: CityId, b: CityId) -> bool {
289+ self.checkpoints
290+ .iter()
291+ .any(|&(x, y)| (x == a && y == b) || (x == b && y == a))
292+ }
293+}
294+
295+// ---------------------------------------------------------------------------
296+// Clock
297+// ---------------------------------------------------------------------------
298+
299+#[derive(Resource, Debug)]
300+pub struct GameClock {
301+ pub day: u32,
302+ pub quarter: u32,
303+ /// Repeating; one tick = one game day.
304+ pub timer: Timer,
305+}
306+
307+impl Default for GameClock {
308+ fn default() -> Self {
309+ GameClock {
310+ day: 1,
311+ quarter: 1,
312+ timer: Timer::from_seconds(2.0, TimerMode::Repeating),
313+ }
314+ }
315+}
316+
317+// ---------------------------------------------------------------------------
318+// Messages
319+// ---------------------------------------------------------------------------
320+
321+#[derive(Message, Debug, Clone)]
322+pub struct QuarterChanged(pub u32);
323+
324+#[derive(Message, Debug, Clone)]
325+pub struct Delivered {
326+ pub contract: Contract,
327+ pub net_pay: i64,
328+}
329+
330+/// A loaded truck was inspected at a customs checkpoint and paid `fee`.
331+#[derive(Message, Debug, Clone, Copy)]
332+pub struct Inspected {
333+ pub truck: usize,
334+ pub fee: i64,
335+}
336+
337+/// A truck's cargo became embargoed mid-route, so customs turned it back. No pay.
338+#[derive(Message, Debug, Clone, Copy)]
339+pub struct Returned {
340+ pub truck: usize,
341+ pub cargo: CargoKind,
342+}
343+
344+/// Programmatic request to accept the open contract at this index into the first idle truck.
345+#[derive(Message, Debug, Clone, Copy)]
346+pub struct AcceptContract(pub usize);
347+
348+// ---------------------------------------------------------------------------
349+// Tests
350+// ---------------------------------------------------------------------------
351+
352+#[cfg(test)]
353+mod tests {
354+ use super::*;
355+
356+ #[test]
357+ fn shortest_path_exists_between_all_pairs() {
358+ let net = RoadNetwork::default();
359+ let n = net.cities.len();
360+ for a in 0..n {
361+ for b in 0..n {
362+ let path = net
363+ .shortest_path(CityId(a), CityId(b))
364+ .unwrap_or_else(|| panic!("no path {a} -> {b}"));
365+ assert_eq!(path.first(), Some(&CityId(a)), "wrong start for {a} -> {b}");
366+ assert_eq!(path.last(), Some(&CityId(b)), "wrong end for {a} -> {b}");
367+ }
368+ }
369+ }
370+
371+ #[test]
372+ fn shortest_path_same_city_is_single_node() {
373+ let net = RoadNetwork::default();
374+ assert_eq!(
375+ net.shortest_path(CityId(2), CityId(2)),
376+ Some(vec![CityId(2)])
377+ );
378+ }
379+
380+ #[test]
381+ fn shortest_path_out_of_range_is_none() {
382+ let net = RoadNetwork::default();
383+ assert_eq!(net.shortest_path(CityId(0), CityId(99)), None);
384+ }
385+
386+ #[test]
387+ fn shortest_path_consecutive_cities_are_connected() {
388+ let net = RoadNetwork::default();
389+ let path = net.shortest_path(CityId(0), CityId(7)).unwrap();
390+ for w in path.windows(2) {
391+ assert!(
392+ net.neighbors(w[0]).iter().any(|(c, _)| *c == w[1]),
393+ "{:?} and {:?} are not connected",
394+ w[0],
395+ w[1]
396+ );
397+ }
398+ }
399+
400+ #[test]
401+ fn checkpoint_check_is_order_independent() {
402+ let regs = Regulations {
403+ checkpoints: vec![(CityId(1), CityId(3))],
404+ ..Default::default()
405+ };
406+ assert!(regs.is_checkpoint(CityId(1), CityId(3)));
407+ assert!(regs.is_checkpoint(CityId(3), CityId(1)));
408+ assert!(!regs.is_checkpoint(CityId(1), CityId(2)));
409+ }
410+}
archive/trucking/src/regulations.rsadded+63 -0
@@ -0,0 +1,63 @@
1+use bevy::prelude::*;
2+use rand::RngExt;
3+use rand::seq::IndexedRandom;
4+
5+use crate::model::{ALL_CARGO, CityId, GameClock, QuarterChanged, Regulations, RoadNetwork};
6+
7+pub struct RegulationsPlugin;
8+
9+impl Plugin for RegulationsPlugin {
10+ fn build(&self, app: &mut App) {
11+ app.add_systems(Startup, seed_checkpoints)
12+ .add_systems(Update, (tick_clock, on_quarter_changed).chain());
13+ }
14+}
15+
16+/// Advances the game clock one day per finished timer tick and emits `QuarterChanged` on each new quarter.
17+fn tick_clock(
18+ time: Res<Time>,
19+ mut clock: ResMut<GameClock>,
20+ mut quarters: MessageWriter<QuarterChanged>,
21+) {
22+ clock.timer.tick(time.delta());
23+ for _ in 0..clock.timer.times_finished_this_tick() {
24+ clock.day += 1;
25+ if clock.day > 1 && (clock.day - 1).is_multiple_of(30) {
26+ clock.quarter += 1;
27+ quarters.write(QuarterChanged(clock.quarter));
28+ }
29+ }
30+}
31+
32+/// Re-rolls the regulations for the new quarter. Stricter as the quarter goes on.
33+pub fn on_quarter_changed(
34+ mut quarters: MessageReader<QuarterChanged>,
35+ net: Res<RoadNetwork>,
36+ mut regs: ResMut<Regulations>,
37+) {
38+ let mut rng = rand::rng();
39+ for QuarterChanged(quarter) in quarters.read() {
40+ let embargo_count = rng.random_range(0..=2);
41+ regs.embargoed = ALL_CARGO.sample(&mut rng, embargo_count).copied().collect();
42+ regs.tariff_pct = rng.random_range(5..=35);
43+ regs.checkpoints = pick_checkpoints(&net, &mut rng, 2 + *quarter as usize);
44+ regs.inspection_fee = 100 + 50 * i64::from(*quarter);
45+ }
46+}
47+
48+/// Quarter 1 starts with two checkpoints so the map is not empty.
49+fn seed_checkpoints(mut regs: ResMut<Regulations>, net: Res<RoadNetwork>) {
50+ regs.checkpoints = pick_checkpoints(&net, &mut rand::rng(), 2);
51+}
52+
53+/// Picks up to `count` distinct roads as checkpoints.
54+fn pick_checkpoints(
55+ net: &RoadNetwork,
56+ rng: &mut impl rand::Rng,
57+ count: usize,
58+) -> Vec<(CityId, CityId)> {
59+ net.roads
60+ .sample(rng, count.min(net.roads.len()))
61+ .map(|road| (road.a, road.b))
62+ .collect()
63+}
archive/trucking/src/trucks.rsadded+168 -0
@@ -0,0 +1,168 @@
1+use bevy::prelude::*;
2+
3+use crate::model::{
4+ CityId, Delivered, Inspected, Money, Regulations, Returned, RoadNetwork, Truck,
5+};
6+
7+/// Seconds a loaded truck waits at a customs checkpoint after paying the fee.
8+const INSPECTION_WAIT_SECS: f32 = 3.0;
9+
10+/// Display index (1, 2) for a truck. Read by the HUD, not by this plugin.
11+#[derive(Component, Debug)]
12+pub struct TruckLabel(pub usize);
13+
14+pub struct TrucksPlugin;
15+
16+impl Plugin for TrucksPlugin {
17+ fn build(&self, app: &mut App) {
18+ app.add_systems(Startup, spawn_trucks)
19+ .add_systems(Update, (move_trucks, arrive_at_cities, draw_trucks).chain());
20+ }
21+}
22+
23+fn spawn_trucks(mut commands: Commands, net: Res<RoadNetwork>) {
24+ let start = net.cities[0].pos;
25+ for label in 1..=2 {
26+ commands.spawn((
27+ Truck {
28+ at: CityId(0),
29+ path: vec![],
30+ progress: 0.0,
31+ job: None,
32+ loaded: false,
33+ speed: 120.0,
34+ wait: 0.0,
35+ },
36+ Transform::from_xyz(start.x, start.y, 1.0),
37+ TruckLabel(label),
38+ ));
39+ }
40+}
41+
42+/// Length of the road between two adjacent cities, falling back to straight-line distance.
43+fn road_length(net: &RoadNetwork, a: CityId, b: CityId) -> f32 {
44+ net.roads
45+ .iter()
46+ .find(|r| (r.a == a && r.b == b) || (r.a == b && r.b == a))
47+ .map(|r| r.length)
48+ .unwrap_or_else(|| net.cities[a.0].pos.distance(net.cities[b.0].pos))
49+}
50+
51+fn move_trucks(
52+ time: Res<Time>,
53+ net: Res<RoadNetwork>,
54+ regs: Res<Regulations>,
55+ mut money: ResMut<Money>,
56+ mut inspected: MessageWriter<Inspected>,
57+ mut returned: MessageWriter<Returned>,
58+ mut trucks: Query<(&mut Truck, &mut Transform, &TruckLabel)>,
59+) {
60+ let dt = time.delta_secs();
61+ for (mut truck, mut transform, label) in &mut trucks {
62+ if truck.wait > 0.0 {
63+ truck.wait = (truck.wait - dt).max(0.0);
64+ continue;
65+ }
66+ let Some(&next) = truck.path.first() else {
67+ continue;
68+ };
69+ let length = road_length(&net, truck.at, next).max(f32::EPSILON);
70+ truck.progress += truck.speed * dt / length;
71+
72+ if truck.progress >= 1.0 {
73+ let at_checkpoint = truck.loaded && regs.is_checkpoint(truck.at, next);
74+ let embargoed = truck
75+ .job
76+ .as_ref()
77+ .is_some_and(|j| regs.embargoed.contains(&j.cargo));
78+ if at_checkpoint && embargoed {
79+ // Customs turns the shipment back at the last city. No pay, no fee.
80+ if let Some(job) = truck.job.as_ref() {
81+ returned.write(Returned {
82+ truck: label.0,
83+ cargo: job.cargo,
84+ });
85+ }
86+ truck.job = None;
87+ truck.loaded = false;
88+ truck.path.clear();
89+ truck.progress = 0.0;
90+ // Snap the sprite back to the city the truck is turned back at.
91+ transform.translation = net.cities[truck.at.0].pos.extend(transform.translation.z);
92+ continue;
93+ }
94+ truck.at = next;
95+ truck.path.remove(0);
96+ truck.progress = 0.0;
97+ if at_checkpoint {
98+ money.0 -= regs.inspection_fee;
99+ inspected.write(Inspected {
100+ truck: label.0,
101+ fee: regs.inspection_fee,
102+ });
103+ truck.wait = INSPECTION_WAIT_SECS;
104+ transform.translation = net.cities[next.0].pos.extend(transform.translation.z);
105+ continue;
106+ }
107+ }
108+
109+ // Interpolate between the segment's endpoints; `progress` is clamped so the truck never overshoots.
110+ let from = net.cities[truck.at.0].pos;
111+ let to = net.cities[next.0].pos;
112+ let pos = from.lerp(to, truck.progress.clamp(0.0, 1.0));
113+ transform.translation.x = pos.x;
114+ transform.translation.y = pos.y;
115+ }
116+}
117+
118+fn arrive_at_cities(
119+ net: Res<RoadNetwork>,
120+ regs: Res<Regulations>,
121+ mut money: ResMut<Money>,
122+ mut delivered: MessageWriter<Delivered>,
123+ mut trucks: Query<&mut Truck>,
124+) {
125+ for mut truck in &mut trucks {
126+ if !truck.path.is_empty() {
127+ continue;
128+ }
129+ let Some(job) = truck.job.clone() else {
130+ continue;
131+ };
132+
133+ if !truck.loaded {
134+ if truck.at == job.from {
135+ truck.loaded = true;
136+ if let Some(mut path) = net.shortest_path(job.from, job.to) {
137+ path.remove(0);
138+ truck.path = path;
139+ }
140+ }
141+ } else if truck.at == job.to {
142+ let tariff = job.pay * regs.tariff_pct / 100;
143+ let net_pay = job.pay - tariff;
144+ money.0 += net_pay;
145+ delivered.write(Delivered {
146+ contract: job,
147+ net_pay,
148+ });
149+ truck.job = None;
150+ truck.loaded = false;
151+ }
152+ }
153+}
154+
155+fn draw_trucks(mut gizmos: Gizmos, trucks: Query<(&Truck, &Transform)>) {
156+ for (truck, transform) in &trucks {
157+ let color = if truck.loaded {
158+ Color::srgb(1.0, 0.85, 0.1)
159+ } else {
160+ Color::WHITE
161+ };
162+ gizmos.rect_2d(
163+ Isometry2d::from_translation(transform.translation.truncate()),
164+ Vec2::splat(14.0),
165+ color,
166+ );
167+ }
168+}
src/audio.rsadded+432 -0
@@ -0,0 +1,432 @@
1+//! Placeholder sound. Every effect is synthesised at startup as a 16-bit mono WAV
2+//! held in memory, so no asset files ship with the game.
3+
4+use std::f32::consts::TAU;
5+use std::sync::Arc;
6+
7+use bevy::audio::{
8+ AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, PlaybackSettings, Volume,
9+};
10+use bevy::prelude::*;
11+use bevy::ui_widgets::Activate;
12+
13+use crate::model::Notify;
14+use crate::settings::Settings;
15+
16+const RATE: u32 = 44_100;
17+const RATE_F: f32 = 44_100.0;
18+/// Minimum gap between two plays of the same sound.
19+const DEFAULT_GAP: f64 = 0.15;
20+/// Whistles are long, so they get their own, wider gap.
21+const WHISTLE_GAP: f64 = 1.5;
22+/// Telegraph news beeps are at most this often.
23+const TELEGRAPH_GAP: f64 = 2.0;
24+
25+/// A sound the game asks for. Gameplay systems write these, `play_sounds` plays them.
26+#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
27+pub enum SoundEvent {
28+ Click,
29+ TrackLaid,
30+ TrainDeparts,
31+ Raid,
32+ Telegraph,
33+ Victory,
34+ Defeat,
35+}
36+
37+const SOUND_COUNT: usize = 7;
38+
39+impl SoundEvent {
40+ fn slot(self) -> usize {
41+ self as usize
42+ }
43+
44+ fn min_gap(self) -> f64 {
45+ match self {
46+ SoundEvent::TrainDeparts => WHISTLE_GAP,
47+ _ => DEFAULT_GAP,
48+ }
49+ }
50+}
51+
52+pub struct GameAudioPlugin;
53+
54+impl Plugin for GameAudioPlugin {
55+ fn build(&self, app: &mut App) {
56+ app.add_message::<SoundEvent>()
57+ .init_resource::<SoundLimiter>()
58+ .add_observer(on_activate)
59+ .add_systems(Startup, build_sfx)
60+ .add_systems(Update, sync_ambient)
61+ .add_systems(PostUpdate, play_sounds);
62+ }
63+}
64+
65+/// Handles for every one-shot sound.
66+#[derive(Resource)]
67+struct Sfx {
68+ click: Handle<AudioSource>,
69+ track_laid: Handle<AudioSource>,
70+ train_departs: Handle<AudioSource>,
71+ raid: Handle<AudioSource>,
72+ telegraph: Handle<AudioSource>,
73+ victory: Handle<AudioSource>,
74+ defeat: Handle<AudioSource>,
75+}
76+
77+/// Marks the looping ambient bed, whose volume follows the settings.
78+#[derive(Component)]
79+struct AmbientBed;
80+
81+/// Last play time per sound, and last telegraph time, in real seconds.
82+#[derive(Resource)]
83+struct SoundLimiter {
84+ last: [f64; SOUND_COUNT],
85+ telegraph: f64,
86+}
87+
88+impl Default for SoundLimiter {
89+ fn default() -> Self {
90+ Self {
91+ last: [f64::NEG_INFINITY; SOUND_COUNT],
92+ telegraph: f64::NEG_INFINITY,
93+ }
94+ }
95+}
96+
97+fn on_activate(_: On<Activate>, mut sounds: MessageWriter<SoundEvent>) {
98+ sounds.write(SoundEvent::Click);
99+}
100+
101+fn build_sfx(mut commands: Commands, sources: Option<ResMut<Assets<AudioSource>>>) {
102+ // Without the audio plugin (harness runs) there is no asset type to fill, so stay silent.
103+ let Some(mut sources) = sources else {
104+ return;
105+ };
106+ let mut add_source = |samples: Vec<f32>| {
107+ sources.add(AudioSource {
108+ bytes: encode_wav(&samples),
109+ })
110+ };
111+ let sfx = Sfx {
112+ click: add_source(click()),
113+ track_laid: add_source(track_laid()),
114+ train_departs: add_source(train_departs()),
115+ raid: add_source(raid()),
116+ telegraph: add_source(telegraph()),
117+ victory: add_source(victory()),
118+ defeat: add_source(defeat()),
119+ };
120+ let ambient = add_source(ambient());
121+ commands.spawn((
122+ AudioPlayer(ambient),
123+ PlaybackSettings::LOOP.with_volume(Volume::Linear(0.0)),
124+ AmbientBed,
125+ ));
126+ commands.insert_resource(sfx);
127+}
128+
129+/// Keeps the ambient bed at master * ambient, or silent when muted.
130+fn sync_ambient(settings: Res<Settings>, mut beds: Query<&mut AudioSink, With<AmbientBed>>) {
131+ let audio = &settings.audio;
132+ let level = if audio.muted {
133+ 0.0
134+ } else {
135+ audio.master * audio.ambient
136+ };
137+ for mut sink in &mut beds {
138+ sink.set_volume(Volume::Linear(level));
139+ }
140+}
141+
142+/// Plays queued sounds as one-shots. Runs after all Update systems, so a raid and the
143+/// news from the same frame are both visible here.
144+fn play_sounds(
145+ mut commands: Commands,
146+ sfx: Option<Res<Sfx>>,
147+ settings: Res<Settings>,
148+ time: Res<Time<Real>>,
149+ mut limiter: ResMut<SoundLimiter>,
150+ mut events: MessageReader<SoundEvent>,
151+ mut notes: MessageReader<Notify>,
152+) {
153+ let now = time.elapsed_secs_f64();
154+ let mut queue: Vec<SoundEvent> = events.read().copied().collect();
155+
156+ // News: one telegraph beep per window, and none in a frame that also has a raid.
157+ let any_note = notes.read().next().is_some();
158+ let raid_now = queue.contains(&SoundEvent::Raid);
159+ if any_note && !raid_now && now - limiter.telegraph >= TELEGRAPH_GAP {
160+ queue.push(SoundEvent::Telegraph);
161+ }
162+
163+ let Some(sfx) = sfx else {
164+ return;
165+ };
166+ let audio = &settings.audio;
167+ if audio.muted || audio.master * audio.effects <= 0.0 {
168+ return;
169+ }
170+ let volume = Volume::Linear(audio.master * audio.effects);
171+
172+ for sound in queue {
173+ let slot = sound.slot();
174+ if now - limiter.last[slot] < sound.min_gap() {
175+ continue;
176+ }
177+ limiter.last[slot] = now;
178+ let handle = match sound {
179+ SoundEvent::Click => &sfx.click,
180+ SoundEvent::TrackLaid => &sfx.track_laid,
181+ SoundEvent::TrainDeparts => &sfx.train_departs,
182+ SoundEvent::Raid => &sfx.raid,
183+ SoundEvent::Telegraph => {
184+ limiter.telegraph = now;
185+ &sfx.telegraph
186+ }
187+ SoundEvent::Victory => &sfx.victory,
188+ SoundEvent::Defeat => &sfx.defeat,
189+ };
190+ commands.spawn((
191+ AudioPlayer::new(handle.clone()),
192+ PlaybackSettings::DESPAWN.with_volume(volume),
193+ ));
194+ }
195+}
196+
197+// ---------------------------------------------------------------------------
198+// Synthesis. Each function returns mono samples in [-1, 1] at RATE.
199+// ---------------------------------------------------------------------------
200+
201+fn samples(secs: f32) -> usize {
202+ (secs * RATE_F).round() as usize
203+}
204+
205+fn sine(freq: f32, t: f32) -> f32 {
206+ (TAU * freq * t).sin()
207+}
208+
209+/// Adds `sample(t)` into `buf` from `start` for `dur` seconds, where `t` is local time.
210+fn add(buf: &mut [f32], start: f32, dur: f32, mut sample: impl FnMut(f32) -> f32) {
211+ let first = (start * RATE_F).round() as usize;
212+ for i in 0..samples(dur) {
213+ let Some(slot) = buf.get_mut(first + i) else {
214+ break;
215+ };
216+ *slot += sample(i as f32 / RATE_F);
217+ }
218+}
219+
220+/// Fade in over `attack` seconds and fade out over the last `release` seconds of `dur`.
221+fn env(t: f32, dur: f32, attack: f32, release: f32) -> f32 {
222+ let a = if attack > 0.0 {
223+ (t / attack).min(1.0)
224+ } else {
225+ 1.0
226+ };
227+ let r = if release > 0.0 {
228+ ((dur - t) / release).clamp(0.0, 1.0)
229+ } else {
230+ 1.0
231+ };
232+ a.min(r)
233+}
234+
235+fn normalize(buf: &mut [f32], peak: f32) {
236+ let max = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
237+ if max > 0.0 {
238+ let gain = peak / max;
239+ for s in buf.iter_mut() {
240+ *s *= gain;
241+ }
242+ }
243+}
244+
245+/// Xorshift noise, so every run produces the same sounds.
246+struct Noise(u32);
247+
248+impl Noise {
249+ fn white(&mut self) -> f32 {
250+ let mut x = self.0;
251+ x ^= x << 13;
252+ x ^= x >> 17;
253+ x ^= x << 5;
254+ self.0 = x;
255+ x as f32 / u32::MAX as f32 * 2.0 - 1.0
256+ }
257+}
258+
259+/// One-pole low-pass run twice around the loop, so the filter state is already settled
260+/// at the seam and the looped output is continuous.
261+fn lowpass_loop(x: &[f32], alpha: f32) -> Vec<f32> {
262+ let n = x.len();
263+ let mut y = 0.0;
264+ let mut out = Vec::with_capacity(n);
265+ for i in 0..2 * n {
266+ y += alpha * (x[i % n] - y);
267+ if i >= n {
268+ out.push(y);
269+ }
270+ }
271+ out
272+}
273+
274+/// Soft wooden tick, 40 ms.
275+fn click() -> Vec<f32> {
276+ const DUR: f32 = 0.04;
277+ let mut buf = vec![0.0; samples(DUR)];
278+ let mut noise = Noise(0x9E37_79B9);
279+ add(&mut buf, 0.0, DUR, |t| {
280+ let body =
281+ sine(1400.0, t) * (-t * 110.0).exp() + 0.5 * sine(2900.0, t) * (-t * 200.0).exp();
282+ let knock = noise.white() * (-t * 400.0).exp() * 0.3;
283+ (0.5 * body + knock) * env(t, DUR, 0.001, 0.01)
284+ });
285+ buf
286+}
287+
288+/// Two hammer clanks on rail: inharmonic partials plus a little noise.
289+fn track_laid() -> Vec<f32> {
290+ const DUR: f32 = 0.55;
291+ let mut buf = vec![0.0; samples(DUR)];
292+ let mut noise = Noise(0x2545_F491);
293+ for start in [0.0, 0.2] {
294+ add(&mut buf, start, 0.35, |t| {
295+ let ring = 0.5 * sine(1250.0, t) + 0.3 * sine(1880.0, t) + 0.2 * sine(3140.0, t);
296+ let clank = ring * (-t * 18.0).exp() * 0.35 + noise.white() * (-t * 70.0).exp() * 0.2;
297+ clank * env(t, 0.35, 0.001, 0.08)
298+ });
299+ }
300+ buf
301+}
302+
303+/// Steam whistle, 0.8 s: two detuned sines around 650 Hz with vibrato, plus breath noise.
304+fn train_departs() -> Vec<f32> {
305+ const DUR: f32 = 0.8;
306+ let mut buf = vec![0.0; samples(DUR)];
307+ let mut noise = Noise(0x0BAD_5EED);
308+ let (mut phase_a, mut phase_b, mut breath) = (0.0f32, 0.0f32, 0.0f32);
309+ add(&mut buf, 0.0, DUR, |t| {
310+ let freq = 650.0 * (1.0 + 0.015 * sine(5.5, t));
311+ phase_a = (phase_a + TAU * freq / RATE_F) % TAU;
312+ phase_b = (phase_b + TAU * freq * 1.012 / RATE_F) % TAU;
313+ breath += 0.15 * (noise.white() - breath);
314+ let whistle = 0.3 * phase_a.sin() + 0.2 * phase_b.sin();
315+ (whistle + 0.4 * breath) * env(t, DUR, 0.08, 0.25)
316+ });
317+ buf
318+}
319+
320+/// Distant explosion, about 1.2 s: low-passed noise burst over a 50-58 Hz thump.
321+fn raid() -> Vec<f32> {
322+ const DUR: f32 = 1.2;
323+ let mut buf = vec![0.0; samples(DUR)];
324+ let mut noise = Noise(0x1234_5678);
325+ let (mut low, mut lower, mut thump_phase) = (0.0f32, 0.0f32, 0.0f32);
326+ add(&mut buf, 0.0, DUR, |t| {
327+ low += 0.05 * (noise.white() - low);
328+ lower += 0.05 * (low - lower);
329+ let blast = lower * 15.0 * (-t * 3.5).exp() * env(t, DUR, 0.01, 0.2);
330+ thump_phase = (thump_phase + TAU * (50.0 + 8.0 * (-t * 8.0).exp()) / RATE_F) % TAU;
331+ let thump = thump_phase.sin() * (-t * 5.0).exp();
332+ blast + 0.8 * thump
333+ });
334+ normalize(&mut buf, 0.8);
335+ buf
336+}
337+
338+/// Morse-like telegraph: dot, dot, dash, dot at 800 Hz.
339+fn telegraph() -> Vec<f32> {
340+ const DUR: f32 = 0.6;
341+ let mut buf = vec![0.0; samples(DUR)];
342+ for (start, len) in [(0.0, 0.06), (0.11, 0.06), (0.22, 0.15), (0.42, 0.06)] {
343+ add(&mut buf, start, len, |t| {
344+ (0.3 * sine(800.0, t) + 0.1 * sine(1600.0, t)) * env(t, len, 0.004, 0.01)
345+ });
346+ }
347+ buf
348+}
349+
350+/// One decaying plucked tone with a soft octave overtone.
351+fn chime(buf: &mut [f32], freq: f32, start: f32, dur: f32, amp: f32, decay: f32) {
352+ add(buf, start, dur, |t| {
353+ (sine(freq, t) + 0.15 * sine(2.0 * freq, t))
354+ * amp
355+ * (-t * decay).exp()
356+ * env(t, dur, 0.008, dur * 0.3)
357+ });
358+}
359+
360+/// Three quick notes, then the chord held to 1.5 s in total.
361+fn fanfare(run: [f32; 3], chord: [f32; 3]) -> Vec<f32> {
362+ const DUR: f32 = 1.5;
363+ let mut buf = vec![0.0; samples(DUR)];
364+ for (i, freq) in run.into_iter().enumerate() {
365+ chime(&mut buf, freq, i as f32 * 0.2, 0.6, 0.3, 4.0);
366+ }
367+ for freq in chord {
368+ chime(&mut buf, freq, 0.6, 0.9, 0.16, 1.5);
369+ }
370+ buf
371+}
372+
373+/// Rising major triad C-E-G.
374+fn victory() -> Vec<f32> {
375+ fanfare([523.25, 659.25, 783.99], [523.25, 659.25, 783.99])
376+}
377+
378+/// Falling notes into a low C minor chord.
379+fn defeat() -> Vec<f32> {
380+ fanfare([392.0, 311.13, 261.63], [130.81, 155.56, 196.0])
381+}
382+
383+/// Ten-second wind and rumble bed. Every component repeats exactly every 10 s, so the
384+/// loop is seamless. Two distant artillery thuds sit inside the loop and decay before it ends.
385+fn ambient() -> Vec<f32> {
386+ const SECS: f32 = 10.0;
387+ let n = samples(SECS);
388+ let mut noise = Noise(0x7A3C_91E5);
389+ let raw: Vec<f32> = (0..n).map(|_| noise.white()).collect();
390+ let wind = lowpass_loop(&lowpass_loop(&raw, 0.03), 0.03);
391+ let mut buf: Vec<f32> = wind
392+ .iter()
393+ .enumerate()
394+ .map(|(i, w)| {
395+ let t = i as f32 / RATE_F;
396+ let swell = 0.7 + 0.2 * sine(1.0 / SECS, t) + 0.1 * (TAU * 2.0 * t / SECS + 1.0).sin();
397+ w * swell
398+ })
399+ .collect();
400+ normalize(&mut buf, 0.3);
401+ add(&mut buf, 3.3, 2.0, |t| 0.25 * thud(t));
402+ add(&mut buf, 7.1, 2.0, |t| 0.18 * thud(t));
403+ buf
404+}
405+
406+fn thud(t: f32) -> f32 {
407+ sine(45.0, t) * (-t * 3.0).exp() * env(t, 2.0, 0.003, 0.5)
408+}
409+
410+/// Encodes mono f32 samples as a 16-bit PCM WAV file in memory.
411+fn encode_wav(samples: &[f32]) -> Arc<[u8]> {
412+ let data_len = (samples.len() * 2) as u32;
413+ let mut out = Vec::with_capacity(44 + data_len as usize);
414+ out.extend_from_slice(b"RIFF");
415+ out.extend_from_slice(&(36 + data_len).to_le_bytes());
416+ out.extend_from_slice(b"WAVE");
417+ out.extend_from_slice(b"fmt ");
418+ out.extend_from_slice(&16u32.to_le_bytes());
419+ out.extend_from_slice(&1u16.to_le_bytes()); // PCM
420+ out.extend_from_slice(&1u16.to_le_bytes()); // mono
421+ out.extend_from_slice(&RATE.to_le_bytes());
422+ out.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate
423+ out.extend_from_slice(&2u16.to_le_bytes()); // block align
424+ out.extend_from_slice(&16u16.to_le_bytes()); // bits per sample
425+ out.extend_from_slice(b"data");
426+ out.extend_from_slice(&data_len.to_le_bytes());
427+ for &s in samples {
428+ let v = (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
429+ out.extend_from_slice(&v.to_le_bytes());
430+ }
431+ Arc::from(out)
432+}
src/build.rsadded+322 -0
@@ -0,0 +1,322 @@
1+use bevy::prelude::*;
2+use bevy::window::PrimaryWindow;
3+
4+use crate::audio::SoundEvent;
5+use crate::map::{MapHover, WorldText};
6+use crate::model::{
7+ MIN_USABLE_CONDITION, Network, NodeClicked, NodeId, Notify, REPAIR_COST, TRACK_COST_PER_UNIT,
8+ Tool, TrackClicked, TrackSeg, Treasury,
9+};
10+
11+pub struct BuildPlugin;
12+
13+impl Plugin for BuildPlugin {
14+ fn build(&self, app: &mut App) {
15+ app.add_systems(Startup, spawn_cost_label).add_systems(
16+ Update,
17+ (handle_node_clicks, handle_track_clicks, build_preview).chain(),
18+ );
19+ }
20+}
21+
22+/// Logical pixels within which the cursor snaps to a node.
23+const SNAP_RADIUS: f32 = 24.0;
24+/// Cost label glyph size in world units (see `map::WorldText`).
25+const COST_LABEL_SIZE: f32 = 27.0;
26+/// Dash and gap lengths of the preview line, in world units.
27+const DASH_LEN: f32 = 12.0;
28+const GAP_LEN: f32 = 8.0;
29+
30+#[derive(Component)]
31+struct BuildCostLabel;
32+
33+fn spawn_cost_label(mut commands: Commands) {
34+ commands.spawn((
35+ BuildCostLabel,
36+ Text2d::new(""),
37+ WorldText {
38+ size: COST_LABEL_SIZE,
39+ },
40+ TextColor(Color::WHITE),
41+ Visibility::Hidden,
42+ Transform::from_xyz(0.0, 0.0, 20.0),
43+ ));
44+}
45+
46+/// Cost of a track of the given length, in dollars.
47+pub(crate) fn track_cost(length: f32) -> i64 {
48+ (length * TRACK_COST_PER_UNIT as f32) as i64
49+}
50+
51+/// Cost of laying the given track segments, in dollars.
52+pub(crate) fn segments_cost(segs: &[TrackSeg]) -> i64 {
53+ segs.iter().map(|s| track_cost(s.length)).sum()
54+}
55+
56+/// A node within this many world units of a straight track counts as lying on it.
57+const ON_TRACK_RADIUS: f32 = 30.0;
58+
59+/// The new segments that make a straight track from `from` to `to`.
60+///
61+/// The line is split at every node it passes within `ON_TRACK_RADIUS`, so the track
62+/// connects there instead of running past it. Segments that already exist are left
63+/// out. Empty when nothing new would be laid: the pair is already linked directly,
64+/// or a link on the way is cut and must be repaired first.
65+pub(crate) fn new_segments(net: &Network, from: NodeId, to: NodeId) -> Vec<TrackSeg> {
66+ if from == to || net.track_between(from, to).is_some() {
67+ return Vec::new();
68+ }
69+ let a = net.nodes[from.0].pos;
70+ let d = net.nodes[to.0].pos - a;
71+ let len2 = d.length_squared();
72+ let mut mids: Vec<(f32, NodeId)> = Vec::new();
73+ if len2 > 0.0 {
74+ for (i, node) in net.nodes.iter().enumerate() {
75+ let id = NodeId(i);
76+ if id == from || id == to {
77+ continue;
78+ }
79+ let t = (node.pos - a).dot(d) / len2;
80+ if t > 0.0 && t < 1.0 && node.pos.distance(a + d * t) <= ON_TRACK_RADIUS {
81+ mids.push((t, id));
82+ }
83+ }
84+ }
85+ mids.sort_by(|x, y| x.0.total_cmp(&y.0));
86+
87+ let mut chain = vec![from];
88+ chain.extend(mids.into_iter().map(|(_, id)| id));
89+ chain.push(to);
90+ let mut segs = Vec::new();
91+ for link in chain.windows(2) {
92+ let (x, y) = (link[0], link[1]);
93+ match net.track_between(x, y) {
94+ // A cut link on the way blocks the whole line.
95+ Some(i) if net.tracks[i].condition < MIN_USABLE_CONDITION => return Vec::new(),
96+ Some(_) => {}
97+ None => segs.push(TrackSeg {
98+ a: x,
99+ b: y,
100+ length: net.nodes[x.0].pos.distance(net.nodes[y.0].pos),
101+ condition: 1.0,
102+ }),
103+ }
104+ }
105+ segs
106+}
107+
108+/// "A-B" using the node names of a track.
109+fn track_name(net: &Network, seg: &TrackSeg) -> String {
110+ format!("{}-{}", net.nodes[seg.a.0].name, net.nodes[seg.b.0].name)
111+}
112+
113+fn handle_node_clicks(
114+ mut clicks: MessageReader<NodeClicked>,
115+ mut tool: ResMut<Tool>,
116+ mut net: ResMut<Network>,
117+ mut treasury: ResMut<Treasury>,
118+ mut notify: MessageWriter<Notify>,
119+ mut sounds: MessageWriter<SoundEvent>,
120+) {
121+ for &NodeClicked(n) in clicks.read() {
122+ let Tool::BuildTrack { from } = tool.as_mut() else {
123+ continue;
124+ };
125+ match *from {
126+ None => *from = Some(n),
127+ Some(f) if f == n => *from = None,
128+ Some(f) => {
129+ let segs = new_segments(&net, f, n);
130+ let cost = segments_cost(&segs);
131+ if segs.is_empty() {
132+ let msg = if net.track_between(f, n).is_some() {
133+ "Track already exists"
134+ } else {
135+ "No new track to lay"
136+ };
137+ notify.write(Notify(msg.into()));
138+ } else if treasury.0 >= cost {
139+ let name = format!("{}-{}", net.nodes[f.0].name, net.nodes[n.0].name);
140+ net.tracks.extend(segs);
141+ treasury.0 -= cost;
142+ notify.write(Notify(format!("Laid track {name} for ${cost}")));
143+ sounds.write(SoundEvent::TrackLaid);
144+ } else {
145+ notify.write(Notify(format!("Not enough funds (${cost} needed)")));
146+ }
147+ // Keep chaining from the node just clicked.
148+ *from = Some(n);
149+ }
150+ }
151+ }
152+}
153+
154+fn handle_track_clicks(
155+ mut clicks: MessageReader<TrackClicked>,
156+ tool: Res<Tool>,
157+ mut net: ResMut<Network>,
158+ mut treasury: ResMut<Treasury>,
159+ mut notify: MessageWriter<Notify>,
160+ mut sounds: MessageWriter<SoundEvent>,
161+) {
162+ for &TrackClicked(i) in clicks.read() {
163+ let Some(seg) = net.tracks.get(i).copied() else {
164+ continue;
165+ };
166+ match tool.as_ref() {
167+ Tool::Repair => repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds),
168+ // Inspect is the default mode: a click on a damaged track repairs it, an intact one does nothing.
169+ Tool::Inspect if seg.condition < 1.0 => {
170+ repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds)
171+ }
172+ _ => {}
173+ }
174+ }
175+}
176+
177+/// Repairs track `i` to full condition if the treasury can pay for it, otherwise says why not.
178+fn repair_track(
179+ i: usize,
180+ net: &mut Network,
181+ treasury: &mut Treasury,
182+ notify: &mut MessageWriter<Notify>,
183+ sounds: &mut MessageWriter<SoundEvent>,
184+) {
185+ let seg = net.tracks[i];
186+ let name = track_name(net, &seg);
187+ if seg.condition >= 1.0 {
188+ notify.write(Notify("Track is intact".into()));
189+ } else if treasury.0 >= REPAIR_COST {
190+ net.tracks[i].condition = 1.0;
191+ treasury.0 -= REPAIR_COST;
192+ notify.write(Notify(format!("Repaired {name} (-${REPAIR_COST})")));
193+ sounds.write(SoundEvent::TrackLaid);
194+ } else {
195+ notify.write(Notify("Not enough funds".into()));
196+ }
197+}
198+
199+/// Draws the dashed track preview and the cost label while laying track.
200+#[allow(
201+ clippy::too_many_arguments,
202+ reason = "Bevy system: one parameter per resource and query"
203+)]
204+fn build_preview(
205+ tool: Res<Tool>,
206+ net: Res<Network>,
207+ treasury: Res<Treasury>,
208+ hover: Res<MapHover>,
209+ windows: Query<&Window, With<PrimaryWindow>>,
210+ cameras: Query<(&Camera, &GlobalTransform), With<Camera2d>>,
211+ mut gizmos: Gizmos,
212+ mut labels: Query<
213+ (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility),
214+ With<BuildCostLabel>,
215+ >,
216+) {
217+ let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else {
218+ return;
219+ };
220+
221+ let Tool::BuildTrack { from: Some(f) } = tool.as_ref() else {
222+ *visibility = Visibility::Hidden;
223+ return;
224+ };
225+ let f = *f;
226+
227+ let cursor_world = windows
228+ .single()
229+ .ok()
230+ .and_then(|w| w.cursor_position())
231+ .and_then(|cursor| {
232+ let (camera, gt) = cameras.single().ok()?;
233+ camera.viewport_to_world_2d(gt, cursor).ok()
234+ });
235+ let (Some(cursor_world), Some(from_node)) = (cursor_world, net.nodes.get(f.0)) else {
236+ *visibility = Visibility::Hidden;
237+ return;
238+ };
239+ let from_pos = from_node.pos;
240+
241+ let snapped = net.node_at(cursor_world, SNAP_RADIUS * hover.world_per_px);
242+ let target = match snapped {
243+ Some(n) => net.nodes[n.0].pos,
244+ None => cursor_world,
245+ };
246+
247+ let on_origin = snapped == Some(f);
248+ // Snapped to another node: the exact new segments, split at any node the line passes.
249+ let segs = match snapped {
250+ Some(n) if !on_origin => Some(new_segments(&net, f, n)),
251+ _ => None,
252+ };
253+
254+ let (label, label_color) = if on_origin {
255+ // Hovering the origin node: clicking it again cancels.
256+ (
257+ "Click again to cancel".to_string(),
258+ Color::srgb(0.35, 0.35, 0.35),
259+ )
260+ } else if matches!(&segs, Some(s) if s.is_empty()) {
261+ (
262+ "Track already exists".to_string(),
263+ Color::srgb(0.8, 0.1, 0.1),
264+ )
265+ } else {
266+ let cost = match &segs {
267+ Some(segs) => segments_cost(segs),
268+ None => track_cost(from_pos.distance(target)),
269+ };
270+ let color = if treasury.0 >= cost {
271+ Color::srgb(0.1, 0.5, 0.1)
272+ } else {
273+ Color::srgb(0.8, 0.1, 0.1)
274+ };
275+ // Off-node cursor: the cost is only an estimate from the cursor distance.
276+ let prefix = if snapped.is_some() { "" } else { "~" };
277+ (format!("{prefix}${cost}"), color)
278+ };
279+
280+ // Draw each new segment; otherwise the straight dashed preview, unless on the origin.
281+ match &segs {
282+ Some(segs) if !segs.is_empty() => {
283+ for s in segs {
284+ draw_dashed(
285+ &mut gizmos,
286+ net.nodes[s.a.0].pos,
287+ net.nodes[s.b.0].pos,
288+ Color::srgba(0.2, 0.15, 0.1, 0.8),
289+ );
290+ }
291+ }
292+ _ if !on_origin => draw_dashed(
293+ &mut gizmos,
294+ from_pos,
295+ target,
296+ Color::srgba(0.2, 0.15, 0.1, 0.8),
297+ ),
298+ _ => {}
299+ }
300+
301+ if text.0 != label {
302+ text.0 = label;
303+ }
304+ *color = TextColor(label_color);
305+ transform.translation = Vec3::new(target.x + 14.0, target.y + 14.0, 20.0);
306+ *visibility = Visibility::Visible;
307+}
308+
309+fn draw_dashed(gizmos: &mut Gizmos<'_, '_>, from: Vec2, to: Vec2, color: Color) {
310+ let delta = to - from;
311+ let len = delta.length();
312+ if len <= 0.0 {
313+ return;
314+ }
315+ let dir = delta / len;
316+ let mut s = 0.0;
317+ while s < len {
318+ let e = (s + DASH_LEN).min(len);
319+ gizmos.line_2d(from + dir * s, from + dir * e, color);
320+ s += DASH_LEN + GAP_LEN;
321+ }
322+}
src/demo.rsadded+583 -0
@@ -0,0 +1,583 @@
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+
9+use std::collections::VecDeque;
10+
11+use bevy::app::AppExit;
12+use bevy::ecs::change_detection::Mut;
13+use bevy::prelude::*;
14+use bevy::time::{Real, Time};
15+use bevy::ui::Display;
16+
17+use crate::audio::SoundEvent;
18+use crate::build::track_cost;
19+use crate::front::{FrontRuntime, air_raid, reset_game};
20+use crate::hud::BOTTOM_H;
21+use crate::menu::{Menu, MenuScreen};
22+use 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.
28+const CAPTION_MIN_SECS: f64 = 4.0;
29+const CAPTION_SECS_PER_CHAR: f64 = 0.05;
30+/// Gap between the subtitle box and the bottom strip.
31+const SUBTITLE_GAP: f32 = 12.0;
32+/// Side margin of the subtitle box, from the window edge.
33+const 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.
36+const RAID_WAIT_SECS: f64 = 8.0;
37+/// Real seconds allowed for a money wait or a budget wait before moving on.
38+const WAIT_TIMEOUT_SECS: f64 = 150.0;
39+/// One weekly budget, in game hours.
40+const WEEK_HOURS: u32 = 24 * 7;
41+
42+/// Adds the narrated demo bot and its caption box.
43+pub struct DemoPlugin {
44+ /// End the run when the script ends (used with `--record`).
45+ pub exit_when_done: bool,
46+}
47+
48+impl 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)]
65+struct 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+
73+impl Captions {
74+ fn idle(&self) -> bool {
75+ self.queue.is_empty() && self.current.is_none()
76+ }
77+}
78+
79+fn hold_secs(text: &str) -> f64 {
80+ (text.chars().count() as f64 * CAPTION_SECS_PER_CHAR).max(CAPTION_MIN_SECS)
81+}
82+
83+fn 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)]
99+struct SubtitleRoot;
100+
101+#[derive(Component)]
102+struct SubtitleText;
103+
104+/// The caption box sits above the bottom strip, centred, and above the menus.
105+fn 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+
139+fn 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+
163+type Act = Box<dyn Fn(&mut World) + Send + Sync>;
164+type Check = Box<dyn Fn(&World) -> bool + Send + Sync>;
165+
166+/// One scripted step. The script runs them in order.
167+enum 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+
178+enum 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)]
186+struct Script {
187+ steps: VecDeque<Step>,
188+ wait: Option<Wait>,
189+ exit_when_done: bool,
190+ done: bool,
191+}
192+
193+fn act(f: impl Fn(&mut World) + Send + Sync + 'static) -> Step {
194+ Step::Act(Box::new(f))
195+}
196+
197+fn until(f: impl Fn(&World) -> bool + Send + Sync + 'static, timeout: f64) -> Step {
198+ Step::Until(Box::new(f), timeout)
199+}
200+
201+fn say(text: impl Into<String>) -> Step {
202+ Step::Say(text.into())
203+}
204+
205+fn pause(secs: f64) -> Step {
206+ Step::Pause(secs)
207+}
208+
209+/// Runs the script. Exclusive, so steps can change any resource and write messages.
210+fn 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+
252+fn 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+
260+fn money(w: &World) -> i64 {
261+ w.resource::<Treasury>().0
262+}
263+
264+fn set_tool(w: &mut World, tool: Tool) {
265+ *w.resource_mut::<Tool>() = tool;
266+}
267+
268+fn 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.
273+fn 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.
282+fn new_operation(w: &mut World) {
283+ set_screen(w, None);
284+ reset_game(w);
285+}
286+
287+fn 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.
293+fn 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.
299+fn 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.
308+fn 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.
348+fn 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.
356+fn 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.
369+fn 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.
387+fn 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.
396+fn 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+}
src/economy.rsadded+261 -0
@@ -0,0 +1,261 @@
1+//! Game clock, home-front production and consumption, and the weekly budget.
2+
3+use std::collections::HashMap;
4+
5+use bevy::input::ButtonInput;
6+use bevy::prelude::*;
7+use bevy::time::{Real, Time};
8+
9+use crate::menu::Menu;
10+use crate::model::{
11+ Good, HourTick, Network, NodeKind, Notify, Outcome, SECS_PER_HOUR, SimClock, Train, Treasury,
12+};
13+use crate::seasons::SeasonState;
14+
15+/// Stock cap per good per node.
16+const STOCK_CAP: f32 = 200.0;
17+/// Food eaten per hour by Capital and City.
18+const FOOD_PER_HOUR: f32 = 0.5;
19+/// Hunger relief per hour when fed, and gain per hour when starving.
20+const HUNGER_RECOVER: f32 = 0.02;
21+const HUNGER_GAIN: f32 = 0.03;
22+/// Hunger level at which a city's production warning fires.
23+const HUNGER_ALARM: f32 = 0.5;
24+/// Minimum game hours between two bread-line warnings for the same city.
25+const ALARM_COOLDOWN_HOURS: u32 = 24;
26+/// Wounded treated per hour per hospital node.
27+const TREAT_PER_HOUR: f32 = 1.0;
28+/// Troops returned per wounded treated.
29+const TROOPS_PER_TREATED: f32 = 0.5;
30+/// Weekly budget period in game hours.
31+const WEEK_HOURS: u32 = 24 * 7;
32+const BASE_INCOME: i64 = 2000;
33+const FRONT_LINE_BONUS: i64 = 500;
34+
35+pub struct EconomyPlugin;
36+
37+impl Plugin for EconomyPlugin {
38+ fn build(&self, app: &mut App) {
39+ app.add_systems(Update, (clock_controls, advance_clock).chain())
40+ .add_systems(Update, economy_tick.after(advance_clock));
41+ }
42+}
43+
44+/// Space toggles pause (restoring the previous speed on unpause).
45+/// Digit1/2/3 select speed 1, 2 or 4.
46+fn clock_controls(
47+ keys: Res<ButtonInput<KeyCode>>,
48+ menu: Res<Menu>,
49+ mut clock: ResMut<SimClock>,
50+ mut prev_speed: Local<u32>,
51+) {
52+ if menu.is_open() {
53+ return;
54+ }
55+ if keys.just_pressed(KeyCode::Space) {
56+ if clock.speed == 0 {
57+ clock.speed = if *prev_speed == 0 { 1 } else { *prev_speed };
58+ } else {
59+ *prev_speed = clock.speed;
60+ clock.speed = 0;
61+ }
62+ }
63+ let digits = [
64+ (KeyCode::Digit1, 1),
65+ (KeyCode::Digit2, 2),
66+ (KeyCode::Digit3, 4),
67+ ];
68+ for (key, speed) in digits {
69+ if keys.just_pressed(key) {
70+ clock.speed = speed;
71+ }
72+ }
73+}
74+
75+/// Advances game time by real time times speed, emitting one `HourTick` per whole hour.
76+pub fn advance_clock(
77+ time: Res<Time<Real>>,
78+ outcome: Res<Outcome>,
79+ mut clock: ResMut<SimClock>,
80+ mut ticks: MessageWriter<HourTick>,
81+) {
82+ if *outcome != Outcome::Ongoing {
83+ return;
84+ }
85+ clock.acc += time.delta_secs() * clock.speed as f32;
86+ while clock.acc >= SECS_PER_HOUR {
87+ clock.acc -= SECS_PER_HOUR;
88+ clock.hour += 1;
89+ ticks.write(HourTick);
90+ }
91+}
92+
93+/// Runs the hourly production, consumption and budget for every `HourTick` read this frame.
94+/// Ticks are ordered after `advance_clock`, so the tick hours are the last `n` hours of the clock.
95+#[allow(clippy::too_many_arguments, reason = "bevy system parameters")]
96+pub(crate) fn economy_tick(
97+ mut ticks: MessageReader<HourTick>,
98+ clock: Res<SimClock>,
99+ season: Res<SeasonState>,
100+ mut net: ResMut<Network>,
101+ mut treasury: ResMut<Treasury>,
102+ trains: Query<&Train>,
103+ mut notes: MessageWriter<Notify>,
104+ mut alarm_hours: Local<HashMap<usize, u32>>,
105+) {
106+ let n = ticks.read().count() as u32;
107+ if n == 0 {
108+ return;
109+ }
110+ let first_hour = (clock.hour + 1).saturating_sub(n);
111+ for k in 0..n {
112+ let hour = first_hour + k;
113+ for text in run_hour(&mut net.nodes, hour, season.season.food_mult(), &mut alarm_hours) {
114+ notes.write(Notify(text));
115+ }
116+ if is_budget_hour(hour) {
117+ let front_lines = net
118+ .nodes
119+ .iter()
120+ .filter(|node| node.front.is_some_and(|f| f.line > 0.0))
121+ .count();
122+ let upkeep: i64 = trains.iter().map(|t| t.upkeep_per_week()).sum();
123+ let income = budget_income(front_lines);
124+ treasury.0 += income - upkeep;
125+ notes.write(Notify(format!(
126+ "War Ministry allocation: +${income}, upkeep -${upkeep}"
127+ )));
128+ }
129+ }
130+}
131+
132+/// One hour of home-front simulation. Returns the news lines to publish.
133+fn run_hour(
134+ nodes: &mut [crate::model::Node],
135+ hour: u32,
136+ food_mult: f32,
137+ alarm_hours: &mut HashMap<usize, u32>,
138+) -> Vec<String> {
139+ let mut news = Vec::new();
140+
141+ let (hunger_sum, hunger_count) = nodes
142+ .iter()
143+ .filter(|n| !n.captured && matches!(n.kind, NodeKind::Capital | NodeKind::City))
144+ .fold((0.0_f32, 0_usize), |(s, c), n| (s + n.hunger, c + 1));
145+ let avg_hunger = if hunger_count > 0 {
146+ hunger_sum / hunger_count as f32
147+ } else {
148+ 0.0
149+ };
150+ let p = productivity(avg_hunger);
151+
152+ for (i, node) in nodes.iter_mut().enumerate() {
153+ // Captured sites are gone; evacuating sites produce nothing until the evacuation ends.
154+ if node.captured {
155+ continue;
156+ }
157+ let before = node.hunger;
158+ let output = if node.evac.is_some() { 0.0 } else { node.output };
159+ match node.kind {
160+ NodeKind::Factory => {
161+ add_capped(&mut node.stock[Good::Ammo.idx()], 2.0 * p * output);
162+ }
163+ NodeKind::Farm => {
164+ add_capped(&mut node.stock[Good::Food.idx()], 3.0 * output);
165+ }
166+ NodeKind::Capital => {
167+ add_capped(&mut node.stock[Good::Troops.idx()], 0.8 * p * output);
168+ }
169+ NodeKind::City => {
170+ add_capped(&mut node.stock[Good::Troops.idx()], city_troops(before) * output);
171+ }
172+ NodeKind::Depot | NodeKind::Front => {}
173+ }
174+
175+ if matches!(node.kind, NodeKind::Capital | NodeKind::City) {
176+ let (hunger, eaten) = feed(before, node.stock[Good::Food.idx()], FOOD_PER_HOUR * food_mult);
177+ node.stock[Good::Food.idx()] = (node.stock[Good::Food.idx()] - eaten).max(0.0);
178+ node.hunger = hunger;
179+
180+ let wounded = node.stock[Good::Wounded.idx()];
181+ let treated = wounded.min(TREAT_PER_HOUR);
182+ node.stock[Good::Wounded.idx()] = (wounded - treated).max(0.0);
183+ add_capped(
184+ &mut node.stock[Good::Troops.idx()],
185+ treated * TROOPS_PER_TREATED,
186+ );
187+
188+ if node.kind == NodeKind::City
189+ && before < HUNGER_ALARM
190+ && node.hunger >= HUNGER_ALARM
191+ && alarm_due(alarm_hours, i, hour)
192+ {
193+ news.push(format!("Bread lines in {}: production falling", node.name));
194+ }
195+ }
196+ }
197+ news
198+}
199+
200+/// Returns true and records `hour` when the city's warning is off cooldown.
201+/// A last warning later than `hour` came from before a restart, so it does not count.
202+fn alarm_due(alarm_hours: &mut HashMap<usize, u32>, node: usize, hour: u32) -> bool {
203+ match alarm_hours.get(&node) {
204+ Some(&last) if hour >= last && hour - last < ALARM_COOLDOWN_HOURS => false,
205+ _ => {
206+ alarm_hours.insert(node, hour);
207+ true
208+ }
209+ }
210+}
211+
212+/// Output multiplier from average city hunger: 1.0 when fed, 0.4 at full hunger.
213+pub fn productivity(avg_hunger: f32) -> f32 {
214+ 1.0 - 0.6 * avg_hunger
215+}
216+
217+/// Troops a city adds per hour, scaled by its own hunger.
218+pub fn city_troops(hunger: f32) -> f32 {
219+ 0.3 * (1.0 - hunger)
220+}
221+
222+/// One hour of eating a `ration`. Returns (new hunger, food consumed).
223+pub fn feed(hunger: f32, food: f32, ration: f32) -> (f32, f32) {
224+ if food >= ration {
225+ ((hunger - HUNGER_RECOVER).max(0.0), ration)
226+ } else {
227+ ((hunger + HUNGER_GAIN).min(1.0), 0.0)
228+ }
229+}
230+
231+/// Adds `amount` to a stock, clamped to the per-node cap.
232+pub fn add_capped(stock: &mut f32, amount: f32) {
233+ *stock = (*stock + amount).min(STOCK_CAP);
234+}
235+
236+pub fn is_budget_hour(hour: u32) -> bool {
237+ hour > 0 && hour.is_multiple_of(WEEK_HOURS)
238+}
239+
240+pub fn budget_income(front_lines_advancing: usize) -> i64 {
241+ BASE_INCOME + FRONT_LINE_BONUS * front_lines_advancing as i64
242+}
243+
244+#[cfg(test)]
245+mod tests {
246+ use super::*;
247+
248+ #[test]
249+ fn feed_eats_when_fed_and_starves_without_food() {
250+ // Enough food: eat one hour's ration and recover hunger.
251+ let (h, eaten) = feed(0.5, 1.0, FOOD_PER_HOUR);
252+ assert!((h - 0.48).abs() < 1e-6);
253+ assert_eq!(eaten, FOOD_PER_HOUR);
254+ // No food: eat nothing and hunger rises, capped at 1.
255+ let (h, eaten) = feed(0.5, 0.49, FOOD_PER_HOUR);
256+ assert!((h - 0.53).abs() < 1e-6);
257+ assert_eq!(eaten, 0.0);
258+ let (h, _) = feed(0.99, 0.0, FOOD_PER_HOUR);
259+ assert_eq!(h, 1.0);
260+ }
261+}
src/evac.rsadded+377 -0
@@ -0,0 +1,377 @@
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+
6+use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, TAU};
7+
8+use bevy::prelude::*;
9+use bevy::time::{Real, Time};
10+
11+use crate::front::front_hour_system;
12+use crate::map::WorldText;
13+use 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`.
18+const THREAT_LINE: f32 = -0.4;
19+/// The threat lifts once the threatening front recovers above this line.
20+const SAFE_LINE: f32 = -0.2;
21+const EVAC_RANGE: f32 = 350.0;
22+const EVAC_HOURS: u32 = 120;
23+const EVAC_CRATES: u32 = 6;
24+/// An evacuation destination lies at least this far west of the building.
25+const REAR_GAP: f32 = 150.0;
26+/// Distance from the destination to the rebuilt site, and the clearance it needs.
27+const REBUILD_OFFSET: f32 = 45.0;
28+const REBUILD_CLEAR: f32 = 35.0;
29+
30+const CRATE_FILL: Color = Color::srgb(0.55, 0.36, 0.16);
31+const CRATE_EDGE: Color = Color::srgb(0.22, 0.15, 0.09);
32+const ALARM: Color = Color::srgb(0.78, 0.12, 0.10);
33+const AMBER: Color = Color::srgb(1.0, 0.70, 0.10);
34+const CAPTION_SIZE: f32 = 15.0;
35+
36+pub struct EvacPlugin;
37+
38+impl 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`.
46+pub 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.
71+pub 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`.
76+fn 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.
84+fn 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.
113+pub(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+
203+fn 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)]
221+struct EvacCaption(usize);
222+
223+/// Keeps one caption per site that still needs a destination.
224+fn 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.
258+fn crate_at(pos: Vec2, k: u32) -> Vec2 {
259+ pos + Vec2::new(-36.0, 14.0 + k as f32 * 9.0)
260+}
261+
262+fn 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`.
274+fn 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.
283+fn 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.
304+fn 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)]
354+mod 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+}
src/front.rsadded+690 -0
@@ -0,0 +1,690 @@
1+//! Front sectors: supply and line simulation, the front-line drawing,
2+//! air raids, and the victory/defeat overlay with restart.
3+
4+use std::collections::HashMap;
5+
6+use bevy::input::ButtonInput;
7+use bevy::prelude::*;
8+use bevy::time::{Real, Time};
9+
10+use crate::audio::SoundEvent;
11+use crate::economy::advance_clock;
12+use crate::model::{
13+ FrontState, Good, HourTick, MIN_USABLE_CONDITION, Network, Notify, Outcome, Selected, SimClock,
14+ Tool, Train, Treasury,
15+};
16+use crate::seasons::SeasonState;
17+use crate::trains::TrainCounter;
18+
19+/// Ammo, food and troops one sector needs per game hour.
20+pub const AMMO_NEED: f32 = 1.0;
21+pub const FOOD_NEED: f32 = 0.8;
22+pub const TROOPS_NEED: f32 = 0.15;
23+
24+/// Hourly need of a front sector for `g`. Food scales with the season's food multiplier.
25+pub fn hourly_need(g: Good, food_mult: f32) -> f32 {
26+ match g {
27+ Good::Ammo => AMMO_NEED,
28+ Good::Food => FOOD_NEED * food_mult,
29+ Good::Troops => TROOPS_NEED,
30+ Good::Wounded => 0.0,
31+ }
32+}
33+/// Fraction of the gap to the hour's supply ratio closed each hour.
34+const SUPPLY_RATE: f32 = 0.1;
35+/// Line drift per hour per unit of supply above or below the neutral point.
36+const LINE_RATE: f32 = 0.004;
37+pub const NEUTRAL_SUPPLY: f32 = 0.5;
38+/// Wounded produced per hour: base plus shortage scaled.
39+const WOUNDED_BASE: f32 = 0.2;
40+const WOUNDED_SHORTAGE: f32 = 0.5;
41+const WOUNDED_CAP: f32 = 200.0;
42+const LOW_SUPPLY: f32 = 0.35;
43+const NOTICE_COOLDOWN_HOURS: u32 = 24;
44+const ADVANCE_LINE: f32 = 0.5;
45+const RETREAT_LINE: f32 = -0.5;
46+
47+/// Air raids are checked every this many game hours.
48+const RAID_EVERY_HOURS: u32 = 24;
49+const RAID_CHANCE: f64 = 0.35;
50+/// Condition lost by a damaged track in one raid.
51+const RAID_DAMAGE_MIN: f32 = 0.25;
52+const RAID_DAMAGE_MAX: f32 = 0.5;
53+/// Track condition regained per game hour without repair crews.
54+const SELF_REPAIR_PER_HOUR: f32 = 0.01;
55+/// Raids only hit track with an endpoint east of this x.
56+const FRONT_ZONE_X: f32 = 100.0;
57+/// Raid animation length in real seconds. Shown even while paused.
58+const RAID_FX_SECS: f32 = 2.5;
59+/// The bomber crosses from this far off the track's midpoint to the other side.
60+const RAID_PLANE_REACH: Vec2 = Vec2::new(480.0, 140.0);
61+/// Bomb bursts: (age in seconds, fraction along the hit track).
62+const RAID_BURSTS: [(f32, f32); 4] = [(0.6, 0.18), (0.85, 0.42), (1.1, 0.62), (1.35, 0.84)];
63+const RAID_BURST_SECS: f32 = 1.0;
64+/// Track flashes from this age, then fades out.
65+const RAID_FLASH_START: f32 = 0.5;
66+
67+/// Front line geometry.
68+const LINE_OFFSET_X: f32 = 70.0;
69+const LINE_SWING_X: f32 = 120.0;
70+const LINE_EXTENT_Y: f32 = 360.0;
71+const JAG_STEP: f32 = 12.0;
72+const JAG_AMPLITUDE: f32 = 5.0;
73+const TOOTH_SPACING: f32 = 15.0;
74+const TOOTH_LEN: f32 = 8.0;
75+const HATCH_STEP: f32 = 14.0;
76+const HATCH_LEN: f32 = 36.0;
77+const BAR_W: f32 = 90.0;
78+const BAR_H: f32 = 8.0;
79+/// Supply bar sits above the node; the stock bars and the name label sit below it.
80+const BAR_DY: f32 = 16.0;
81+
82+/// Next state of one front sector after one game hour.
83+///
84+/// `stock` is `[ammo, food, troops, wounded]` of the sector node. Ammo, food
85+/// and troops are consumed up to what is available; wounded are produced.
86+fn step_sector(stock: [f32; 4], front: FrontState, food_mult: f32) -> ([f32; 4], FrontState) {
87+ let mut stock = stock;
88+ let mut ratio_sum = 0.0;
89+ for g in [Good::Ammo, Good::Food, Good::Troops] {
90+ let idx = g.idx();
91+ let need = hourly_need(g, food_mult);
92+ let taken = need.min(stock[idx].max(0.0));
93+ stock[idx] -= taken;
94+ ratio_sum += taken / need;
95+ }
96+ let ratio = ratio_sum / 3.0;
97+ let supply = front.supply + (ratio - front.supply) * SUPPLY_RATE;
98+ let line = (front.line + (supply - NEUTRAL_SUPPLY) * LINE_RATE).clamp(-1.0, 1.0);
99+ let wounded = stock[Good::Wounded.idx()] + WOUNDED_BASE + (1.0 - supply) * WOUNDED_SHORTAGE;
100+ stock[Good::Wounded.idx()] = wounded.min(WOUNDED_CAP);
101+ (stock, FrontState { line, supply })
102+}
103+
104+/// Track condition after one game hour of self-repair, capped at fully intact.
105+pub fn repair_step(condition: f32) -> f32 {
106+ (condition + SELF_REPAIR_PER_HOUR).min(1.0)
107+}
108+
109+/// Outcome implied by the current front lines, if any.
110+fn judge(net: &Network) -> Option<Outcome> {
111+ let lines: Vec<f32> = net
112+ .nodes
113+ .iter()
114+ .filter_map(|n| n.front.map(|f| f.line))
115+ .collect();
116+ if lines.iter().any(|&l| l <= -1.0) {
117+ Some(Outcome::Defeat)
118+ } else if !lines.is_empty() && lines.iter().all(|&l| l >= 1.0) {
119+ Some(Outcome::Victory)
120+ } else {
121+ None
122+ }
123+}
124+
125+/// A low-supply notice may fire at most once per cooldown window per sector.
126+fn notice_due(last: Option<u32>, now: u32) -> bool {
127+ last.is_none_or(|h| now.saturating_sub(h) >= NOTICE_COOLDOWN_HOURS)
128+}
129+
130+/// Advances every front sector one hour and returns the news lines.
131+fn step_fronts(net: &mut Network, runtime: &mut FrontRuntime, now: u32, food_mult: f32) -> Vec<String> {
132+ let mut news = Vec::new();
133+ for (i, node) in net.nodes.iter_mut().enumerate() {
134+ let Some(old) = node.front else { continue };
135+ let (stock, new) = step_sector(node.stock, old, food_mult);
136+ node.stock = stock;
137+ node.front = Some(new);
138+ if new.supply < LOW_SUPPLY && notice_due(runtime.low_notice.get(&i).copied(), now) {
139+ runtime.low_notice.insert(i, now);
140+ news.push(format!("{} is running out of supplies!", node.name));
141+ }
142+ if old.line < ADVANCE_LINE && new.line >= ADVANCE_LINE {
143+ news.push(format!("{} advances", node.name));
144+ }
145+ if old.line > RETREAT_LINE && new.line <= RETREAT_LINE {
146+ news.push(format!("{} is falling back", node.name));
147+ }
148+ }
149+ news
150+}
151+
152+/// Track indices eligible for a raid: usable and touching the front zone.
153+fn raid_candidates(net: &Network) -> Vec<usize> {
154+ net.tracks
155+ .iter()
156+ .enumerate()
157+ .filter(|(_, t)| {
158+ t.condition >= MIN_USABLE_CONDITION
159+ && (net.nodes[t.a.0].pos.x > FRONT_ZONE_X || net.nodes[t.b.0].pos.x > FRONT_ZONE_X)
160+ })
161+ .map(|(i, _)| i)
162+ .collect()
163+}
164+
165+/// Damages one random eligible track. Returns its index and the news line.
166+pub(crate) fn air_raid(net: &mut Network, runtime: &mut FrontRuntime) -> Option<(usize, String)> {
167+ let candidates = raid_candidates(net);
168+ if candidates.is_empty() {
169+ return None;
170+ }
171+ let i = candidates[rand::random_range(0..candidates.len())];
172+ let track = net.tracks[i];
173+ let a = &net.nodes[track.a.0];
174+ let b = &net.nodes[track.b.0];
175+ let text = format!("Air raid! Line {}-{} damaged", a.name, b.name);
176+ let (pa, pb) = (a.pos, b.pos);
177+ let loss: f32 = rand::random_range(RAID_DAMAGE_MIN..RAID_DAMAGE_MAX);
178+ net.tracks[i].condition = (track.condition - loss).max(0.0);
179+ runtime.raids.push(RaidFx {
180+ a: pa,
181+ b: pb,
182+ age: 0.0,
183+ });
184+ Some((i, text))
185+}
186+
187+/// A raid effect still on screen, over the track it hit.
188+pub(crate) struct RaidFx {
189+ /// Endpoints of the hit track.
190+ a: Vec2,
191+ b: Vec2,
192+ /// Real seconds since the raid.
193+ age: f32,
194+}
195+
196+/// Per-session state owned by the front. Reset on restart.
197+#[derive(Resource, Default)]
198+pub(crate) struct FrontRuntime {
199+ /// Game hours processed since start or restart.
200+ hours: u32,
201+ /// Node index -> hour of the last low-supply notice.
202+ low_notice: HashMap<usize, u32>,
203+ pub(crate) raids: Vec<RaidFx>,
204+}
205+
206+#[derive(Component)]
207+struct OutcomeOverlay;
208+
209+pub struct FrontPlugin;
210+
211+impl Plugin for FrontPlugin {
212+ fn build(&self, app: &mut App) {
213+ app.init_resource::<FrontRuntime>().add_systems(
214+ Update,
215+ (
216+ // Reads the hour ticks written by the clock in the same frame.
217+ front_hour_system.after(advance_clock),
218+ restart_system,
219+ outcome_overlay,
220+ draw_front,
221+ )
222+ .chain(),
223+ );
224+ }
225+}
226+
227+#[allow(clippy::too_many_arguments, reason = "bevy system parameters")]
228+pub(crate) fn front_hour_system(
229+ mut ticks: MessageReader<HourTick>,
230+ mut net: ResMut<Network>,
231+ mut outcome: ResMut<Outcome>,
232+ mut clock: ResMut<SimClock>,
233+ season: Res<SeasonState>,
234+ mut runtime: ResMut<FrontRuntime>,
235+ mut notify: MessageWriter<Notify>,
236+ mut sounds: MessageWriter<SoundEvent>,
237+) {
238+ for _ in ticks.read() {
239+ runtime.hours += 1;
240+ if *outcome != Outcome::Ongoing {
241+ continue;
242+ }
243+ for news in step_fronts(&mut net, &mut runtime, clock.hour, season.season.food_mult()) {
244+ notify.write(Notify(news));
245+ }
246+ // Track touching a captured site stays cut.
247+ let cut: Vec<bool> = net.tracks.iter().map(|t| net.is_cut(t)).collect();
248+ for (track, cut) in net.tracks.iter_mut().zip(cut) {
249+ if !cut {
250+ track.condition = repair_step(track.condition);
251+ }
252+ }
253+ if let Some(result) = judge(&net) {
254+ *outcome = result;
255+ clock.speed = 0;
256+ let text = match result {
257+ Outcome::Victory => "OPERATION SUCCESSFUL",
258+ _ => "THE FRONT HAS COLLAPSED",
259+ };
260+ sounds.write(match result {
261+ Outcome::Victory => SoundEvent::Victory,
262+ _ => SoundEvent::Defeat,
263+ });
264+ notify.write(Notify(text.to_string()));
265+ continue;
266+ }
267+ // Fog keeps the bombers grounded; summer skies raise the odds.
268+ if runtime.hours.is_multiple_of(RAID_EVERY_HOURS)
269+ && !season.fog
270+ && rand::random_bool(RAID_CHANCE * f64::from(season.season.raid_mult()))
271+ && let Some((_, text)) = air_raid(&mut net, &mut runtime)
272+ {
273+ sounds.write(SoundEvent::Raid);
274+ notify.write(Notify(text));
275+ }
276+ }
277+}
278+
279+/// Enter restarts a finished game.
280+fn restart_system(world: &mut World) {
281+ let pressed = {
282+ let keys = world.resource::<ButtonInput<KeyCode>>();
283+ keys.just_pressed(KeyCode::Enter) || keys.just_pressed(KeyCode::NumpadEnter)
284+ };
285+ if !pressed || *world.resource::<Outcome>() == Outcome::Ongoing {
286+ return;
287+ }
288+ reset_game(world);
289+}
290+
291+/// Starts a fresh operation: default map, treasury, clock, trains and front state.
292+/// Used by Enter after a finished game and by the menu's New Operation.
293+pub fn reset_game(world: &mut World) {
294+ *world.resource_mut::<Network>() = Network::default();
295+ *world.resource_mut::<Treasury>() = Treasury::default();
296+ *world.resource_mut::<SimClock>() = SimClock::default();
297+ *world.resource_mut::<Outcome>() = Outcome::Ongoing;
298+ *world.resource_mut::<Tool>() = Tool::Inspect;
299+ *world.resource_mut::<Selected>() = Selected(None);
300+ *world.resource_mut::<FrontRuntime>() = FrontRuntime::default();
301+ *world.resource_mut::<TrainCounter>() = TrainCounter::default();
302+ *world.resource_mut::<SeasonState>() = SeasonState::default();
303+ let trains: Vec<Entity> = world
304+ .query_filtered::<Entity, With<Train>>()
305+ .iter(world)
306+ .collect();
307+ for e in trains {
308+ world.entity_mut(e).despawn();
309+ }
310+ world.spawn(crate::trains::starting_train());
311+}
312+
313+/// Keeps the centred result panel in step with `Outcome`.
314+fn outcome_overlay(
315+ mut commands: Commands,
316+ outcome: Res<Outcome>,
317+ clock: Res<SimClock>,
318+ existing: Query<Entity, With<OutcomeOverlay>>,
319+) {
320+ let (title, accent) = match *outcome {
321+ Outcome::Ongoing => {
322+ for e in &existing {
323+ commands.entity(e).despawn();
324+ }
325+ return;
326+ }
327+ Outcome::Victory => ("OPERATION SUCCESSFUL", Color::srgb(0.72, 0.84, 0.46)),
328+ Outcome::Defeat => ("THE FRONT HAS COLLAPSED", Color::srgb(0.92, 0.28, 0.22)),
329+ };
330+ if !existing.is_empty() {
331+ return;
332+ }
333+ let paper = Color::srgb(0.90, 0.85, 0.70);
334+ let day = format!("Day {}", clock.day() + 1);
335+ commands.spawn((
336+ OutcomeOverlay,
337+ GlobalZIndex(100),
338+ Node {
339+ position_type: PositionType::Absolute,
340+ width: Val::Percent(100.0),
341+ height: Val::Percent(100.0),
342+ justify_content: JustifyContent::Center,
343+ align_items: AlignItems::Center,
344+ ..default()
345+ },
346+ BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
347+ children![(
348+ Node {
349+ flex_direction: FlexDirection::Column,
350+ align_items: AlignItems::Center,
351+ row_gap: Val::Px(16.0),
352+ padding: UiRect::all(Val::Px(36.0)),
353+ border: UiRect::all(Val::Px(4.0)),
354+ min_width: Val::Px(560.0),
355+ ..default()
356+ },
357+ BackgroundColor(Color::srgb(0.20, 0.21, 0.15)),
358+ BorderColor::all(accent),
359+ children![
360+ (
361+ Text::new("FRONT COMMAND - OPERATIONS REPORT"),
362+ TextFont {
363+ font_size: FontSize::Px(18.0),
364+ ..default()
365+ },
366+ TextColor(paper),
367+ ),
368+ (
369+ Text::new(title),
370+ TextFont {
371+ font_size: FontSize::Px(44.0),
372+ ..default()
373+ },
374+ TextColor(accent),
375+ ),
376+ (
377+ Text::new(day),
378+ TextFont {
379+ font_size: FontSize::Px(24.0),
380+ ..default()
381+ },
382+ TextColor(paper),
383+ ),
384+ (
385+ Text::new("Press Enter to restart"),
386+ TextFont {
387+ font_size: FontSize::Px(20.0),
388+ ..default()
389+ },
390+ TextColor(paper),
391+ ),
392+ ]
393+ )],
394+ ));
395+}
396+
397+fn front_red() -> Color {
398+ Color::srgb(0.78, 0.12, 0.10)
399+}
400+
401+/// Colour of the supply bar: red at 0, green at 1.
402+fn supply_color(t: f32) -> Color {
403+ let red = Vec3::new(0.85, 0.15, 0.10);
404+ let green = Vec3::new(0.20, 0.75, 0.25);
405+ let c = red.lerp(green, t.clamp(0.0, 1.0));
406+ Color::srgb(c.x, c.y, c.z)
407+}
408+
409+/// Front-line points, north to south: sector points plus extensions to y = ±360.
410+fn front_base_line(net: &Network) -> Vec<Vec2> {
411+ let mut sectors: Vec<Vec2> = net
412+ .nodes
413+ .iter()
414+ .filter_map(|n| {
415+ n.front
416+ .map(|f| Vec2::new(n.pos.x + LINE_OFFSET_X + f.line * LINE_SWING_X, n.pos.y))
417+ })
418+ .collect();
419+ if sectors.is_empty() {
420+ return sectors;
421+ }
422+ sectors.sort_by(|a, b| b.y.total_cmp(&a.y));
423+ let north = sectors[0];
424+ let south = sectors[sectors.len() - 1];
425+ let mut out = vec![Vec2::new(north.x, LINE_EXTENT_Y)];
426+ out.extend(sectors);
427+ out.push(Vec2::new(south.x, -LINE_EXTENT_Y));
428+ out
429+}
430+
431+/// Zig-zags the base line so it reads as jagged.
432+fn jagged(base: &[Vec2]) -> Vec<Vec2> {
433+ let mut out = Vec::new();
434+ for w in base.windows(2) {
435+ let (a, b) = (w[0], w[1]);
436+ let steps = ((a.y - b.y).abs() / JAG_STEP).ceil().max(1.0) as usize;
437+ for s in 0..steps {
438+ let p = a.lerp(b, s as f32 / steps as f32);
439+ let sign = if s % 2 == 0 { -1.0 } else { 1.0 };
440+ out.push(Vec2::new(p.x + sign * JAG_AMPLITUDE, p.y));
441+ }
442+ }
443+ if let Some(&last) = base.last() {
444+ out.push(last);
445+ }
446+ out
447+}
448+
449+/// X of the smooth base line at height `y`.
450+fn x_at(base: &[Vec2], y: f32) -> f32 {
451+ for w in base.windows(2) {
452+ let (a, b) = (w[0], w[1]);
453+ if y <= a.y && y >= b.y {
454+ let span = a.y - b.y;
455+ if span <= 0.0 {
456+ return a.x;
457+ }
458+ return a.x + (b.x - a.x) * ((a.y - y) / span);
459+ }
460+ }
461+ base.first().map_or(0.0, |p| p.x)
462+}
463+
464+fn draw_line(gizmos: &mut Gizmos, base: &[Vec2]) {
465+ let pts = jagged(base);
466+ // Four offset strokes make the line read as thick.
467+ for dx in [-1.5_f32, -0.5, 0.5, 1.5] {
468+ gizmos.linestrip_2d(pts.iter().map(|p| *p + Vec2::new(dx, 0.0)), front_red());
469+ }
470+ // Teeth every TOOTH_SPACING along the line, perpendicular, pointing east.
471+ let mut to_next = TOOTH_SPACING;
472+ for w in pts.windows(2) {
473+ let seg = w[1] - w[0];
474+ let len = seg.length();
475+ if len <= f32::EPSILON {
476+ continue;
477+ }
478+ let dir = seg / len;
479+ let mut normal = Vec2::new(-dir.y, dir.x);
480+ if normal.x < 0.0 {
481+ normal = -normal;
482+ }
483+ let mut along = to_next;
484+ while along <= len {
485+ let p = w[0] + dir * along;
486+ gizmos.line_2d(p, p + normal * TOOTH_LEN, front_red());
487+ along += TOOTH_SPACING;
488+ }
489+ to_next = along - len;
490+ }
491+}
492+
493+/// Faint diagonal hatching east of the line: enemy territory.
494+fn draw_hatching(gizmos: &mut Gizmos, base: &[Vec2]) {
495+ let color = Color::srgba(0.78, 0.12, 0.10, 0.22);
496+ let mut y = -LINE_EXTENT_Y;
497+ while y <= LINE_EXTENT_Y {
498+ let x = x_at(base, y);
499+ gizmos.line_2d(
500+ Vec2::new(x, y),
501+ Vec2::new(x + HATCH_LEN, y + HATCH_LEN),
502+ color,
503+ );
504+ y += HATCH_STEP;
505+ }
506+}
507+
508+/// Small supply bar below a front node, filled red to green by supply.
509+fn draw_supply_bar(gizmos: &mut Gizmos, pos: Vec2, supply: f32) {
510+ let left = pos + Vec2::new(-BAR_W * 0.5, BAR_DY);
511+ let frac = supply.clamp(0.0, 1.0);
512+ let frame = Color::srgb(0.12, 0.11, 0.09);
513+ gizmos.linestrip_2d(
514+ [
515+ left,
516+ left + Vec2::new(BAR_W, 0.0),
517+ left + Vec2::new(BAR_W, BAR_H),
518+ left + Vec2::new(0.0, BAR_H),
519+ left,
520+ ],
521+ frame,
522+ );
523+ let fill = supply_color(frac);
524+ for row in 0..=(BAR_H as u32) {
525+ let y = left.y + row as f32;
526+ gizmos.line_2d(
527+ Vec2::new(left.x, y),
528+ Vec2::new(left.x + BAR_W * frac, y),
529+ fill,
530+ );
531+ }
532+}
533+
534+/// Bomber silhouette in local units, nose along +x. Each part is a closed outline.
535+const BOMBER: [&[[f32; 2]]; 5] = [
536+ &[[22.0, 0.0], [15.0, -2.5], [-14.0, -2.5], [-20.0, -1.0], [-20.0, 1.0], [-14.0, 2.5], [15.0, 2.5]],
537+ &[[8.0, 2.5], [-3.0, 19.0], [-9.0, 19.0], [-6.0, 2.5]],
538+ &[[8.0, -2.5], [-3.0, -19.0], [-9.0, -19.0], [-6.0, -2.5]],
539+ &[[-15.0, 1.5], [-20.0, 9.0], [-24.0, 9.0], [-21.0, 1.0]],
540+ &[[-15.0, -1.5], [-20.0, -9.0], [-24.0, -9.0], [-21.0, -1.0]],
541+];
542+/// Small escort fighter, same convention.
543+const FIGHTER: [&[[f32; 2]]; 3] = [
544+ &[[16.0, 0.0], [8.0, -1.5], [-10.0, -1.5], [-12.0, 0.0], [-10.0, 1.5], [8.0, 1.5]],
545+ &[[3.0, 1.5], [-3.0, 11.0], [-6.0, 11.0], [-5.0, 1.5]],
546+ &[[3.0, -1.5], [-3.0, -11.0], [-6.0, -11.0], [-5.0, -1.5]],
547+];
548+
549+/// Draws a plane as a thick-outlined silhouette, rotated to `heading`.
550+fn draw_plane(
551+ gizmos: &mut Gizmos,
552+ center: Vec2,
553+ heading: Vec2,
554+ scale: f32,
555+ parts: &[&[[f32; 2]]],
556+ color: Color,
557+) {
558+ let side = Vec2::new(-heading.y, heading.x);
559+ for part in parts {
560+ let pts: Vec<Vec2> = part
561+ .iter()
562+ .map(|p| center + heading * (p[0] * scale) + side * (p[1] * scale))
563+ .collect();
564+ // Several strokes side by side make the outline read as a solid shape.
565+ for off in [-0.6_f32, 0.0, 0.6] {
566+ let o = side * off;
567+ gizmos.linestrip_2d(
568+ pts.iter().map(|p| *p + o).chain(std::iter::once(pts[0] + o)),
569+ color,
570+ );
571+ }
572+ }
573+}
574+
575+/// Filled disc from concentric rings.
576+fn fill_disc(gizmos: &mut Gizmos, c: Vec2, radius: f32, color: Color) {
577+ let mut r = radius;
578+ while r > 0.5 {
579+ gizmos.circle_2d(c, r, color);
580+ r -= 1.5;
581+ }
582+}
583+
584+/// Air raid: the hit track flashes, a bomber and escort cross it, and bombs burst along it.
585+fn draw_raid(gizmos: &mut Gizmos, fx: &RaidFx) {
586+ let t = (fx.age / RAID_FX_SECS).clamp(0.0, 1.0);
587+ let dir = (fx.b - fx.a).normalize_or_zero();
588+ let perp = Vec2::new(-dir.y, dir.x);
589+
590+ // Track flashes red-orange, blinking, then fades.
591+ if fx.age >= RAID_FLASH_START {
592+ let fade = (1.0 - (fx.age - RAID_FLASH_START) / 1.5).clamp(0.0, 1.0);
593+ let blink = 0.5 + 0.5 * (fx.age * 16.0).sin();
594+ let color = Color::srgba(1.0, 0.32, 0.06, fade * (0.35 + 0.65 * blink));
595+ for s in [-3.0_f32, -1.5, 0.0, 1.5, 3.0] {
596+ gizmos.line_2d(fx.a + perp * s, fx.b + perp * s, color);
597+ }
598+ }
599+
600+ // Bomber crosses from one side of the track to the other, escort just ahead.
601+ let mid = (fx.a + fx.b) * 0.5;
602+ let from = mid + RAID_PLANE_REACH;
603+ let to = mid - RAID_PLANE_REACH;
604+ let pos = from.lerp(to, t);
605+ let heading = (to - from).normalize_or_zero();
606+ let alpha = (t / 0.08).min(1.0) * ((1.0 - t) / 0.1).min(1.0);
607+ let ink = Color::srgba(0.10, 0.08, 0.07, alpha);
608+ draw_plane(gizmos, pos, heading, 1.0, &BOMBER, ink);
609+ draw_plane(gizmos, pos + heading * 70.0, heading, 0.55, &FIGHTER, ink);
610+
611+ // Bomb bursts along the hit track: hot core, expanding rings, debris spokes.
612+ for (start, along) in RAID_BURSTS {
613+ let local = fx.age - start;
614+ if !(0.0..RAID_BURST_SECS).contains(&local) {
615+ continue;
616+ }
617+ let u = local / RAID_BURST_SECS;
618+ let fade = 1.0 - u;
619+ let c = fx.a.lerp(fx.b, along);
620+ fill_disc(gizmos, c, 4.0 + 9.0 * fade, Color::srgba(1.0, 0.85, 0.3, fade));
621+ gizmos.circle_2d(c, 6.0 + 30.0 * u, Color::srgba(1.0, 0.5, 0.1, fade));
622+ gizmos.circle_2d(c, 4.0 + 20.0 * u, Color::srgba(0.05, 0.05, 0.05, fade));
623+ for k in 0..8 {
624+ let ang = k as f32 * std::f32::consts::FRAC_PI_4 + 0.3;
625+ let u2 = Vec2::new(ang.cos(), ang.sin());
626+ gizmos.line_2d(
627+ c + u2 * (8.0 + 14.0 * u),
628+ c + u2 * (12.0 + 26.0 * u),
629+ Color::srgba(1.0, 0.7, 0.2, fade),
630+ );
631+ }
632+ }
633+}
634+
635+fn draw_front(
636+ mut gizmos: Gizmos,
637+ net: Res<Network>,
638+ time: Res<Time<Real>>,
639+ mut runtime: ResMut<FrontRuntime>,
640+) {
641+ let base = front_base_line(&net);
642+ if !base.is_empty() {
643+ draw_hatching(&mut gizmos, &base);
644+ draw_line(&mut gizmos, &base);
645+ }
646+ for node in net.nodes.iter() {
647+ if let Some(f) = node.front {
648+ draw_supply_bar(&mut gizmos, node.pos, f.supply);
649+ }
650+ }
651+ let dt = time.delta_secs();
652+ runtime.raids.retain_mut(|r| {
653+ r.age += dt;
654+ r.age < RAID_FX_SECS
655+ });
656+ for fx in &runtime.raids {
657+ draw_raid(&mut gizmos, fx);
658+ }
659+}
660+
661+#[cfg(test)]
662+mod tests {
663+ use super::*;
664+
665+ fn front(line: f32, supply: f32) -> FrontState {
666+ FrontState { line, supply }
667+ }
668+
669+ fn close(a: f32, b: f32) -> bool {
670+ (a - b).abs() < 1e-5
671+ }
672+
673+ #[test]
674+ fn fully_supplied_sector_consumes_and_gains_supply() {
675+ let (stock, f) = step_sector([15.0, 15.0, 15.0, 0.0], front(0.0, 0.5), 1.0);
676+ assert!(close(stock[0], 14.0));
677+ assert!(close(stock[1], 14.2));
678+ assert!(close(stock[2], 14.85));
679+ assert!(close(f.supply, 0.55));
680+ assert!(close(f.line, (0.55 - NEUTRAL_SUPPLY) * LINE_RATE));
681+ assert!(close(stock[3], 0.2 + (1.0 - 0.55) * 0.5));
682+ }
683+
684+ #[test]
685+ fn self_repair_adds_one_percent_and_caps_at_intact() {
686+ assert!(close(repair_step(0.5), 0.51));
687+ assert!(close(repair_step(0.995), 1.0));
688+ assert!(close(repair_step(1.0), 1.0));
689+ }
690+}
src/hud.rsadded+1318 -0
@@ -0,0 +1,1318 @@
1+//! Military HUD: a top bar (clock, speed, one pill per front sector), a bottom
2+//! strip (selected node, its supply lines, last news lines), hover tooltips and
3+//! the help overlay. Nothing here blocks the map except the bars themselves.
4+
5+use std::collections::VecDeque;
6+
7+use bevy::ecs::hierarchy::ChildSpawnerCommands;
8+use bevy::ecs::query::Has;
9+use bevy::picking::hover::Hovered;
10+use bevy::prelude::*;
11+use bevy::ui::{Display, UiTransform};
12+use bevy::ui_widgets::{Activate, Button};
13+
14+use bevy::window::PrimaryWindow;
15+
16+use crate::front::hourly_need;
17+use crate::map::{MapHover, good_color};
18+use crate::menu::Menu;
19+use crate::model::{
20+ CarKind, FrontState, GOODS, Good, MIN_USABLE_CONDITION, Network, NodeClicked, NodeId,
21+ NodeKind, Notify, REPAIR_COST, SLOW_CONDITION, Selected, SimClock, Tool, Train, Treasury,
22+ UiPassThrough, stock_text,
23+};
24+use crate::routes::{AddCar, AddTrain, RemoveCar, Scrap, cargo_good};
25+use crate::seasons::SeasonState;
26+use crate::supply::produces;
27+use crate::trains::{TrainNo, train_center};
28+
29+const PANEL: Color = Color::srgba(0.18, 0.2, 0.14, 0.92);
30+/// Opaque, so nothing of the map shows through the bottom strip.
31+const STRIP: Color = Color::srgb(0.15, 0.17, 0.12);
32+const CHIP: Color = Color::srgb(0.1, 0.11, 0.08);
33+const PARCH: Color = Color::srgb(0.92, 0.88, 0.76);
34+const AMBER: Color = Color::srgb(0.95, 0.68, 0.2);
35+const ALERT: Color = Color::srgb(0.9, 0.3, 0.25);
36+const DARK_RED: Color = Color::srgb(0.4, 0.12, 0.1);
37+const GREEN: Color = Color::srgb(0.35, 0.62, 0.28);
38+const DIM: Color = Color::srgb(0.5, 0.48, 0.42);
39+const BTN: Color = Color::srgba(0.27, 0.29, 0.21, 0.95);
40+const BTN_HOVER: Color = Color::srgba(0.35, 0.37, 0.27, 0.98);
41+const BTN_ACTIVE: Color = Color::srgb(0.6, 0.4, 0.12);
42+const BAR_BG: Color = Color::srgba(0.07, 0.08, 0.05, 0.9);
43+
44+pub(crate) const TOP_H: f32 = 44.0;
45+pub(crate) const BOTTOM_H: f32 = 128.0;
46+/// Width of the selected node card in the bottom strip.
47+const CARD_W: f32 = 300.0;
48+/// Preferred width of the news column; it shrinks before the window does.
49+const NEWS_W: f32 = 360.0;
50+const NEWS_LINES: usize = 3;
51+/// Stock value that fills a bar completely.
52+const BAR_FULL: f32 = 30.0;
53+/// World units from a train's centre within which the cursor picks it.
54+const TRAIN_PICK_RADIUS: f32 = 14.0;
55+/// World units from a damaged track within which the cursor picks it.
56+const TRACK_PICK_RADIUS: f32 = 8.0;
57+
58+/// Goods a front sector consumes every game hour, with their hourly need.
59+const SUPPLIED: [Good; 3] = [Good::Ammo, Good::Food, Good::Troops];
60+
61+/// Icon shapes for the help overlay.
62+#[derive(Clone, Copy)]
63+enum Shape {
64+ Round,
65+ Square,
66+ Diamond,
67+}
68+
69+/// Help overlay rows: icon, its colour, and a label of one to three words.
70+const HELP_ROWS: [(Shape, Color, &str); 8] = [
71+ (Shape::Round, PARCH, "City or capital"),
72+ (Shape::Square, PARCH, "Factory (Ammo)"),
73+ (Shape::Diamond, PARCH, "Farm (Food)"),
74+ (Shape::Round, ALERT, "Front: needs supply"),
75+ (Shape::Square, Color::srgb(0.27, 0.51, 0.71), "Light train"),
76+ (Shape::Square, Color::srgb(0.08, 0.08, 0.09), "Heavy train"),
77+ (Shape::Square, ALERT, "Damaged track: click"),
78+ (Shape::Square, Color::srgb(0.85, 0.6, 0.2), "Stock level"),
79+];
80+
81+/// One start hint, shown in the news log when the game starts.
82+const WELCOME_LINES: [&str; 1] = ["D1 Drag a source onto a front"];
83+
84+pub struct HudPlugin;
85+
86+impl Plugin for HudPlugin {
87+ fn build(&self, app: &mut App) {
88+ app.init_resource::<NewsLog>()
89+ .init_resource::<HelpShown>()
90+ .add_systems(Startup, (spawn_hud, welcome))
91+ .add_observer(on_speed_button)
92+ .add_observer(on_help_toggle)
93+ .add_observer(on_front_pill)
94+ .add_systems(
95+ Update,
96+ (
97+ handle_keys,
98+ handle_node_clicks,
99+ collect_news,
100+ update_button_visuals,
101+ update_texts,
102+ sync_front_pills,
103+ update_front_pills,
104+ update_card,
105+ update_sections,
106+ update_gauges,
107+ update_stock_rows,
108+ update_stock_bars,
109+ sync_line_chips,
110+ render_news,
111+ update_help,
112+ update_tooltip,
113+ ),
114+ );
115+ }
116+}
117+
118+/// Whether the help overlay is shown. H and the [?] button toggle it; starts hidden.
119+#[derive(Resource, Default)]
120+struct HelpShown(bool);
121+
122+/// Marks the help overlay.
123+#[derive(Component)]
124+struct HelpPanel;
125+
126+/// Hover tooltip box, moved to the cursor each frame.
127+#[derive(Component)]
128+struct TooltipRoot;
129+
130+#[derive(Component)]
131+struct TooltipText;
132+
133+fn welcome(mut log: ResMut<NewsLog>) {
134+ log.0.extend(WELCOME_LINES.iter().map(|s| s.to_string()));
135+}
136+
137+/// Last `NEWS_LINES` log lines, already prefixed with the day ("D12 ...").
138+#[derive(Resource, Default)]
139+struct NewsLog(VecDeque<String>);
140+
141+#[derive(Component, Clone, Copy)]
142+struct SpeedButton(u32);
143+
144+/// The [?] button in the top bar.
145+#[derive(Component, Clone, Copy)]
146+struct HelpToggle;
147+
148+/// Front sector pill in the top bar. Clicking it selects the front.
149+#[derive(Component, Clone, Copy)]
150+struct FrontPill(NodeId);
151+
152+/// The small square inside a front pill, coloured by the front's health.
153+#[derive(Component, Clone, Copy)]
154+struct FrontSquare(NodeId);
155+
156+/// Container of the front pills, rebuilt when the set of fronts changes.
157+#[derive(Component)]
158+struct FrontPillRow;
159+
160+/// Container of the supply line chips, rebuilt when its content changes.
161+#[derive(Component)]
162+struct ChipRow;
163+
164+/// The selected node card, and the one-line hint shown when nothing is selected.
165+#[derive(Component)]
166+struct CardRoot;
167+
168+#[derive(Component)]
169+struct HintText;
170+
171+/// Text fields whose content is refreshed from the game state each frame.
172+#[derive(Component, Clone, Copy, PartialEq, Eq)]
173+enum Field {
174+ Day,
175+ Treasury,
176+ NodeName,
177+ Stock(usize),
178+ Hunger,
179+ FrontLine,
180+ Supply,
181+}
182+
183+/// Groups of the card shown only for matching node kinds.
184+#[derive(Component, Clone, Copy, PartialEq, Eq)]
185+enum Section {
186+ Settlement,
187+ Front,
188+}
189+
190+/// One stock row of the card, shown only for goods the node kind makes or takes.
191+#[derive(Component, Clone, Copy)]
192+struct StockRow(Good);
193+
194+/// Fill bar for one stock good (index = `Good::idx()`).
195+#[derive(Component, Clone, Copy)]
196+struct StockBar(usize);
197+
198+/// Fill of the hunger bar of a settlement.
199+#[derive(Component)]
200+struct HungerFill;
201+
202+/// Marker on the front-line gauge, from -1 (pushed back) to +1 (right edge).
203+#[derive(Component)]
204+struct LineMarker;
205+
206+#[derive(Component)]
207+struct NewsList;
208+
209+/// One chip of the bottom strip: the supply lines between two nodes.
210+#[derive(Clone, PartialEq)]
211+struct LineGroup {
212+ from: NodeId,
213+ to: NodeId,
214+ good: Option<Good>,
215+ count: usize,
216+ /// One of the trains of the group; [✕] scraps it.
217+ train: Entity,
218+ /// Cars of that train, front to back. Shown as icons and edited in place.
219+ cars: Vec<CarKind>,
220+}
221+
222+fn label(text: &str, size: f32, color: Color) -> impl Bundle {
223+ (
224+ Text::new(text),
225+ TextFont::from_font_size(size),
226+ TextColor(color),
227+ )
228+}
229+
230+fn row(gap: f32) -> Node {
231+ Node {
232+ align_items: AlignItems::Center,
233+ column_gap: Val::Px(gap),
234+ ..default()
235+ }
236+}
237+
238+/// Mini button for the supply chips: a 24 px square.
239+fn spawn_mini_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) {
240+ parent
241+ .spawn((
242+ Button,
243+ Node {
244+ width: Val::Px(24.0),
245+ height: Val::Px(24.0),
246+ align_items: AlignItems::Center,
247+ justify_content: JustifyContent::Center,
248+ flex_shrink: 0.0,
249+ ..default()
250+ },
251+ BackgroundColor(BTN),
252+ Hovered::default(),
253+ marker,
254+ ))
255+ .with_children(|b| {
256+ b.spawn(label(text, 14.0, PARCH));
257+ });
258+}
259+
260+fn spawn_button(parent: &mut ChildSpawnerCommands, text: &str, marker: impl Bundle) {
261+ parent
262+ .spawn((
263+ Button,
264+ Node {
265+ height: Val::Px(26.0),
266+ padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)),
267+ align_items: AlignItems::Center,
268+ justify_content: JustifyContent::Center,
269+ ..default()
270+ },
271+ BackgroundColor(BTN),
272+ Hovered::default(),
273+ marker,
274+ ))
275+ .with_children(|b| {
276+ b.spawn(label(text, 14.0, PARCH));
277+ });
278+}
279+
280+fn bar_color(g: Good) -> Color {
281+ match g {
282+ Good::Ammo => Color::srgb(0.85, 0.6, 0.2),
283+ Good::Food => Color::srgb(0.5, 0.7, 0.3),
284+ Good::Troops => Color::srgb(0.5, 0.6, 0.7),
285+ Good::Wounded => Color::srgb(0.8, 0.3, 0.25),
286+ }
287+}
288+
289+fn spawn_hud(mut commands: Commands) {
290+ // Top bar: title, clock, speed, front pills, then the help toggle.
291+ commands
292+ .spawn((
293+ Node {
294+ position_type: PositionType::Absolute,
295+ top: Val::Px(0.0),
296+ left: Val::Px(0.0),
297+ right: Val::Px(0.0),
298+ height: Val::Px(TOP_H),
299+ padding: UiRect::horizontal(Val::Px(14.0)),
300+ align_items: AlignItems::Center,
301+ column_gap: Val::Px(16.0),
302+ ..default()
303+ },
304+ BackgroundColor(PANEL),
305+ ))
306+ .with_children(|bar| {
307+ bar.spawn(label("IRON LIFELINE", 16.0, AMBER));
308+ bar.spawn((label("", 14.0, PARCH), Field::Day));
309+ crate::seasons::spawn_badge(bar);
310+ bar.spawn((label("", 14.0, PARCH), Field::Treasury));
311+ bar.spawn(row(4.0)).with_children(|s| {
312+ spawn_button(s, "II", SpeedButton(0));
313+ spawn_button(s, "1x", SpeedButton(1));
314+ spawn_button(s, "2x", SpeedButton(2));
315+ spawn_button(s, "4x", SpeedButton(4));
316+ });
317+ bar.spawn((
318+ Node {
319+ flex_grow: 1.0,
320+ min_width: Val::Px(0.0),
321+ ..row(6.0)
322+ },
323+ FrontPillRow,
324+ ));
325+ spawn_button(bar, "?", HelpToggle);
326+ });
327+
328+ // Bottom strip: selected node card | supply lines | news. Every child is
329+ // clipped, so nothing can run past the strip or the window edge.
330+ commands
331+ .spawn((
332+ Node {
333+ position_type: PositionType::Absolute,
334+ bottom: Val::Px(0.0),
335+ left: Val::Px(0.0),
336+ right: Val::Px(0.0),
337+ height: Val::Px(BOTTOM_H),
338+ padding: UiRect::all(Val::Px(8.0)),
339+ column_gap: Val::Px(10.0),
340+ overflow: Overflow::clip(),
341+ ..default()
342+ },
343+ BackgroundColor(STRIP),
344+ ))
345+ .with_children(|s| {
346+ spawn_card(s);
347+
348+ // Supply lines touching the selected node, or all of them, as wrapping chips.
349+ s.spawn((
350+ Node {
351+ flex_grow: 1.0,
352+ min_width: Val::Px(0.0),
353+ height: Val::Percent(100.0),
354+ flex_wrap: FlexWrap::Wrap,
355+ align_content: AlignContent::Start,
356+ align_items: AlignItems::Start,
357+ column_gap: Val::Px(6.0),
358+ row_gap: Val::Px(6.0),
359+ overflow: Overflow::clip(),
360+ ..default()
361+ },
362+ ChipRow,
363+ ));
364+
365+ // Last news lines, newest on top. Lines wrap inside the column.
366+ s.spawn((
367+ Node {
368+ flex_basis: Val::Px(NEWS_W),
369+ flex_shrink: 1.0,
370+ min_width: Val::Px(0.0),
371+ height: Val::Percent(100.0),
372+ padding: UiRect::all(Val::Px(8.0)),
373+ flex_direction: FlexDirection::Column,
374+ row_gap: Val::Px(3.0),
375+ overflow: Overflow::clip(),
376+ ..default()
377+ },
378+ NewsList,
379+ ));
380+ });
381+
382+ // Help overlay: icons with short labels. Top right, under the bar, never blocks the map.
383+ commands
384+ .spawn((
385+ Node {
386+ position_type: PositionType::Absolute,
387+ top: Val::Px(TOP_H + 6.0),
388+ right: Val::Px(8.0),
389+ padding: UiRect::all(Val::Px(10.0)),
390+ flex_direction: FlexDirection::Column,
391+ row_gap: Val::Px(6.0),
392+ display: Display::None,
393+ ..default()
394+ },
395+ BackgroundColor(PANEL),
396+ GlobalZIndex(40),
397+ HelpPanel,
398+ UiPassThrough,
399+ ))
400+ .with_children(|h| {
401+ for (shape, color, text) in HELP_ROWS {
402+ h.spawn(row(8.0)).with_children(|r| {
403+ spawn_swatch(r, shape, color);
404+ r.spawn(label(text, 13.0, PARCH));
405+ });
406+ }
407+ });
408+
409+ // Hover tooltip, moved to the cursor by `update_tooltip`.
410+ commands.spawn((
411+ Node {
412+ position_type: PositionType::Absolute,
413+ display: Display::None,
414+ padding: UiRect::all(Val::Px(8.0)),
415+ ..default()
416+ },
417+ GlobalZIndex(60),
418+ BackgroundColor(PANEL),
419+ TooltipRoot,
420+ UiPassThrough,
421+ children![(label("", 13.0, PARCH), TooltipText)],
422+ ));
423+}
424+
425+/// The left part of the bottom strip: a hint, or the selected node. Compact:
426+/// name and kind on one row, stock bars in a 2x2 grid, then one row for the
427+/// settlement hunger or the front line gauge with its supply.
428+fn spawn_card(s: &mut ChildSpawnerCommands) {
429+ s.spawn(Node {
430+ width: Val::Px(CARD_W),
431+ flex_shrink: 0.0,
432+ height: Val::Percent(100.0),
433+ padding: UiRect::axes(Val::Px(10.0), Val::Px(6.0)),
434+ flex_direction: FlexDirection::Column,
435+ overflow: Overflow::clip(),
436+ ..default()
437+ })
438+ .with_children(|c| {
439+ c.spawn((label("Drag from a source to a front", 14.0, DIM), HintText));
440+ c.spawn((
441+ Node {
442+ flex_direction: FlexDirection::Column,
443+ row_gap: Val::Px(4.0),
444+ display: Display::None,
445+ ..default()
446+ },
447+ CardRoot,
448+ ))
449+ .with_children(|card| {
450+ card.spawn((label("", 14.0, PARCH), Field::NodeName));
451+
452+ // 2x2 stock grid. A cell hides when the node does not use that good.
453+ card.spawn(Node {
454+ flex_direction: FlexDirection::Row,
455+ flex_wrap: FlexWrap::Wrap,
456+ row_gap: Val::Px(4.0),
457+ ..default()
458+ })
459+ .with_children(|grid| {
460+ for g in GOODS {
461+ grid.spawn((
462+ Node {
463+ display: Display::None,
464+ width: Val::Percent(50.0),
465+ padding: UiRect::right(Val::Px(8.0)),
466+ ..row(4.0)
467+ },
468+ StockRow(g),
469+ ))
470+ .with_children(|r| {
471+ r.spawn((
472+ label(g.name(), 12.0, PARCH),
473+ Node {
474+ width: Val::Px(56.0),
475+ ..default()
476+ },
477+ ));
478+ r.spawn((
479+ label("", 12.0, PARCH),
480+ Node {
481+ width: Val::Px(24.0),
482+ ..default()
483+ },
484+ Field::Stock(g.idx()),
485+ ));
486+ r.spawn((
487+ Node {
488+ flex_grow: 1.0,
489+ min_width: Val::Px(0.0),
490+ height: Val::Px(6.0),
491+ ..default()
492+ },
493+ BackgroundColor(BAR_BG),
494+ ))
495+ .with_children(|bg| {
496+ bg.spawn((
497+ Node {
498+ width: Val::Percent(0.0),
499+ height: Val::Percent(100.0),
500+ ..default()
501+ },
502+ BackgroundColor(bar_color(g)),
503+ StockBar(g.idx()),
504+ ));
505+ });
506+ });
507+ }
508+ });
509+
510+ // Settlement: hunger text and bar on one row.
511+ card.spawn((row(6.0), Section::Settlement))
512+ .with_children(|b| {
513+ b.spawn((
514+ label("", 12.0, PARCH),
515+ Node {
516+ width: Val::Px(84.0),
517+ ..default()
518+ },
519+ Field::Hunger,
520+ ));
521+ b.spawn((
522+ Node {
523+ flex_grow: 1.0,
524+ min_width: Val::Px(0.0),
525+ height: Val::Px(5.0),
526+ ..default()
527+ },
528+ BackgroundColor(BAR_BG),
529+ ))
530+ .with_children(|bg| {
531+ bg.spawn((
532+ Node {
533+ width: Val::Percent(0.0),
534+ height: Val::Percent(100.0),
535+ ..default()
536+ },
537+ BackgroundColor(ALERT),
538+ HungerFill,
539+ ));
540+ });
541+ });
542+
543+ // Front: front line text, gauge and supply % on one row.
544+ card.spawn((row(6.0), Section::Front)).with_children(|b| {
545+ b.spawn((
546+ label("", 12.0, PARCH),
547+ Node {
548+ width: Val::Px(84.0),
549+ ..default()
550+ },
551+ Field::FrontLine,
552+ ));
553+ b.spawn((
554+ Node {
555+ flex_grow: 1.0,
556+ min_width: Val::Px(0.0),
557+ height: Val::Px(6.0),
558+ ..default()
559+ },
560+ BackgroundColor(BAR_BG),
561+ ))
562+ .with_children(|bg| {
563+ bg.spawn((
564+ Node {
565+ position_type: PositionType::Absolute,
566+ left: Val::Percent(50.0),
567+ top: Val::Px(-2.0),
568+ width: Val::Px(4.0),
569+ height: Val::Px(10.0),
570+ ..default()
571+ },
572+ BackgroundColor(PARCH),
573+ LineMarker,
574+ ));
575+ });
576+ b.spawn((label("", 12.0, PARCH), Field::Supply));
577+ });
578+ });
579+ });
580+}
581+
582+/// A small icon for the help overlay: round, square or diamond.
583+fn spawn_swatch(r: &mut ChildSpawnerCommands, shape: Shape, color: Color) {
584+ let mut node = Node {
585+ width: Val::Px(12.0),
586+ height: Val::Px(12.0),
587+ ..default()
588+ };
589+ let mut transform = UiTransform::default();
590+ match shape {
591+ Shape::Round => node.border_radius = BorderRadius::MAX,
592+ Shape::Square => {}
593+ Shape::Diamond => transform.rotation = Rot2::degrees(45.0),
594+ }
595+ r.spawn((node, transform, BackgroundColor(color)));
596+}
597+
598+/// A front pill: a button with the front's name and a health square.
599+fn spawn_pill(p: &mut ChildSpawnerCommands, id: NodeId, name: &str) {
600+ p.spawn((
601+ Button,
602+ FrontPill(id),
603+ Node {
604+ height: Val::Px(26.0),
605+ padding: UiRect::axes(Val::Px(10.0), Val::Px(2.0)),
606+ align_items: AlignItems::Center,
607+ column_gap: Val::Px(6.0),
608+ ..default()
609+ },
610+ BackgroundColor(BTN),
611+ Hovered::default(),
612+ ))
613+ .with_children(|b| {
614+ b.spawn((
615+ Node {
616+ width: Val::Px(10.0),
617+ height: Val::Px(10.0),
618+ ..default()
619+ },
620+ BackgroundColor(GREEN),
621+ FrontSquare(id),
622+ ));
623+ b.spawn(label(name, 14.0, PARCH));
624+ });
625+}
626+
627+/// Health colour of a front: green supplied, amber short, red starving.
628+/// A front pushed back past -0.6 pulses red.
629+fn front_color(front: &FrontState, blink: bool) -> Color {
630+ if front.line < -0.6 {
631+ return if blink { ALERT } else { DARK_RED };
632+ }
633+ if front.supply >= 0.7 {
634+ GREEN
635+ } else if front.supply >= 0.4 {
636+ AMBER
637+ } else {
638+ ALERT
639+ }
640+}
641+
642+/// Hours of supply left in a front-line sector, as "12 h" or "4.2 days".
643+fn lasts_text(hours: f32) -> String {
644+ if hours < 48.0 {
645+ format!("{:.0} h", hours)
646+ } else {
647+ format!("{:.1} days", hours / 24.0)
648+ }
649+}
650+
651+/// Formats a treasury amount, e.g. `$4,000` or `-$120`.
652+fn money(v: i64) -> String {
653+ let digits = v.unsigned_abs().to_string();
654+ let mut out = String::new();
655+ for (i, c) in digits.chars().enumerate() {
656+ if i > 0 && (digits.len() - i).is_multiple_of(3) {
657+ out.push(',');
658+ }
659+ out.push(c);
660+ }
661+ if v < 0 {
662+ format!("-${out}")
663+ } else {
664+ format!("${out}")
665+ }
666+}
667+
668+/// Help hotkey. Space and 1/2/3 are handled by `economy.rs`, Esc by `menu.rs`.
669+/// Nothing here runs while a menu is open.
670+fn handle_keys(keys: Res<ButtonInput<KeyCode>>, menu: Res<Menu>, mut help: ResMut<HelpShown>) {
671+ if menu.is_open() {
672+ return;
673+ }
674+ if keys.just_pressed(KeyCode::KeyH) {
675+ help.0 = !help.0;
676+ }
677+}
678+
679+fn on_speed_button(ev: On<Activate>, buttons: Query<&SpeedButton>, mut clock: ResMut<SimClock>) {
680+ if let Ok(btn) = buttons.get(ev.entity)
681+ && clock.speed != btn.0
682+ {
683+ clock.speed = btn.0;
684+ }
685+}
686+
687+fn on_help_toggle(
688+ ev: On<Activate>,
689+ toggles: Query<(), With<HelpToggle>>,
690+ mut help: ResMut<HelpShown>,
691+) {
692+ if toggles.get(ev.entity).is_ok() {
693+ help.0 = !help.0;
694+ }
695+}
696+
697+fn on_front_pill(ev: On<Activate>, pills: Query<&FrontPill>, mut selected: ResMut<Selected>) {
698+ if let Ok(FrontPill(id)) = pills.get(ev.entity) {
699+ selected.0 = Some(*id);
700+ }
701+}
702+
703+fn handle_node_clicks(
704+ mut clicks: MessageReader<NodeClicked>,
705+ tool: Res<Tool>,
706+ mut selected: ResMut<Selected>,
707+) {
708+ for click in clicks.read() {
709+ if matches!(*tool, Tool::Inspect) && selected.0 != Some(click.0) {
710+ selected.0 = Some(click.0);
711+ }
712+ }
713+}
714+
715+fn collect_news(mut notes: MessageReader<Notify>, clock: Res<SimClock>, mut log: ResMut<NewsLog>) {
716+ let day = clock.day() + 1;
717+ let fresh: Vec<String> = notes.read().map(|n| format!("D{day} {}", n.0)).collect();
718+ if fresh.is_empty() {
719+ return;
720+ }
721+ let queue = &mut log.0;
722+ queue.extend(fresh);
723+ while queue.len() > NEWS_LINES {
724+ queue.pop_front();
725+ }
726+}
727+
728+#[allow(
729+ clippy::type_complexity,
730+ reason = "one-off query tuple for button colours"
731+)]
732+fn update_button_visuals(
733+ clock: Res<SimClock>,
734+ help: Res<HelpShown>,
735+ mut buttons: Query<
736+ (
737+ &Hovered,
738+ &mut BackgroundColor,
739+ Option<&SpeedButton>,
740+ Has<HelpToggle>,
741+ ),
742+ Or<(With<SpeedButton>, With<HelpToggle>, With<FrontPill>)>,
743+ >,
744+) {
745+ for (hovered, mut bg, speed, is_help) in &mut buttons {
746+ let active = match speed {
747+ Some(s) => clock.speed == s.0,
748+ None => is_help && help.0,
749+ };
750+ let target = if active {
751+ BTN_ACTIVE
752+ } else if hovered.get() {
753+ BTN_HOVER
754+ } else {
755+ BTN
756+ };
757+ if bg.0 != target {
758+ bg.0 = target;
759+ }
760+ }
761+}
762+
763+fn update_texts(
764+ clock: Res<SimClock>,
765+ treasury: Res<Treasury>,
766+ selected: Res<Selected>,
767+ net: Res<Network>,
768+ mut texts: Query<(&Field, &mut Text, &mut TextColor)>,
769+) {
770+ let node = selected.0.and_then(|id| net.nodes.get(id.0));
771+ for (field, mut text, mut color) in &mut texts {
772+ let (value, tint): (String, Color) = match *field {
773+ Field::Day => (
774+ format!("Day {} (Week {})", clock.day() + 1, clock.week() + 1),
775+ PARCH,
776+ ),
777+ Field::Treasury => (
778+ format!("Treasury {}", money(treasury.0)),
779+ if treasury.0 < 0 { ALERT } else { PARCH },
780+ ),
781+ Field::NodeName => (
782+ node.map_or(String::new(), |n| {
783+ format!("{} | {}", n.name, n.kind.name())
784+ }),
785+ PARCH,
786+ ),
787+ Field::Stock(i) => (
788+ node.map_or(String::new(), |n| format!("{:.0}", n.stock[i])),
789+ PARCH,
790+ ),
791+ Field::Hunger => match node {
792+ Some(n) if is_settlement(n.kind) => (
793+ format!("Hunger {}%", (n.hunger * 100.0).round() as i32),
794+ if n.hunger > 0.5 { ALERT } else { PARCH },
795+ ),
796+ _ => (String::new(), PARCH),
797+ },
798+ Field::FrontLine => (
799+ node.and_then(|n| n.front.as_ref())
800+ .map_or(String::new(), |f| format!("Front {:+.2}", f.line)),
801+ PARCH,
802+ ),
803+ Field::Supply => (
804+ node.and_then(|n| n.front.as_ref())
805+ .map_or(String::new(), |f| {
806+ format!("Supply {}%", (f.supply * 100.0).round() as i32)
807+ }),
808+ PARCH,
809+ ),
810+ };
811+ if text.0 != value {
812+ text.0 = value;
813+ }
814+ if color.0 != tint {
815+ color.0 = tint;
816+ }
817+ }
818+}
819+
820+fn is_settlement(kind: NodeKind) -> bool {
821+ matches!(kind, NodeKind::Capital | NodeKind::City)
822+}
823+
824+/// Rebuilds the front pills when the set of fronts changes.
825+fn sync_front_pills(
826+ mut commands: Commands,
827+ net: Res<Network>,
828+ rows: Query<Entity, With<FrontPillRow>>,
829+ mut shown: Local<Option<Vec<NodeId>>>,
830+) {
831+ let fronts: Vec<NodeId> = net
832+ .nodes
833+ .iter()
834+ .enumerate()
835+ .filter(|(_, n)| n.kind == NodeKind::Front)
836+ .map(|(i, _)| NodeId(i))
837+ .collect();
838+ if shown.as_ref() == Some(&fronts) {
839+ return;
840+ }
841+ let Ok(row) = rows.single() else {
842+ return;
843+ };
844+ commands
845+ .entity(row)
846+ .despawn_related::<Children>()
847+ .with_children(|p| {
848+ for id in &fronts {
849+ spawn_pill(p, *id, &net.nodes[id.0].name);
850+ }
851+ });
852+ *shown = Some(fronts);
853+}
854+
855+/// Colours the health square of each front pill. The red pulse alternates each frame.
856+fn update_front_pills(
857+ time: Res<Time>,
858+ net: Res<Network>,
859+ mut squares: Query<(&FrontSquare, &mut BackgroundColor)>,
860+) {
861+ let blink = (time.elapsed_secs() * 6.0).sin() > 0.0;
862+ for (square, mut bg) in &mut squares {
863+ let color = net
864+ .nodes
865+ .get(square.0.0)
866+ .and_then(|n| n.front.as_ref())
867+ .map_or(DIM, |f| front_color(f, blink));
868+ if bg.0 != color {
869+ bg.0 = color;
870+ }
871+ }
872+}
873+
874+/// Shows the card for the selected node, or the hint when nothing is selected.
875+#[allow(clippy::type_complexity, reason = "one-off query for card and hint")]
876+fn update_card(
877+ selected: Res<Selected>,
878+ mut cards: Query<(&mut Node, Has<CardRoot>), Or<(With<CardRoot>, With<HintText>)>>,
879+) {
880+ let has = selected.0.is_some();
881+ for (mut node, is_card) in &mut cards {
882+ let shown = if is_card { has } else { !has };
883+ let target = if shown { Display::Flex } else { Display::None };
884+ if node.display != target {
885+ node.display = target;
886+ }
887+ }
888+}
889+
890+fn update_sections(
891+ selected: Res<Selected>,
892+ net: Res<Network>,
893+ mut sections: Query<(&Section, &mut Node)>,
894+) {
895+ let kind = selected
896+ .0
897+ .and_then(|id| net.nodes.get(id.0))
898+ .map(|n| n.kind);
899+ for (section, mut node) in &mut sections {
900+ let shown = match (section, kind) {
901+ (Section::Settlement, Some(k)) => is_settlement(k),
902+ (Section::Front, Some(k)) => k == NodeKind::Front,
903+ _ => false,
904+ };
905+ let target = if shown { Display::Flex } else { Display::None };
906+ if node.display != target {
907+ node.display = target;
908+ }
909+ }
910+}
911+
912+/// Shows a stock row only when the selected node makes or takes that good.
913+fn update_stock_rows(
914+ selected: Res<Selected>,
915+ net: Res<Network>,
916+ mut rows: Query<(&StockRow, &mut Node)>,
917+) {
918+ let node = selected.0.and_then(|id| net.nodes.get(id.0));
919+ for (StockRow(good), mut ui) in &mut rows {
920+ let relevant =
921+ node.is_some_and(|n| n.kind.accepts(*good) || produces(n.kind) == Some(*good));
922+ let target = if relevant {
923+ Display::Flex
924+ } else {
925+ Display::None
926+ };
927+ if ui.display != target {
928+ ui.display = target;
929+ }
930+ }
931+}
932+
933+/// Fills the hunger bar of a settlement and moves the front-line marker.
934+fn update_gauges(
935+ selected: Res<Selected>,
936+ net: Res<Network>,
937+ mut gauges: Query<(&mut Node, Has<HungerFill>, Has<LineMarker>)>,
938+) {
939+ let node = selected.0.and_then(|id| net.nodes.get(id.0));
940+ for (mut ui, is_hunger, is_line) in &mut gauges {
941+ if is_hunger {
942+ let fill = node
943+ .filter(|n| is_settlement(n.kind))
944+ .map_or(0.0, |n| (n.hunger * 100.0).clamp(0.0, 100.0));
945+ let target = Val::Percent(fill);
946+ if ui.width != target {
947+ ui.width = target;
948+ }
949+ }
950+ if is_line {
951+ let at = node
952+ .and_then(|n| n.front.as_ref())
953+ .map_or(50.0, |f| ((f.line + 1.0) / 2.0 * 100.0).clamp(0.0, 100.0));
954+ let target = Val::Percent(at);
955+ if ui.left != target {
956+ ui.left = target;
957+ }
958+ }
959+ }
960+}
961+
962+fn update_stock_bars(
963+ selected: Res<Selected>,
964+ net: Res<Network>,
965+ mut bars: Query<(&StockBar, &mut Node)>,
966+) {
967+ let node = selected.0.and_then(|id| net.nodes.get(id.0));
968+ for (bar, mut ui) in &mut bars {
969+ let fill = node.map_or(0.0, |n| {
970+ (n.stock[bar.0] / BAR_FULL * 100.0).clamp(0.0, 100.0)
971+ });
972+ let target = Val::Percent(fill);
973+ if ui.width != target {
974+ ui.width = target;
975+ }
976+ }
977+}
978+
979+/// Rebuilds the supply line chips when the lines shown change. Shows the lines
980+/// that touch the selected node, or all lines when nothing is selected.
981+fn sync_line_chips(
982+ mut commands: Commands,
983+ net: Res<Network>,
984+ selected: Res<Selected>,
985+ trains: Query<(Entity, &Train)>,
986+ rows: Query<Entity, With<ChipRow>>,
987+ mut shown: Local<Option<Vec<LineGroup>>>,
988+) {
989+ let mut groups: Vec<LineGroup> = Vec::new();
990+ for (entity, train) in &trains {
991+ let (Some(first), Some(last)) = (train.route.first(), train.route.last()) else {
992+ continue;
993+ };
994+ let (from, to) = (first.node, last.node);
995+ if selected.0.is_some_and(|id| id != from && id != to) {
996+ continue;
997+ }
998+ match groups.iter_mut().find(|g| g.from == from && g.to == to) {
999+ Some(g) => g.count += 1,
1000+ None => groups.push(LineGroup {
1001+ from,
1002+ to,
1003+ good: cargo_good(train),
1004+ count: 1,
1005+ train: entity,
1006+ cars: train.cars.clone(),
1007+ }),
1008+ }
1009+ }
1010+ groups.sort_by_key(|g| (g.from.0, g.to.0));
1011+
1012+ if shown.as_ref() == Some(&groups) {
1013+ return;
1014+ }
1015+ let Ok(row) = rows.single() else {
1016+ return;
1017+ };
1018+ commands
1019+ .entity(row)
1020+ .despawn_related::<Children>()
1021+ .with_children(|p| {
1022+ if groups.is_empty() {
1023+ let text = if selected.0.is_some() {
1024+ "No supply lines here"
1025+ } else {
1026+ "No supply lines yet"
1027+ };
1028+ p.spawn(label(text, 14.0, DIM));
1029+ }
1030+ for g in &groups {
1031+ spawn_chip(p, g, &net);
1032+ }
1033+ });
1034+ *shown = Some(groups);
1035+}
1036+
1037+/// Colour of a car icon: its good's colour, or grey for a flat car.
1038+fn car_color(car: CarKind) -> Color {
1039+ car.good()
1040+ .map_or(Color::srgb(0.55, 0.53, 0.50), good_color)
1041+}
1042+
1043+/// One chip: good dot, "From > To", train count, [+] and [✕], then the consist of
1044+/// the line's first train: a coloured icon per car (click to remove it), and a
1045+/// coloured button per car type (click to add one).
1046+fn spawn_chip(p: &mut ChildSpawnerCommands, g: &LineGroup, net: &Network) {
1047+ let name = |id: NodeId| net.nodes.get(id.0).map_or("?", |n| n.name.as_str());
1048+ p.spawn((
1049+ Node {
1050+ height: Val::Px(32.0),
1051+ flex_shrink: 0.0,
1052+ align_items: AlignItems::Center,
1053+ column_gap: Val::Px(5.0),
1054+ padding: UiRect::horizontal(Val::Px(6.0)),
1055+ ..default()
1056+ },
1057+ BackgroundColor(CHIP),
1058+ ))
1059+ .with_children(|c| {
1060+ c.spawn((
1061+ Node {
1062+ width: Val::Px(8.0),
1063+ height: Val::Px(8.0),
1064+ ..default()
1065+ },
1066+ BackgroundColor(g.good.map_or(DIM, bar_color)),
1067+ ));
1068+ c.spawn(label(
1069+ &format!("{} > {}", name(g.from), name(g.to)),
1070+ 13.0,
1071+ PARCH,
1072+ ));
1073+ c.spawn(label(&format!("x{}", g.count), 13.0, AMBER));
1074+ spawn_mini_button(
1075+ c,
1076+ "+",
1077+ AddTrain {
1078+ from: g.from,
1079+ to: g.to,
1080+ },
1081+ );
1082+ spawn_mini_button(c, "x", Scrap(g.train));
1083+ for (index, car) in g.cars.iter().enumerate() {
1084+ c.spawn((
1085+ Button,
1086+ Node {
1087+ width: Val::Px(10.0),
1088+ height: Val::Px(14.0),
1089+ flex_shrink: 0.0,
1090+ ..default()
1091+ },
1092+ BackgroundColor(car_color(*car)),
1093+ RemoveCar {
1094+ entity: g.train,
1095+ index,
1096+ },
1097+ ));
1098+ }
1099+ for car in CarKind::ALL {
1100+ c.spawn((
1101+ Button,
1102+ Node {
1103+ width: Val::Px(12.0),
1104+ height: Val::Px(12.0),
1105+ flex_shrink: 0.0,
1106+ ..default()
1107+ },
1108+ BackgroundColor(car_color(car)),
1109+ AddCar {
1110+ entity: g.train,
1111+ car,
1112+ },
1113+ ));
1114+ }
1115+ });
1116+}
1117+
1118+/// Rebuilds the news list when the log changes. Older lines fade out.
1119+fn render_news(log: Res<NewsLog>, lists: Query<Entity, With<NewsList>>, mut commands: Commands) {
1120+ if !log.is_changed() {
1121+ return;
1122+ }
1123+ let Ok(list) = lists.single() else {
1124+ return;
1125+ };
1126+ commands
1127+ .entity(list)
1128+ .despawn_related::<Children>()
1129+ .with_children(|p| {
1130+ // Long entries wrap inside the column; the column clips what does not fit.
1131+ for (age, line) in log.0.iter().rev().take(NEWS_LINES).enumerate() {
1132+ let alpha = (1.0 - 0.3 * age as f32).max(0.35);
1133+ p.spawn((
1134+ label(line, 13.0, Color::srgba(0.92, 0.88, 0.76, alpha)),
1135+ ));
1136+ }
1137+ });
1138+}
1139+
1140+/// Shows or hides the help overlay to match `HelpShown`.
1141+fn update_help(help: Res<HelpShown>, mut panels: Query<&mut Node, With<HelpPanel>>) {
1142+ let target = if help.0 { Display::Flex } else { Display::None };
1143+ for mut node in &mut panels {
1144+ if node.display != target {
1145+ node.display = target;
1146+ }
1147+ }
1148+}
1149+
1150+/// Keeps the tooltip at the cursor, describing the node, train or track under it.
1151+#[allow(clippy::too_many_arguments, reason = "bevy system parameters")]
1152+fn update_tooltip(
1153+ hover: Res<MapHover>,
1154+ net: Res<Network>,
1155+ windows: Query<&Window, With<PrimaryWindow>>,
1156+ trains: Query<(&Train, &TrainNo)>,
1157+ routes: Query<&Train>,
1158+ season: Res<SeasonState>,
1159+ mut roots: Query<&mut Node, With<TooltipRoot>>,
1160+ mut texts: Query<&mut Text, With<TooltipText>>,
1161+) {
1162+ let (Ok(mut root), Ok(mut text)) = (roots.single_mut(), texts.single_mut()) else {
1163+ return;
1164+ };
1165+ let cursor = windows.single().ok().and_then(|w| w.cursor_position());
1166+ let route_refs: Vec<&Train> = routes.iter().collect();
1167+ let content = match (hover.node, hover.world) {
1168+ (Some(id), _) => node_tip(&net, &route_refs, id, season.season.food_mult()),
1169+ (None, Some(world)) => train_tip(&net, world, hover.zoom, &trains)
1170+ .or_else(|| track_tip(&net, world, hover.zoom)),
1171+ (None, None) => None,
1172+ };
1173+ match (content, cursor) {
1174+ (Some(s), Some(c)) => {
1175+ if text.0 != s {
1176+ text.0 = s;
1177+ }
1178+ root.display = Display::Flex;
1179+ root.left = Val::Px(c.x + 16.0);
1180+ root.top = Val::Px(c.y + 16.0);
1181+ }
1182+ _ => root.display = Display::None,
1183+ }
1184+}
1185+
1186+/// Tooltip lines for a node: name and kind, what it makes, stock. A front adds its status.
1187+fn node_tip(net: &Network, trains: &[&Train], id: NodeId, food_mult: f32) -> Option<String> {
1188+ let n = net.nodes.get(id.0)?;
1189+ let mut text = format!("{} ({})", n.name, n.kind.name());
1190+ if n.kind.makes_text() != "nothing" {
1191+ text.push_str(&format!("\nMakes {}", n.kind.makes_text()));
1192+ }
1193+ text.push_str(&format!("\nStock: {}", stock_text(&n.stock)));
1194+ if n.kind == NodeKind::Front {
1195+ text.push('\n');
1196+ text.push_str(&front_problem(net, trains, id, food_mult));
1197+ }
1198+ Some(text)
1199+}
1200+
1201+/// One-line reason a front is short, highest priority first: rail, delivery, then goods.
1202+fn front_problem(net: &Network, trains: &[&Train], id: NodeId, food_mult: f32) -> String {
1203+ let capital = net
1204+ .nodes
1205+ .iter()
1206+ .position(|n| n.kind == NodeKind::Capital)
1207+ .map(NodeId);
1208+ let connected = capital.is_some_and(|c| net.shortest_path(c, id).is_some());
1209+ if !connected {
1210+ let cut = net
1211+ .tracks
1212+ .iter()
1213+ .any(|t| (t.a == id || t.b == id) && t.condition < MIN_USABLE_CONDITION);
1214+ return if cut {
1215+ "Rail cut: repair the track"
1216+ } else {
1217+ "No rail: drag to lay track"
1218+ }
1219+ .to_string();
1220+ }
1221+ if !trains.iter().any(|t| t.route.iter().any(|s| s.node == id)) {
1222+ return "No train delivers here".to_string();
1223+ }
1224+ let node = &net.nodes[id.0];
1225+ let mut short: Vec<&str> = Vec::new();
1226+ let mut lowest: Option<(f32, &str)> = None;
1227+ for good in SUPPLIED {
1228+ let hours = node.stock[good.idx()].max(0.0) / hourly_need(good, food_mult);
1229+ if hours < 1.0 {
1230+ short.push(good.name());
1231+ }
1232+ if lowest.is_none_or(|(h, _)| hours < h) {
1233+ lowest = Some((hours, good.name()));
1234+ }
1235+ }
1236+ match lowest {
1237+ Some((hours, _)) if !short.is_empty() => {
1238+ format!("Short: {} ({} left)", short.join(", "), lasts_text(hours))
1239+ }
1240+ _ => "Well supplied".to_string(),
1241+ }
1242+}
1243+
1244+/// Tooltip lines for the train nearest the cursor, if one is close enough.
1245+fn train_tip(
1246+ net: &Network,
1247+ world: Vec2,
1248+ zoom: f32,
1249+ trains: &Query<(&Train, &TrainNo)>,
1250+) -> Option<String> {
1251+ let (train, no) = trains
1252+ .iter()
1253+ .map(|(t, no)| (train_center(net, t).distance(world), t, no))
1254+ .filter(|(d, _, _)| *d <= TRAIN_PICK_RADIUS * zoom)
1255+ .min_by(|a, b| a.0.total_cmp(&b.0))
1256+ .map(|(_, t, no)| (t, no))?;
1257+
1258+ let carried: Vec<String> = GOODS
1259+ .iter()
1260+ .filter(|g| train.cargo[g.idx()] >= 0.5)
1261+ .map(|g| format!("{} {:.0}", g.name(), train.cargo[g.idx()]))
1262+ .collect();
1263+ let cargo = if carried.is_empty() {
1264+ "empty".to_string()
1265+ } else {
1266+ carried.join(", ")
1267+ };
1268+ let dest = train
1269+ .route
1270+ .get(train.stop_idx)
1271+ .and_then(|s| net.nodes.get(s.node.0))
1272+ .map_or("-", |n| n.name.as_str());
1273+ let mut lines = vec![format!(
1274+ "{} train #{}: {} to {}",
1275+ train.loco.name(),
1276+ no.0,
1277+ cargo,
1278+ dest
1279+ )];
1280+ if train.stalled {
1281+ lines.push("Stalled: no track".to_string());
1282+ } else if let Some(next) = train.path.first()
1283+ && let Some(i) = net.track_between(train.at, *next)
1284+ && net.tracks[i].condition < SLOW_CONDITION
1285+ {
1286+ lines.push("Slowed: damaged track".to_string());
1287+ }
1288+ Some(lines.join("\n"))
1289+}
1290+
1291+/// Distance from a point to a straight track segment.
1292+fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 {
1293+ let ab = b - a;
1294+ let t = ((p - a).dot(ab) / ab.length_squared().max(f32::EPSILON)).clamp(0.0, 1.0);
1295+ p.distance(a + ab * t)
1296+}
1297+
1298+/// Tooltip for the damaged track nearest the cursor: its state and the repair price.
1299+fn track_tip(net: &Network, world: Vec2, zoom: f32) -> Option<String> {
1300+ let track = net
1301+ .tracks
1302+ .iter()
1303+ .filter(|t| t.condition < 1.0)
1304+ .map(|t| {
1305+ let d = segment_distance(world, net.nodes[t.a.0].pos, net.nodes[t.b.0].pos);
1306+ (d, t)
1307+ })
1308+ .filter(|(d, _)| *d <= TRACK_PICK_RADIUS * zoom)
1309+ .min_by(|a, b| a.0.total_cmp(&b.0))
1310+ .map(|(_, t)| t)?;
1311+ let mut text = format!("Damaged track\nRepair ${REPAIR_COST}");
1312+ if track.condition < MIN_USABLE_CONDITION {
1313+ text.push_str("\nBlocked");
1314+ } else if track.condition < SLOW_CONDITION {
1315+ text.push_str("\nSlow");
1316+ }
1317+ Some(text)
1318+}
src/main.rsadded+135 -0
@@ -0,0 +1,135 @@
1+#![forbid(unsafe_code)]
2+
3+mod audio;
4+mod build;
5+mod demo;
6+mod economy;
7+mod evac;
8+mod front;
9+mod hud;
10+mod map;
11+mod menu;
12+mod model;
13+mod routes;
14+mod scenario;
15+mod seasons;
16+mod settings;
17+mod signals;
18+mod supply;
19+mod trains;
20+mod tutorial;
21+
22+use bevy::camera::ScalingMode;
23+use bevy::prelude::*;
24+
25+use build::BuildPlugin;
26+use demo::DemoPlugin;
27+use economy::EconomyPlugin;
28+use evac::EvacPlugin;
29+use front::FrontPlugin;
30+use hud::HudPlugin;
31+use map::MapPlugin;
32+use menu::{Menu, MenuPlugin, MenuScreen};
33+use model::*;
34+use routes::RoutesPlugin;
35+use scenario::{CapturePlugin, Cli, ScenarioPlugin};
36+use seasons::SeasonsPlugin;
37+use settings::SettingsPlugin;
38+use supply::SupplyPlugin;
39+use trains::TrainsPlugin;
40+use tutorial::TutorialPlugin;
41+
42+fn main() {
43+ let cli = Cli::from_env();
44+ let (settings, settings_warning) = settings::load();
45+ // The game opens on the main menu, except in the scenario harness run. The demo starts there too.
46+ let skip_menu = cli.scenario || cli.play;
47+ let exit_when_done = cli.record.is_some();
48+ let menu = if skip_menu {
49+ Menu::default()
50+ } else {
51+ Menu {
52+ screen: Some(MenuScreen::Main),
53+ ..default()
54+ }
55+ };
56+ let mut app = App::new();
57+ // Harness runs have no sound device to open, so audio is off there.
58+ let headless = cli.scenario || cli.record.is_some() || cli.quit_after.is_some();
59+ let plugins = DefaultPlugins.set(WindowPlugin {
60+ primary_window: Some(settings::initial_window(&settings.display)),
61+ ..default()
62+ });
63+ let plugins = if headless {
64+ plugins.disable::<bevy::audio::AudioPlugin>()
65+ } else {
66+ plugins
67+ };
68+ app.add_plugins(plugins)
69+ .insert_resource(ClearColor(Color::srgb(0.86, 0.81, 0.68)))
70+ .insert_resource(settings)
71+ .insert_resource(menu)
72+ .init_resource::<Network>()
73+ .init_resource::<Treasury>()
74+ .init_resource::<SimClock>()
75+ .init_resource::<Tool>()
76+ .init_resource::<Selected>()
77+ .init_resource::<Outcome>()
78+ .add_message::<NodeClicked>()
79+ .add_message::<TrackClicked>()
80+ .add_message::<HourTick>()
81+ .add_message::<Notify>()
82+ .add_systems(Startup, spawn_camera)
83+ .add_plugins((
84+ MapPlugin,
85+ BuildPlugin,
86+ RoutesPlugin,
87+ TrainsPlugin,
88+ EconomyPlugin,
89+ FrontPlugin,
90+ EvacPlugin,
91+ HudPlugin,
92+ SupplyPlugin,
93+ SeasonsPlugin,
94+ ))
95+ .add_plugins((
96+ MenuPlugin,
97+ SettingsPlugin {
98+ load_warning: settings_warning,
99+ },
100+ ))
101+ .add_plugins(audio::GameAudioPlugin)
102+ .add_plugins(signals::SignalsPlugin)
103+ .add_plugins(TutorialPlugin {
104+ enabled: !cli.scenario && !cli.demo,
105+ });
106+ if cli.scenario {
107+ app.add_plugins(ScenarioPlugin { stress: cli.stress });
108+ }
109+ if cli.demo {
110+ app.add_plugins(DemoPlugin { exit_when_done });
111+ }
112+ if cli.record.is_some() || cli.quit_after.is_some() {
113+ app.add_plugins(CapturePlugin {
114+ record: cli.record,
115+ quit_after: cli.quit_after,
116+ });
117+ }
118+ app.run();
119+}
120+
121+/// Spawns the 2D camera. Its scale and offset are set by `map::fit_camera` on the first frame
122+/// and on every window resize, so the map frame fits the area between the bars.
123+fn spawn_camera(mut commands: Commands) {
124+ commands.spawn((
125+ Camera2d,
126+ Transform::default(),
127+ Projection::Orthographic(OrthographicProjection {
128+ scale: 1.0,
129+ scaling_mode: ScalingMode::FixedVertical {
130+ viewport_height: 720.0,
131+ },
132+ ..OrthographicProjection::default_2d()
133+ }),
134+ ));
135+}
src/map.rsadded+1121 -0
@@ -0,0 +1,1121 @@
1+//! Campaign map: camera controls, click picking and the parchment map art.
2+//!
3+//! Everything on the map is drawn with gizmos each frame, except the node
4+//! name labels, which are spawned once at startup.
5+
6+use bevy::ecs::system::SystemParam;
7+use bevy::input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll};
8+use bevy::prelude::*;
9+use bevy::sprite::Anchor;
10+use bevy::time::{Real, Time};
11+use bevy::ui::{CalculatedClip, ComputedNode, UiGlobalTransform, UiScale};
12+use bevy::window::PrimaryWindow;
13+
14+use crate::menu::Menu;
15+use crate::model::{
16+ GOODS, Good, MIN_USABLE_CONDITION, Network, Node, NodeId, NodeKind, SLOW_CONDITION, Selected,
17+ TrackClicked, UiPassThrough,
18+};
19+use crate::settings::Settings;
20+
21+/// Default zoom limits (orthographic scale). The view is 720 world units tall at scale 1.
22+const MIN_SCALE: f32 = 0.5;
23+const MAX_SCALE: f32 = 2.5;
24+/// World units of the map frame (the playfield), centred on the origin.
25+const MAP_W: f32 = 1280.0;
26+const MAP_H: f32 = 720.0;
27+/// Blank space kept between the map frame and the window edges, in logical px.
28+const FIT_MARGIN_X: f32 = 16.0;
29+const FIT_MARGIN_Y: f32 = 8.0;
30+/// Arrow-key pan speed in logical pixels per second.
31+const KEY_PAN_SPEED: f32 = 450.0;
32+/// Node pick radius in logical pixels, so clicks feel the same at any zoom or window size.
33+const NODE_PICK_RADIUS: f32 = 20.0;
34+/// Track pick distance in logical pixels.
35+const TRACK_PICK_DISTANCE: f32 = 8.0;
36+/// Node name label: glyph size in world units. About 15 px on screen at 720 px tall with the
37+/// camera scale 1.31 (27 at the old scale 1.8).
38+const NODE_LABEL_SIZE: f32 = 19.65;
39+/// Offset of a label centre below the node, just under the stock bars (which end 30 units down).
40+const NODE_LABEL_OFFSET: f32 = 46.0;
41+/// Gap between a node centre and a label placed beside or above it.
42+const LABEL_SIDE_GAP: f32 = 14.0;
43+/// Average advance of the label font in ems, to estimate label width before layout.
44+const LABEL_CHAR_EM: f32 = 0.6;
45+/// Gap kept clear at each end of a track so it does not run into node glyphs.
46+const NODE_GLYPH_RADIUS: f32 = 12.0;
47+/// Spacing of crossties along a track.
48+const TIE_SPACING: f32 = 12.0;
49+/// Half-length of a crosstie.
50+const TIE_HALF_LEN: f32 = 4.0;
51+/// Stock bar scale: world units per stock unit, capped at `BAR_MAX_WIDTH`.
52+const BAR_UNITS_PER_STOCK: f32 = 0.4;
53+const BAR_MAX_WIDTH: f32 = 40.0;
54+
55+const INK: Color = Color::srgb(0.22, 0.15, 0.09);
56+const RUST: Color = Color::srgb(0.66, 0.26, 0.12);
57+const RED: Color = Color::srgb(0.78, 0.12, 0.10);
58+const AMBER: Color = Color::srgb(1.0, 0.70, 0.10);
59+const HOVER_RING: Color = Color::srgb(1.0, 0.98, 0.90);
60+/// Name of a captured site, and the parchment that greys its glyph.
61+const CAPTURED_INK: Color = Color::srgb(0.52, 0.48, 0.42);
62+const PARCH: Color = Color::srgba(0.86, 0.81, 0.68, 0.6);
63+/// Slowed track, and the repair badge on any damaged track.
64+const SLOW_ORANGE: Color = Color::srgb(1.0, 0.55, 0.10);
65+const CRATER: Color = Color::srgb(0.16, 0.10, 0.06);
66+/// Warm tint of lightly scorched track.
67+const SCORCH: Color = Color::srgb(0.80, 0.42, 0.16);
68+/// Any track below this condition shows its damage, however mild.
69+const DAMAGED_CONDITION: f32 = 0.95;
70+/// Gap cut into blocked track, and the distance between the two rails.
71+const GAP_LEN: f32 = 14.0;
72+const RAIL_HALF: f32 = 2.5;
73+/// Repair badge sits this far off the track's midpoint.
74+const BADGE_OFFSET: f32 = 16.0;
75+const BADGE_R: f32 = 8.0;
76+
77+pub struct MapPlugin;
78+
79+impl Plugin for MapPlugin {
80+ fn build(&self, app: &mut App) {
81+ app.init_resource::<MapHover>()
82+ .init_resource::<ZoomLimits>()
83+ .add_systems(Startup, spawn_node_labels)
84+ .add_systems(
85+ Update,
86+ (
87+ fit_camera,
88+ camera_controls,
89+ picking,
90+ draw_map,
91+ sync_node_labels,
92+ place_node_labels,
93+ update_world_text,
94+ )
95+ .chain(),
96+ );
97+ }
98+}
99+
100+/// Zoom bounds the wheel is clamped to. `fit_camera` widens them when the fitted view
101+/// falls outside the defaults, so the fitted view is always reachable.
102+#[derive(Resource, Clone, Copy)]
103+pub struct ZoomLimits {
104+ pub min: f32,
105+ pub max: f32,
106+}
107+
108+impl Default for ZoomLimits {
109+ fn default() -> Self {
110+ Self {
111+ min: MIN_SCALE,
112+ max: MAX_SCALE,
113+ }
114+ }
115+}
116+
117+/// Ortho scale and camera offset that fit the map frame into the free area: the full window
118+/// width, and the height between the top bar and the bottom strip. `size` is the window in
119+/// logical px. The camera is `FixedVertical { 720 }`, so `h` logical px show `720 * scale`
120+/// world units, i.e. `world_per_px = 720 * scale / h`.
121+///
122+/// The bars are UI nodes sized in UI px, which `UiScale` multiplies, so their logical height
123+/// is `TOP_H * ui_scale` and `BOTTOM_H * ui_scale`.
124+fn fit_view(size: Vec2, ui_scale: f32) -> (f32, Vec2) {
125+ let top = crate::hud::TOP_H * ui_scale;
126+ let bottom = crate::hud::BOTTOM_H * ui_scale;
127+ let free_w = (size.x - 2.0 * FIT_MARGIN_X).max(1.0);
128+ let free_h = (size.y - top - bottom - 2.0 * FIT_MARGIN_Y).max(1.0);
129+ // World units per logical px that make the frame fit both ways.
130+ let world_per_px = (MAP_W / free_w).max(MAP_H / free_h);
131+ let scale = world_per_px * size.y / MAP_H;
132+ // The free area centre is (bottom - top) / 2 px above the window centre (screen y points
133+ // down, and the bottom strip is the taller one). The camera centre looks at world y = offset,
134+ // so world y = 0 lands `offset` below the window centre: offset = (top - bottom) / 2 px.
135+ let offset_y = (top - bottom) * 0.5 * world_per_px;
136+ (scale, Vec2::new(0.0, offset_y))
137+}
138+
139+/// Everything `fit_view` depends on. The camera is refitted whenever any of it changes.
140+#[derive(Clone, Copy, PartialEq)]
141+struct FitKey {
142+ /// Window size in logical px.
143+ size: Vec2,
144+ /// Physical px per logical px.
145+ scale_factor: f32,
146+ /// UI scale, which sets the bar heights.
147+ ui_scale: f32,
148+ /// Logical size of the camera viewport, which the projection area is built from.
149+ viewport: Option<Vec2>,
150+}
151+
152+/// Refits the camera whenever the window size, scale factor, UI scale or camera viewport
153+/// changes (and once at startup). The zoom and pan are left alone between those changes.
154+fn fit_camera(
155+ window: Single<&Window, With<PrimaryWindow>>,
156+ ui_scale: Res<UiScale>,
157+ mut limits: ResMut<ZoomLimits>,
158+ mut last: Local<Option<FitKey>>,
159+ mut cameras: Query<(&Camera, &mut Transform, &mut Projection), With<Camera2d>>,
160+) {
161+ let size = Vec2::new(window.width(), window.height());
162+ if size.min_element() < 1.0 {
163+ return;
164+ }
165+ let Ok((camera, mut transform, mut projection)) = cameras.single_mut() else {
166+ return;
167+ };
168+ let key = FitKey {
169+ size,
170+ scale_factor: window.scale_factor(),
171+ ui_scale: ui_scale.0,
172+ viewport: camera.logical_viewport_size(),
173+ };
174+ if *last == Some(key) {
175+ return;
176+ }
177+ *last = Some(key);
178+ let (scale, offset) = fit_view(size, ui_scale.0);
179+ limits.min = MIN_SCALE.min(scale);
180+ limits.max = MAX_SCALE.max(scale);
181+ if let Projection::Orthographic(ortho) = projection.as_mut() {
182+ ortho.scale = scale;
183+ }
184+ transform.translation = offset.extend(transform.translation.z);
185+}
186+
187+/// Pointer state recomputed every frame by `picking`. Empty while the cursor is over the UI.
188+#[derive(Resource, Default)]
189+pub struct MapHover {
190+ /// Node under the cursor.
191+ pub node: Option<NodeId>,
192+ /// Cursor position in world units, when it is over the map.
193+ pub world: Option<Vec2>,
194+ /// Orthographic zoom scale. Hover and pick code outside this file reads it.
195+ pub zoom: f32,
196+ /// World units covered by one logical pixel, from the projection area and viewport size.
197+ pub world_per_px: f32,
198+}
199+
200+/// Text in world space that stays sharp and readable at any zoom or window size.
201+///
202+/// The font is rasterized at the screen's pixel density and the transform scales it back to
203+/// `size`, so glyphs map one to one onto physical pixels. `update_world_text` keeps this in
204+/// step with the zoom, the window and the text size setting.
205+#[derive(Component, Clone, Copy, Debug)]
206+pub struct WorldText {
207+ /// Glyph size in world units at the default text size.
208+ pub size: f32,
209+}
210+
211+/// Marker for a node name label. Holds the index of the node it names.
212+#[derive(Component)]
213+struct NodeLabel(usize);
214+
215+/// Sides of a node a name label can sit on, in tie-break order.
216+#[derive(Clone, Copy)]
217+enum LabelSide {
218+ Below,
219+ Above,
220+ Right,
221+ Left,
222+}
223+
224+const LABEL_SIDES: [LabelSide; 4] = [
225+ LabelSide::Below,
226+ LabelSide::Above,
227+ LabelSide::Right,
228+ LabelSide::Left,
229+];
230+
231+/// Keeps one name label per node. Spawns labels for nodes added at runtime, drops the
232+/// labels of nodes a restart removed, and greys the labels of captured sites.
233+fn sync_node_labels(
234+ mut commands: Commands,
235+ net: Res<Network>,
236+ mut labels: Query<(Entity, &NodeLabel, &mut TextColor)>,
237+) {
238+ let mut have = vec![false; net.nodes.len()];
239+ for (entity, label, mut color) in &mut labels {
240+ let Some(node) = net.nodes.get(label.0) else {
241+ commands.entity(entity).despawn();
242+ continue;
243+ };
244+ have[label.0] = true;
245+ let want = if node.captured { CAPTURED_INK } else { INK };
246+ if color.0 != want {
247+ color.0 = want;
248+ }
249+ }
250+ for (i, node) in net.nodes.iter().enumerate() {
251+ if have[i] {
252+ continue;
253+ }
254+ commands.spawn((
255+ NodeLabel(i),
256+ Text2d(node.name.clone()),
257+ WorldText {
258+ size: NODE_LABEL_SIZE,
259+ },
260+ TextColor(INK),
261+ TextLayout::default(),
262+ Anchor::CENTER,
263+ Transform::from_xyz(node.pos.x, node.pos.y, 1.0),
264+ ));
265+ }
266+}
267+
268+fn spawn_node_labels(mut commands: Commands, net: Res<Network>) {
269+ for (i, node) in net.nodes.iter().enumerate() {
270+ commands.spawn((
271+ NodeLabel(i),
272+ Text2d(node.name.clone()),
273+ WorldText {
274+ size: NODE_LABEL_SIZE,
275+ },
276+ TextColor(INK),
277+ TextLayout::default(),
278+ Anchor::CENTER,
279+ Transform::from_xyz(node.pos.x, node.pos.y, 1.0),
280+ ));
281+ }
282+}
283+
284+/// Anchor point (relative to the node), text anchor and justification for a label on `side`.
285+fn label_anchor(side: LabelSide) -> (Vec2, Anchor, Justify) {
286+ match side {
287+ LabelSide::Below => (
288+ Vec2::new(0.0, -NODE_LABEL_OFFSET),
289+ Anchor::CENTER,
290+ Justify::Center,
291+ ),
292+ LabelSide::Above => (
293+ Vec2::new(0.0, LABEL_SIDE_GAP + NODE_LABEL_SIZE * 0.5),
294+ Anchor::CENTER,
295+ Justify::Center,
296+ ),
297+ LabelSide::Right => (
298+ Vec2::new(LABEL_SIDE_GAP, 0.0),
299+ Anchor::CENTER_LEFT,
300+ Justify::Left,
301+ ),
302+ LabelSide::Left => (
303+ Vec2::new(-LABEL_SIDE_GAP, 0.0),
304+ Anchor::CENTER_RIGHT,
305+ Justify::Right,
306+ ),
307+ }
308+}
309+
310+/// Bounding box (relative to the node) of a label of `width` placed on `side`, padded by 1.
311+fn label_rect(side: LabelSide, width: f32) -> (Vec2, Vec2) {
312+ let (p, _, _) = label_anchor(side);
313+ let h = NODE_LABEL_SIZE * 0.5;
314+ let half_w = width * 0.5;
315+ let (min, max) = match side {
316+ LabelSide::Below | LabelSide::Above => (p - Vec2::new(half_w, h), p + Vec2::new(half_w, h)),
317+ LabelSide::Right => (p - Vec2::new(0.0, h), p + Vec2::new(width, h)),
318+ LabelSide::Left => (p - Vec2::new(width, h), p + Vec2::new(0.0, h)),
319+ };
320+ (min - Vec2::ONE, max + Vec2::ONE)
321+}
322+
323+/// Boxes (relative to the node) that a label must avoid: the stock bars, the producer icon,
324+/// and for a front the supply row and its warning ring.
325+fn node_obstacles(kind: NodeKind) -> Vec<(Vec2, Vec2)> {
326+ let mut out = vec![(Vec2::new(-20.0, -31.0), Vec2::new(20.0, -16.0))];
327+ if matches!(kind, NodeKind::Factory | NodeKind::Farm | NodeKind::City) {
328+ // Column where evacuation crates stack, north-west of the site.
329+ out.push((Vec2::new(-41.0, 9.0), Vec2::new(-31.0, 63.0)));
330+ }
331+ match kind {
332+ // Matches the producer icon offset in signals.rs.
333+ NodeKind::Factory | NodeKind::Farm | NodeKind::Capital | NodeKind::City => {
334+ out.push((Vec2::new(10.0, 10.0), Vec2::new(24.0, 24.0)));
335+ }
336+ NodeKind::Front => {
337+ // Supply row: three icons of side 14 at x = -20, 0, 20, centred on y = 44.
338+ out.push((Vec2::new(-27.0, 37.0), Vec2::new(27.0, 51.0)));
339+ out.push((Vec2::splat(-29.0), Vec2::splat(29.0)));
340+ }
341+ NodeKind::Depot => {}
342+ }
343+ out
344+}
345+
346+fn rects_overlap(a_min: Vec2, a_max: Vec2, b_min: Vec2, b_max: Vec2) -> bool {
347+ a_min.x < b_max.x && b_min.x < a_max.x && a_min.y < b_max.y && b_min.y < a_max.y
348+}
349+
350+/// Liang-Barsky test: does segment `a`-`b` pass through the box `min`-`max`?
351+fn segment_hits_rect(a: Vec2, b: Vec2, min: Vec2, max: Vec2) -> bool {
352+ let d = b - a;
353+ let (mut t0, mut t1) = (0.0f32, 1.0f32);
354+ let edges = [
355+ (-d.x, a.x - min.x),
356+ (d.x, max.x - a.x),
357+ (-d.y, a.y - min.y),
358+ (d.y, max.y - a.y),
359+ ];
360+ for (p, q) in edges {
361+ if p == 0.0 {
362+ if q < 0.0 {
363+ return false;
364+ }
365+ } else {
366+ let r = q / p;
367+ if p < 0.0 {
368+ if r > t1 {
369+ return false;
370+ }
371+ t0 = t0.max(r);
372+ } else {
373+ if r < t0 {
374+ return false;
375+ }
376+ t1 = t1.min(r);
377+ }
378+ }
379+ }
380+ t0 <= t1
381+}
382+
383+/// Puts each name label on the side with the fewest collisions. A side costs 10 per track
384+/// segment crossing its box and 10 per stock bar, icon or front ring it overlaps. Ties go to
385+/// the earlier entry in `LABEL_SIDES`. Runs only when the set of tracks changes.
386+fn place_node_labels(
387+ net: Res<Network>,
388+ mut placed: Local<Option<Vec<(usize, usize)>>>,
389+ fresh: Query<(), Added<NodeLabel>>,
390+ mut labels: Query<(&NodeLabel, &mut Transform, &mut Anchor, &mut TextLayout)>,
391+) {
392+ let unchanged = matches!(placed.as_ref(), Some(p)
393+ if p.len() == net.tracks.len()
394+ && p.iter().zip(&net.tracks).all(|(p, t)| *p == (t.a.0, t.b.0)));
395+ if unchanged && fresh.is_empty() {
396+ return;
397+ }
398+ *placed = Some(net.tracks.iter().map(|t| (t.a.0, t.b.0)).collect());
399+
400+ for (label, mut transform, mut anchor, mut layout) in &mut labels {
401+ let node = &net.nodes[label.0];
402+ let width = node.name.chars().count() as f32 * LABEL_CHAR_EM * NODE_LABEL_SIZE;
403+ let obstacles = node_obstacles(node.kind);
404+
405+ let mut best = (usize::MAX, LabelSide::Below);
406+ for side in LABEL_SIDES {
407+ let (min, max) = label_rect(side, width);
408+ let overlaps = obstacles
409+ .iter()
410+ .filter(|(o_min, o_max)| rects_overlap(min, max, *o_min, *o_max))
411+ .count();
412+ let hits = net
413+ .tracks
414+ .iter()
415+ .filter(|t| {
416+ let a = net.nodes[t.a.0].pos - node.pos;
417+ let b = net.nodes[t.b.0].pos - node.pos;
418+ segment_hits_rect(a, b, min, max)
419+ })
420+ .count();
421+ let score = 10 * (overlaps + hits);
422+ if score < best.0 {
423+ best = (score, side);
424+ }
425+ }
426+
427+ let (offset, text_anchor, justify) = label_anchor(best.1);
428+ transform.translation = (node.pos + offset).extend(transform.translation.z);
429+ *anchor = text_anchor;
430+ *layout = TextLayout::justify(justify);
431+ }
432+}
433+
434+/// World units covered by one logical pixel of the view.
435+///
436+/// Read from the projection's area, which is updated after the frame's systems run, so it
437+/// lags a zoom change by one frame. Returns 0 before the first projection update.
438+fn world_per_pixel(camera: &Camera, ortho: &OrthographicProjection) -> f32 {
439+ match camera.logical_viewport_size() {
440+ Some(viewport) if viewport.y > 0.0 => ortho.area.height() / viewport.y,
441+ _ => 0.0,
442+ }
443+}
444+
445+/// Keeps every `WorldText` at the right font size and transform for the current view.
446+///
447+/// The font is set to `size` times the physical pixels per world unit, and the transform
448+/// scales it back down, so the glyphs land on physical pixels with no resampling blur.
449+fn update_world_text(
450+ settings: Res<Settings>,
451+ camera: Single<(&Camera, &Projection), With<Camera2d>>,
452+ mut texts: Query<(&WorldText, &mut TextFont, &mut Transform)>,
453+) {
454+ let (camera, projection) = *camera;
455+ let Projection::Orthographic(ortho) = projection else {
456+ return;
457+ };
458+ let Some(physical) = camera.physical_viewport_size() else {
459+ return;
460+ };
461+ let area_height = ortho.area.height();
462+ if area_height <= 0.0 || physical.y == 0 {
463+ return;
464+ }
465+ let density = physical.y as f32 / area_height;
466+ let text_size = settings.display.text_size;
467+ for (text, mut font, mut transform) in &mut texts {
468+ let font_size = FontSize::Px(text.size * text_size * density);
469+ if font.font_size != font_size {
470+ font.font_size = font_size;
471+ }
472+ let scale = Vec3::splat(1.0 / density);
473+ if transform.scale != scale {
474+ transform.scale = scale;
475+ }
476+ }
477+}
478+
479+/// Right-drag and arrow-key panning, mouse-wheel zoom.
480+fn camera_controls(
481+ time: Res<Time>,
482+ buttons: Res<ButtonInput<MouseButton>>,
483+ keys: Res<ButtonInput<KeyCode>>,
484+ motion: Res<AccumulatedMouseMotion>,
485+ scroll: Res<AccumulatedMouseScroll>,
486+ limits: Res<ZoomLimits>,
487+ mut cameras: Query<(&Camera, &mut Transform, &mut Projection), With<Camera2d>>,
488+) {
489+ let Ok((camera, mut transform, mut projection)) = cameras.single_mut() else {
490+ return;
491+ };
492+ let Projection::Orthographic(ortho) = projection.as_mut() else {
493+ return;
494+ };
495+
496+ if scroll.delta.y != 0.0 {
497+ let factor = (1.0 - scroll.delta.y * 0.1).clamp(0.5, 1.5);
498+ ortho.scale = (ortho.scale * factor).clamp(limits.min, limits.max);
499+ }
500+ let px = world_per_pixel(camera, ortho);
501+
502+ if buttons.pressed(MouseButton::Right) {
503+ // Screen y points down, world y points up.
504+ transform.translation.x -= motion.delta.x * px;
505+ transform.translation.y += motion.delta.y * px;
506+ }
507+
508+ let step = KEY_PAN_SPEED * px * time.delta_secs();
509+ if keys.pressed(KeyCode::ArrowLeft) {
510+ transform.translation.x -= step;
511+ }
512+ if keys.pressed(KeyCode::ArrowRight) {
513+ transform.translation.x += step;
514+ }
515+ if keys.pressed(KeyCode::ArrowUp) {
516+ transform.translation.y += step;
517+ }
518+ if keys.pressed(KeyCode::ArrowDown) {
519+ transform.translation.y -= step;
520+ }
521+}
522+
523+/// UI nodes with the data the map needs to hit-test them.
524+type UiNodes<'w, 's> = Query<
525+ 'w,
526+ 's,
527+ (
528+ Entity,
529+ &'static ComputedNode,
530+ &'static UiGlobalTransform,
531+ Option<&'static InheritedVisibility>,
532+ Option<&'static CalculatedClip>,
533+ ),
534+>;
535+
536+/// Everything the map picking needs, grouped to keep the system signature short.
537+#[derive(SystemParam)]
538+pub(crate) struct PickParams<'w, 's> {
539+ buttons: Res<'w, ButtonInput<MouseButton>>,
540+ net: Res<'w, Network>,
541+ menu: Res<'w, Menu>,
542+ hover: ResMut<'w, MapHover>,
543+ window: Single<'w, 's, &'static Window, With<PrimaryWindow>>,
544+ camera: Single<
545+ 'w,
546+ 's,
547+ (
548+ &'static Camera,
549+ &'static GlobalTransform,
550+ &'static Projection,
551+ ),
552+ With<Camera2d>,
553+ >,
554+ ui: UiNodes<'w, 's>,
555+ passthrough: Query<'w, 's, (), With<UiPassThrough>>,
556+ parents: Query<'w, 's, &'static ChildOf>,
557+ track_clicked: MessageWriter<'w, TrackClicked>,
558+}
559+
560+/// Map colour of a good: stock bars and supply line previews.
561+pub fn good_color(g: Good) -> Color {
562+ match g {
563+ Good::Ammo => Color::srgb(0.33, 0.36, 0.14), // dark olive
564+ Good::Food => Color::srgb(0.87, 0.73, 0.40), // wheat
565+ Good::Troops => Color::srgb(0.10, 0.18, 0.42), // navy
566+ Good::Wounded => Color::srgb(0.72, 0.08, 0.22), // crimson
567+ }
568+}
569+
570+/// True when the physical-pixel point lies inside any visible UI node.
571+///
572+/// This is the single rule for "the cursor is on the interface": the map
573+/// ignores hover and clicks there. It tests the node rectangles directly, so
574+/// it works for every UI widget, whichever interaction API it uses. Nodes marked
575+/// `UiPassThrough`, or inside such a node, never count.
576+fn point_over_ui(
577+ ui: &UiNodes,
578+ passthrough: &Query<(), With<UiPassThrough>>,
579+ parents: &Query<&ChildOf>,
580+ point: Vec2,
581+) -> bool {
582+ ui.iter()
583+ .any(|(entity, node, transform, visibility, clip)| {
584+ // Display::None nodes lay out to zero size and are skipped by the size test.
585+ node.size() != Vec2::ZERO
586+ && visibility.is_some_and(|v| v.get())
587+ && node.contains_point(*transform, point)
588+ && clip.is_none_or(|c| c.contains_point(point))
589+ && !is_pass_through(entity, passthrough, parents)
590+ })
591+}
592+
593+/// True when `entity` or one of its ancestors is marked `UiPassThrough`.
594+fn is_pass_through(
595+ entity: Entity,
596+ passthrough: &Query<(), With<UiPassThrough>>,
597+ parents: &Query<&ChildOf>,
598+) -> bool {
599+ let mut current = Some(entity);
600+ while let Some(e) = current {
601+ if passthrough.get(e).is_ok() {
602+ return true;
603+ }
604+ current = parents.get(e).ok().map(ChildOf::parent);
605+ }
606+ false
607+}
608+
609+/// Updates the hover target and handles left-click picking.
610+///
611+/// Hover and clicks are ignored while the cursor is over the UI.
612+pub(crate) fn picking(mut p: PickParams) {
613+ let (camera, cam_tf, projection) = *p.camera;
614+ let (zoom, world_per_px) = match projection {
615+ Projection::Orthographic(ortho) => (ortho.scale, world_per_pixel(camera, ortho)),
616+ _ => (1.0, 0.0),
617+ };
618+ let cursor = p.window.cursor_position();
619+ let over_ui = cursor.is_some_and(|c| {
620+ let physical = c * camera.target_scaling_factor().unwrap_or(1.0);
621+ point_over_ui(&p.ui, &p.passthrough, &p.parents, physical)
622+ });
623+ // Hover and clicks are ignored while the cursor is over the UI or a menu is open.
624+ let world = if over_ui || p.menu.is_open() {
625+ None
626+ } else {
627+ cursor.and_then(|c| camera.viewport_to_world_2d(cam_tf, c).ok())
628+ };
629+
630+ p.hover.node = world.and_then(|w| p.net.node_at(w, NODE_PICK_RADIUS * world_per_px));
631+ p.hover.world = world;
632+ p.hover.zoom = zoom;
633+ p.hover.world_per_px = world_per_px;
634+
635+ if !p.buttons.just_pressed(MouseButton::Left) {
636+ return;
637+ }
638+ let Some(world) = world else {
639+ return;
640+ };
641+
642+ // A press on a node belongs to the supply gesture (supply.rs), which sends the
643+ // click on release when the pointer did not move.
644+ if p.net
645+ .node_at(world, NODE_PICK_RADIUS * world_per_px)
646+ .is_some()
647+ {
648+ return;
649+ }
650+
651+ let max_dist = TRACK_PICK_DISTANCE * world_per_px;
652+ let nearest = p
653+ .net
654+ .tracks
655+ .iter()
656+ .enumerate()
657+ .map(|(i, t)| {
658+ let a = p.net.nodes[t.a.0].pos;
659+ let b = p.net.nodes[t.b.0].pos;
660+ (i, dist_point_segment(world, a, b))
661+ })
662+ .filter(|(_, d)| *d <= max_dist)
663+ .min_by(|x, y| x.1.total_cmp(&y.1));
664+ if let Some((index, _)) = nearest {
665+ p.track_clicked.write(TrackClicked(index));
666+ }
667+}
668+
669+fn dist_point_segment(p: Vec2, a: Vec2, b: Vec2) -> f32 {
670+ let ab = b - a;
671+ let len2 = ab.length_squared();
672+ let t = if len2 == 0.0 {
673+ 0.0
674+ } else {
675+ ((p - a).dot(ab) / len2).clamp(0.0, 1.0)
676+ };
677+ (a + ab * t).distance(p)
678+}
679+
680+fn mix(a: Color, b: Color, t: f32) -> Color {
681+ let a = a.to_srgba();
682+ let b = b.to_srgba();
683+ Color::srgb(
684+ a.red + (b.red - a.red) * t,
685+ a.green + (b.green - a.green) * t,
686+ a.blue + (b.blue - a.blue) * t,
687+ )
688+}
689+
690+fn iso(p: Vec2) -> Isometry2d {
691+ Isometry2d::from_translation(p)
692+}
693+
694+/// Closed polygon outline.
695+fn polygon(gizmos: &mut Gizmos, points: &[Vec2], color: Color) {
696+ let first = points[0];
697+ gizmos.linestrip_2d(points.iter().copied().chain(std::iter::once(first)), color);
698+}
699+
700+/// Solid-looking disc built from concentric rings.
701+fn disc(gizmos: &mut Gizmos, center: Vec2, radius: f32, color: Color) {
702+ let mut r = radius;
703+ while r > 0.5 {
704+ gizmos.circle_2d(iso(center), r, color);
705+ r -= 1.5;
706+ }
707+}
708+
709+pub(crate) fn dashed(gizmos: &mut Gizmos, a: Vec2, b: Vec2, dash: f32, gap: f32, color: Color) {
710+ let len = a.distance(b);
711+ if len <= 0.0 {
712+ return;
713+ }
714+ let dir = (b - a) / len;
715+ let mut t = 0.0;
716+ while t < len {
717+ let s = (t + dash).min(len);
718+ gizmos.line_2d(a + dir * t, a + dir * s, color);
719+ t += dash + gap;
720+ }
721+}
722+
723+fn draw_map(
724+ mut gizmos: Gizmos,
725+ net: Res<Network>,
726+ selected: Res<Selected>,
727+ hover: Res<MapHover>,
728+ time: Res<Time<Real>>,
729+) {
730+ draw_background(&mut gizmos);
731+ let hovered = hovered_track(&net, &hover);
732+ draw_tracks(&mut gizmos, &net, hovered, time.elapsed_secs());
733+ for node in &net.nodes {
734+ draw_node(&mut gizmos, node);
735+ }
736+ draw_highlights(&mut gizmos, &net, &selected, &hover);
737+}
738+
739+/// Faint grid and the double-line map border.
740+fn draw_background(gizmos: &mut Gizmos) {
741+ let grid = Color::srgba(0.45, 0.33, 0.20, 0.15);
742+ for x in (-600..=600).step_by(100) {
743+ let x = x as f32;
744+ gizmos.line_2d(Vec2::new(x, -360.0), Vec2::new(x, 360.0), grid);
745+ }
746+ for y in (-300..=300).step_by(100) {
747+ let y = y as f32;
748+ gizmos.line_2d(Vec2::new(-640.0, y), Vec2::new(640.0, y), grid);
749+ }
750+
751+ gizmos.rect_2d(iso(Vec2::ZERO), Vec2::new(1280.0, 720.0), INK);
752+ gizmos.rect_2d(iso(Vec2::ZERO), Vec2::new(1270.0, 710.0), INK);
753+}
754+
755+/// Track under the cursor, found the same way a click finds it. None over a node.
756+fn hovered_track(net: &Network, hover: &MapHover) -> Option<usize> {
757+ if hover.node.is_some() {
758+ return None;
759+ }
760+ let w = hover.world?;
761+ let max_dist = TRACK_PICK_DISTANCE * hover.world_per_px;
762+ net.tracks
763+ .iter()
764+ .enumerate()
765+ .map(|(i, t)| (i, dist_point_segment(w, net.nodes[t.a.0].pos, net.nodes[t.b.0].pos)))
766+ .filter(|(_, d)| *d <= max_dist)
767+ .min_by(|x, y| x.1.total_cmp(&y.1))
768+ .map(|(i, _)| i)
769+}
770+
771+/// Deterministic hash to [0, 1). Same seed, same spot, so craters never jitter.
772+pub(crate) fn unit_hash(seed: u32) -> f32 {
773+ let mut x = seed.wrapping_mul(0x9E37_79B9) ^ 0x85EB_CA6B;
774+ x ^= x >> 15;
775+ x = x.wrapping_mul(0x2C1B_3C6D);
776+ x ^= x >> 12;
777+ (x & 0xFFFF) as f32 / 65536.0
778+}
779+
780+/// Small crater: a ring with six radiating ticks.
781+fn draw_crater(gizmos: &mut Gizmos, c: Vec2, color: Color) {
782+ gizmos.circle_2d(iso(c), 3.5, color);
783+ for k in 0..6 {
784+ let ang = k as f32 * std::f32::consts::FRAC_PI_3 + 0.4;
785+ let u = Vec2::new(ang.cos(), ang.sin());
786+ gizmos.line_2d(c + u * 5.0, c + u * 8.5, color);
787+ }
788+}
789+
790+/// Two or three craters at fixed spots along the track, plus `extra` more as damage grows.
791+/// Blocked track keeps its gap clear.
792+fn draw_craters(
793+ gizmos: &mut Gizmos,
794+ start: Vec2,
795+ end: Vec2,
796+ index: usize,
797+ blocked: bool,
798+ extra: u32,
799+ color: Color,
800+) {
801+ let dir = (end - start).normalize_or_zero();
802+ let perp = Vec2::new(-dir.y, dir.x);
803+ let seed = index as u32 * 97;
804+ let count = 2 + (unit_hash(seed) * 2.0) as u32 + extra;
805+ for k in 0..count {
806+ let h = unit_hash(seed + 11 + k * 7);
807+ let side = unit_hash(seed + 29 + k * 13);
808+ let along = if blocked {
809+ if k % 2 == 0 {
810+ 0.14 + 0.18 * h
811+ } else {
812+ 0.68 + 0.18 * h
813+ }
814+ } else {
815+ 0.15 + 0.7 * h
816+ };
817+ let c = start.lerp(end, along) + perp * (side - 0.5) * 8.0;
818+ draw_crater(gizmos, c, color);
819+ }
820+}
821+
822+/// Stroke of `width` px centred on a..b, built from parallel 1px lines.
823+fn band(gizmos: &mut Gizmos, a: Vec2, b: Vec2, width: f32, color: Color) {
824+ let len = a.distance(b);
825+ if len <= 0.0 {
826+ return;
827+ }
828+ let perp = Vec2::new(-(b - a).y, (b - a).x) / len;
829+ let n = width.round().max(1.0) as i32;
830+ for k in 0..n {
831+ let off = perp * (k as f32 - (n - 1) as f32 * 0.5);
832+ gizmos.line_2d(a + off, b + off, color);
833+ }
834+}
835+
836+/// Rail that is broken and kinked: short segments jogging sideways, with a gap every fourth.
837+fn broken_rail(gizmos: &mut Gizmos, a: Vec2, b: Vec2, off: Vec2, color: Color) {
838+ let len = a.distance(b);
839+ if len <= 0.0 {
840+ return;
841+ }
842+ let dir = (b - a) / len;
843+ let perp = Vec2::new(-dir.y, dir.x);
844+ let seg = 8.0;
845+ let point = |i: usize| {
846+ let t = (i as f32 * seg).min(len);
847+ let jog = if i % 2 == 0 { 1.6 } else { -1.6 };
848+ a + dir * t + off + perp * jog
849+ };
850+ for i in 0..(len / seg).ceil() as usize {
851+ if i % 4 != 3 {
852+ gizmos.line_2d(point(i), point(i + 1), color);
853+ }
854+ }
855+}
856+
857+fn with_alpha(color: Color, alpha: f32) -> Color {
858+ let c = color.to_srgba();
859+ Color::srgba(c.red, c.green, c.blue, alpha)
860+}
861+
862+/// Crossties between two points, same spacing as intact track.
863+fn draw_ties(gizmos: &mut Gizmos, from: Vec2, to: Vec2, color: Color) {
864+ let len = from.distance(to);
865+ if len <= 0.0 {
866+ return;
867+ }
868+ let dir = (to - from) / len;
869+ let perp = Vec2::new(-dir.y, dir.x) * TIE_HALF_LEN;
870+ let ties = (len / TIE_SPACING).floor() as u32;
871+ for i in 0..=ties {
872+ let p = from + dir * (i as f32 * TIE_SPACING);
873+ gizmos.line_2d(p - perp, p + perp, color);
874+ }
875+}
876+
877+/// Line drawn three strokes wide so it reads at default zoom.
878+fn thick_line(gizmos: &mut Gizmos, a: Vec2, b: Vec2, color: Color) {
879+ let len = a.distance(b);
880+ if len <= 0.0 {
881+ return;
882+ }
883+ let perp = Vec2::new(-(b - a).y, (b - a).x) / len * 0.7;
884+ for off in [-perp, Vec2::ZERO, perp] {
885+ gizmos.line_2d(a + off, b + off, color);
886+ }
887+}
888+
889+/// Repair badge: dark disc with a wrench, pulsing gently. Brighter when hovered.
890+/// `scale` grows it with the damage it stands for.
891+fn draw_repair_badge(gizmos: &mut Gizmos, c: Vec2, t: f32, hot: bool, scale: f32) {
892+ let pulse = 0.5 + 0.5 * (t * std::f32::consts::TAU / 1.6).sin();
893+ let r = (BADGE_R + 1.2 * pulse) * scale;
894+ disc(gizmos, c, r, INK);
895+ let ring = if hot { HOVER_RING } else { AMBER };
896+ gizmos.circle_2d(iso(c), r, ring);
897+ let d = Vec2::new(1.0, -1.0).normalize();
898+ thick_line(gizmos, c - d * 4.0 * scale, c + d * 1.5 * scale, ring);
899+ gizmos.circle_2d(iso(c + d * 3.5 * scale), 2.6 * scale, ring);
900+}
901+
902+fn draw_tracks(gizmos: &mut Gizmos, net: &Network, hovered: Option<usize>, t: f32) {
903+ let slow_pulse = 0.5 + 0.5 * (t * std::f32::consts::TAU / 1.2).sin();
904+ let blocked_pulse = 0.5 + 0.5 * (t * std::f32::consts::TAU / 0.6).sin();
905+ for (index, track) in net.tracks.iter().enumerate() {
906+ let a = net.nodes[track.a.0].pos;
907+ let b = net.nodes[track.b.0].pos;
908+ let len = a.distance(b);
909+ if len <= 2.0 * NODE_GLYPH_RADIUS {
910+ continue;
911+ }
912+ let dir = (b - a) / len;
913+ let perp = Vec2::new(-dir.y, dir.x);
914+ let start = a + dir * NODE_GLYPH_RADIUS;
915+ let end = b - dir * NODE_GLYPH_RADIUS;
916+ let mid = (start + end) * 0.5;
917+
918+ if track.condition >= DAMAGED_CONDITION {
919+ let ink = mix(RUST, INK, track.condition.clamp(0.0, 1.0));
920+ gizmos.line_2d(start, end, ink);
921+ draw_ties(gizmos, start, end, ink);
922+ continue;
923+ }
924+
925+ // 0 when fully repaired, 1 when the track is at zero condition.
926+ let damage = (1.0 - track.condition).clamp(0.0, 1.0);
927+ let hot = hovered == Some(index);
928+ let lit = |c: Color| if hot { mix(c, Color::WHITE, 0.45) } else { c };
929+ let crater_alpha = (damage * 2.0 + 0.2).min(1.0);
930+ let badge_scale = 0.8 + 0.8 * damage;
931+ let blocked = track.condition < MIN_USABLE_CONDITION;
932+ let slowed = !blocked && track.condition < SLOW_CONDITION;
933+
934+ if blocked {
935+ // Bold red band, rails stop at a gap in the middle and bend apart at its edges.
936+ let gap = GAP_LEN.min(len * 0.3);
937+ let g1 = mid - dir * gap * 0.5;
938+ let g2 = mid + dir * gap * 0.5;
939+ let col = lit(RED);
940+ let glow = with_alpha(col, 0.3 + 0.35 * blocked_pulse);
941+ band(gizmos, start, g1, 8.0 + 4.0 * damage, glow);
942+ band(gizmos, g2, end, 8.0 + 4.0 * damage, glow);
943+ for s in [-1.0_f32, 1.0] {
944+ let off = perp * (RAIL_HALF * s);
945+ let spread = perp * (s * 6.5);
946+ thick_line(gizmos, start + off, g1 + off, col);
947+ thick_line(gizmos, g1 + off, g1 - dir * 3.0 + spread, col);
948+ thick_line(gizmos, g2 + off, end + off, col);
949+ thick_line(gizmos, g2 + off, g2 + dir * 3.0 + spread, col);
950+ }
951+ draw_ties(gizmos, start, g1, col);
952+ draw_ties(gizmos, g2, end, col);
953+ let ring = with_alpha(RED, 0.4 + 0.6 * blocked_pulse);
954+ let r = 9.0 + 4.0 * blocked_pulse;
955+ gizmos.circle_2d(iso(mid), r, ring);
956+ gizmos.circle_2d(iso(mid), r + 1.5, ring);
957+ draw_craters(
958+ gizmos,
959+ start,
960+ end,
961+ index,
962+ true,
963+ 1,
964+ with_alpha(CRATER, crater_alpha),
965+ );
966+ draw_repair_badge(gizmos, mid + perp * BADGE_OFFSET, t, hot, badge_scale);
967+ } else if slowed {
968+ // Thick orange glow under broken, kinked rails, dark craters, large badge.
969+ let glow = with_alpha(
970+ lit(SLOW_ORANGE),
971+ (0.25 + 0.35 * damage) * (0.7 + 0.3 * slow_pulse),
972+ );
973+ band(gizmos, start, end, 5.0 + 8.0 * damage, glow);
974+ let rail = lit(INK);
975+ for s in [-RAIL_HALF, RAIL_HALF] {
976+ broken_rail(gizmos, start, end, perp * s, rail);
977+ }
978+ draw_ties(gizmos, start, end, rail);
979+ draw_craters(
980+ gizmos,
981+ start,
982+ end,
983+ index,
984+ false,
985+ 1,
986+ with_alpha(CRATER, crater_alpha),
987+ );
988+ draw_repair_badge(gizmos, mid + perp * BADGE_OFFSET, t, hot, badge_scale);
989+ } else {
990+ // Lightly scorched: warm tint along the rails, a soft band, a few scorch craters.
991+ let warm = (damage * 2.5).min(1.0) * 0.8;
992+ let col = lit(mix(INK, SCORCH, warm));
993+ band(
994+ gizmos,
995+ start,
996+ end,
997+ 4.0,
998+ with_alpha(lit(SCORCH), (0.15 + damage).min(0.35)),
999+ );
1000+ for s in [-0.7_f32, 0.0, 0.7] {
1001+ let off = perp * s;
1002+ gizmos.line_2d(start + off, end + off, col);
1003+ }
1004+ draw_ties(gizmos, start, end, col);
1005+ draw_craters(
1006+ gizmos,
1007+ start,
1008+ end,
1009+ index,
1010+ false,
1011+ 0,
1012+ with_alpha(CRATER, crater_alpha),
1013+ );
1014+ draw_repair_badge(gizmos, mid + perp * BADGE_OFFSET, t, hot, badge_scale);
1015+ }
1016+ }
1017+}
1018+
1019+fn draw_node(gizmos: &mut Gizmos, node: &Node) {
1020+ let c = node.pos;
1021+ match node.kind {
1022+ NodeKind::Capital => {
1023+ gizmos.circle_2d(iso(c), 12.0, INK);
1024+ gizmos.circle_2d(iso(c), 9.0, INK);
1025+ let mut star = Vec::with_capacity(10);
1026+ for i in 0..10 {
1027+ let r = if i % 2 == 0 { 6.0 } else { 2.5 };
1028+ let angle = std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / 5.0;
1029+ star.push(c + Vec2::new(angle.cos(), angle.sin()) * r);
1030+ }
1031+ polygon(gizmos, &star, INK);
1032+ }
1033+ NodeKind::City => {
1034+ gizmos.circle_2d(iso(c), 10.0, INK);
1035+ }
1036+ NodeKind::Factory => {
1037+ gizmos.rect_2d(iso(c), Vec2::splat(20.0), INK);
1038+ }
1039+ NodeKind::Farm => {
1040+ let d = 11.0;
1041+ polygon(
1042+ gizmos,
1043+ &[
1044+ c + Vec2::new(0.0, d),
1045+ c + Vec2::new(d, 0.0),
1046+ c + Vec2::new(0.0, -d),
1047+ c + Vec2::new(-d, 0.0),
1048+ ],
1049+ INK,
1050+ );
1051+ }
1052+ NodeKind::Depot => {
1053+ polygon(
1054+ gizmos,
1055+ &[
1056+ c + Vec2::new(0.0, 12.0),
1057+ c + Vec2::new(11.0, -8.0),
1058+ c + Vec2::new(-11.0, -8.0),
1059+ ],
1060+ INK,
1061+ );
1062+ }
1063+ NodeKind::Front => {
1064+ disc(gizmos, c, 10.0, RED);
1065+ gizmos.circle_2d(iso(c), 10.0, INK);
1066+ }
1067+ }
1068+
1069+ draw_stock_bars(gizmos, node);
1070+ if node.captured {
1071+ draw_captured(gizmos, c);
1072+ }
1073+}
1074+
1075+/// A captured site: its glyph greyed out under a red cross in a box.
1076+fn draw_captured(gizmos: &mut Gizmos, c: Vec2) {
1077+ disc(gizmos, c, 13.0, PARCH);
1078+ let half = 13.0;
1079+ gizmos.rect_2d(iso(c), Vec2::splat(half * 2.0), RED);
1080+ gizmos.line_2d(c + Vec2::new(-half, -half), c + Vec2::new(half, half), RED);
1081+ gizmos.line_2d(c + Vec2::new(-half, half), c + Vec2::new(half, -half), RED);
1082+}
1083+
1084+/// Four tiny bars under the node: ammo, food, troops, wounded.
1085+fn draw_stock_bars(gizmos: &mut Gizmos, node: &Node) {
1086+ let track = Color::srgba(0.22, 0.15, 0.09, 0.2);
1087+ let left = node.pos.x - BAR_MAX_WIDTH * 0.5;
1088+ for (i, good) in GOODS.iter().enumerate() {
1089+ let y = node.pos.y - 18.0 - i as f32 * 4.0;
1090+ let stock = node.stock[good.idx()];
1091+ gizmos.line_2d(
1092+ Vec2::new(left, y),
1093+ Vec2::new(left + BAR_MAX_WIDTH, y),
1094+ track,
1095+ );
1096+ let width = (stock.max(0.0) * BAR_UNITS_PER_STOCK).min(BAR_MAX_WIDTH);
1097+ if width > 0.0 {
1098+ gizmos.line_2d(
1099+ Vec2::new(left, y),
1100+ Vec2::new(left + width, y),
1101+ good_color(*good),
1102+ );
1103+ }
1104+ }
1105+}
1106+
1107+fn draw_highlights(gizmos: &mut Gizmos, net: &Network, selected: &Selected, hover: &MapHover) {
1108+ if let Some(id) = hover.node
1109+ && Some(id) != selected.0
1110+ {
1111+ let c = net.nodes[id.0].pos;
1112+ gizmos.circle_2d(iso(c), 18.0, HOVER_RING);
1113+ }
1114+ if let Some(id) = selected.0
1115+ && let Some(node) = net.nodes.get(id.0)
1116+ {
1117+ for r in [18.0, 19.0, 20.0, 21.0] {
1118+ gizmos.circle_2d(iso(node.pos), r, AMBER);
1119+ }
1120+ }
1121+}
src/menu.rsadded+487 -0
@@ -0,0 +1,487 @@
1+//! Menus: the main menu, the pause menu, Settings and How to Play.
2+//!
3+//! While a menu is open the simulation is paused (the clock speed is saved and
4+//! restored), map clicks and hover are ignored (`map.rs`), and gameplay hotkeys
5+//! are ignored (`hud.rs`, `economy.rs`). Esc is handled here.
6+
7+use bevy::app::AppExit;
8+use bevy::ecs::hierarchy::ChildSpawnerCommands;
9+use bevy::picking::hover::Hovered;
10+use bevy::prelude::*;
11+use bevy::ui::Display;
12+use bevy::ui_widgets::{Activate, Button};
13+
14+use crate::economy::advance_clock;
15+use crate::front::reset_game;
16+use crate::model::{SimClock, Tool};
17+use crate::settings::{self, Settings, WindowModeSetting};
18+
19+const PANEL: Color = Color::srgba(0.18, 0.2, 0.14, 0.97);
20+const OVERLAY: Color = Color::srgba(0.07, 0.08, 0.05, 0.9);
21+const PARCH: Color = Color::srgb(0.92, 0.88, 0.76);
22+const AMBER: Color = Color::srgb(0.95, 0.68, 0.2);
23+const BTN: Color = Color::srgba(0.27, 0.29, 0.21, 0.95);
24+const BTN_HOVER: Color = Color::srgba(0.35, 0.37, 0.27, 0.98);
25+
26+/// Values the settings rows cycle through.
27+const RESOLUTIONS: [[u32; 2]; 4] = [[1280, 720], [1600, 900], [1920, 1080], [2560, 1440]];
28+const WINDOW_MODES: [WindowModeSetting; 3] = [
29+ WindowModeSetting::Windowed,
30+ WindowModeSetting::Borderless,
31+ WindowModeSetting::Fullscreen,
32+];
33+/// 0 is unlimited.
34+const FPS_STEPS: [u32; 5] = [30, 60, 120, 144, 0];
35+/// Text and UI size multipliers, on top of the window-height scale.
36+const TEXT_SIZES: [f32; 8] = [0.8, 0.9, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0];
37+
38+const HOW_TO_PLAY: [&str; 10] = [
39+ "Goal: keep the three front sectors (right) supplied with Ammo, Food and Troops.",
40+ "Home side: factories make Ammo, farms make Food, the capital and cities make Troops.",
41+ "Supplied fronts push the red line east. Lose if any sector is pushed back to its limit.",
42+ "Drag from one node to another to send its goods. Air raids can bomb track.",
43+ "Track is laid through stations on the way, and a train is bought.",
44+ "A train only carries what its stops load. Plan before you drag.",
45+ "Bombed track is orange, or red with a gap. Click it (wrench mark) to repair for $150.",
46+ "Cities go hungry without Food. Hungry cities slow war production everywhere.",
47+ "Wounded go to a city or the capital (hospital). Hospital trains carry only wounded.",
48+ "Space pauses, 1/2/3 set speed. Right-drag pans, wheel zooms. Esc opens menu. H or ? shows help.",
49+];
50+
51+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
52+pub enum MenuScreen {
53+ #[default]
54+ Main,
55+ Pause,
56+ Settings,
57+ HowToPlay,
58+}
59+
60+/// Which menu screen is open. `screen` is `None` while playing.
61+#[derive(Resource, Clone, Copy, Debug, Default, PartialEq, Eq)]
62+pub struct Menu {
63+ pub screen: Option<MenuScreen>,
64+ /// Where Settings and How to Play go back to.
65+ pub return_to: MenuScreen,
66+}
67+
68+impl Menu {
69+ pub fn is_open(&self) -> bool {
70+ self.screen.is_some()
71+ }
72+
73+ fn is_sub_screen(&self) -> bool {
74+ matches!(
75+ self.screen,
76+ Some(MenuScreen::Settings | MenuScreen::HowToPlay)
77+ )
78+ }
79+
80+ fn show(&mut self, next: MenuScreen) {
81+ if matches!(next, MenuScreen::Settings | MenuScreen::HowToPlay) && !self.is_sub_screen() {
82+ self.return_to = self.screen.unwrap_or(MenuScreen::Main);
83+ }
84+ self.screen = Some(next);
85+ }
86+
87+ /// Esc and Back: sub-screens return, the pause menu closes, the main menu stays.
88+ fn go_back(&mut self) {
89+ self.screen = match self.screen {
90+ Some(MenuScreen::Settings | MenuScreen::HowToPlay) => Some(self.return_to),
91+ Some(MenuScreen::Pause) => None,
92+ other => other,
93+ };
94+ }
95+}
96+
97+pub struct MenuPlugin;
98+
99+impl Plugin for MenuPlugin {
100+ fn build(&self, app: &mut App) {
101+ app.add_observer(on_menu_action)
102+ .add_systems(Startup, spawn_root)
103+ .add_systems(
104+ Update,
105+ (
106+ menu_escape,
107+ sync_pause.before(advance_clock),
108+ render_menu,
109+ update_menu_buttons,
110+ ),
111+ );
112+ }
113+}
114+
115+/// Esc: a menu open means back. Otherwise it cancels the current tool, or opens
116+/// the pause menu when the tool is already Inspect.
117+fn menu_escape(keys: Res<ButtonInput<KeyCode>>, mut menu: ResMut<Menu>, mut tool: ResMut<Tool>) {
118+ if !keys.just_pressed(KeyCode::Escape) {
119+ return;
120+ }
121+ if menu.is_open() {
122+ menu.go_back();
123+ } else if !matches!(*tool, Tool::Inspect) {
124+ *tool = Tool::Inspect;
125+ } else {
126+ menu.show(MenuScreen::Pause);
127+ }
128+}
129+
130+/// Holds the clock at speed 0 while a menu is open, and restores the speed when
131+/// it closes. A speed that was changed while paused (a restart sets 1x) is kept.
132+fn sync_pause(menu: Res<Menu>, mut clock: ResMut<SimClock>, mut saved: Local<Option<u32>>) {
133+ if menu.is_open() {
134+ if saved.is_none() {
135+ *saved = Some(clock.speed);
136+ }
137+ if clock.speed != 0 {
138+ clock.speed = 0;
139+ }
140+ } else if let Some(speed) = saved.take()
141+ && clock.speed == 0
142+ {
143+ clock.speed = speed;
144+ }
145+}
146+
147+#[derive(Component)]
148+struct MenuRoot;
149+
150+/// The panel inside the overlay. Its children are rebuilt for each screen.
151+#[derive(Component)]
152+struct MenuContent;
153+
154+/// What a menu button does when pressed.
155+#[derive(Component, Clone, Copy)]
156+enum MenuAction {
157+ NewOperation,
158+ Resume,
159+ Quit,
160+ Go(MenuScreen),
161+ Back,
162+ Step(Setting, i32),
163+}
164+
165+/// Settings rows, in the order they are shown.
166+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
167+enum Setting {
168+ Resolution,
169+ WindowMode,
170+ VSync,
171+ FpsLimit,
172+ ShowPerf,
173+ TextSize,
174+ Master,
175+ Effects,
176+ Ambient,
177+ Mute,
178+}
179+
180+fn spawn_root(mut commands: Commands) {
181+ commands.spawn((
182+ MenuRoot,
183+ Node {
184+ position_type: PositionType::Absolute,
185+ left: Val::Px(0.0),
186+ right: Val::Px(0.0),
187+ top: Val::Px(0.0),
188+ bottom: Val::Px(0.0),
189+ justify_content: JustifyContent::Center,
190+ align_items: AlignItems::Center,
191+ display: Display::None,
192+ ..default()
193+ },
194+ BackgroundColor(OVERLAY),
195+ GlobalZIndex(200),
196+ children![(
197+ MenuContent,
198+ Node {
199+ flex_direction: FlexDirection::Column,
200+ align_items: AlignItems::Center,
201+ row_gap: Val::Px(14.0),
202+ padding: UiRect::all(Val::Px(28.0)),
203+ border: UiRect::all(Val::Px(2.0)),
204+ ..default()
205+ },
206+ BackgroundColor(PANEL),
207+ BorderColor::all(AMBER),
208+ )],
209+ ));
210+}
211+
212+fn text(value: &str, size: f32, color: Color) -> impl Bundle {
213+ (
214+ Text::new(value),
215+ TextFont::from_font_size(size),
216+ TextColor(color),
217+ )
218+}
219+
220+fn menu_button(parent: &mut ChildSpawnerCommands, label: &str, width: f32, action: MenuAction) {
221+ parent
222+ .spawn((
223+ Button,
224+ Node {
225+ width: Val::Px(width),
226+ height: Val::Px(36.0),
227+ align_items: AlignItems::Center,
228+ justify_content: JustifyContent::Center,
229+ ..default()
230+ },
231+ BackgroundColor(BTN),
232+ Hovered::default(),
233+ action,
234+ ))
235+ .with_children(|b| {
236+ b.spawn(text(label, 18.0, PARCH));
237+ });
238+}
239+
240+/// Shows the overlay for the open screen and rebuilds its content when needed.
241+fn render_menu(
242+ mut commands: Commands,
243+ menu: Res<Menu>,
244+ settings: Res<Settings>,
245+ mut roots: Query<&mut Node, With<MenuRoot>>,
246+ contents: Query<Entity, With<MenuContent>>,
247+) {
248+ let target = if menu.is_open() {
249+ Display::Flex
250+ } else {
251+ Display::None
252+ };
253+ for mut node in &mut roots {
254+ if node.display != target {
255+ node.display = target;
256+ }
257+ }
258+ if !(menu.is_changed() || settings.is_changed()) {
259+ return;
260+ }
261+ let Ok(content) = contents.single() else {
262+ return;
263+ };
264+ let mut entity = commands.entity(content);
265+ entity.despawn_related::<Children>();
266+ let Some(screen) = menu.screen else {
267+ return;
268+ };
269+ entity.with_children(|p| match screen {
270+ MenuScreen::Main => main_screen(p),
271+ MenuScreen::Pause => pause_screen(p),
272+ MenuScreen::HowToPlay => how_to_play_screen(p),
273+ MenuScreen::Settings => settings_screen(p, &settings),
274+ });
275+}
276+
277+fn main_screen(p: &mut ChildSpawnerCommands) {
278+ p.spawn(text("IRON LIFELINE", 48.0, AMBER));
279+ p.spawn((text("Keep the front alive.", 20.0, PARCH), Node {
280+ margin: UiRect::bottom(Val::Px(12.0)),
281+ ..default()
282+ }));
283+ menu_button(p, "New Operation", 280.0, MenuAction::NewOperation);
284+ menu_button(p, "How to Play", 280.0, MenuAction::Go(MenuScreen::HowToPlay));
285+ menu_button(p, "Settings", 280.0, MenuAction::Go(MenuScreen::Settings));
286+ menu_button(p, "Quit", 280.0, MenuAction::Quit);
287+}
288+
289+fn pause_screen(p: &mut ChildSpawnerCommands) {
290+ p.spawn(text("PAUSED", 36.0, AMBER));
291+ menu_button(p, "Resume", 280.0, MenuAction::Resume);
292+ menu_button(p, "How to Play", 280.0, MenuAction::Go(MenuScreen::HowToPlay));
293+ menu_button(p, "Settings", 280.0, MenuAction::Go(MenuScreen::Settings));
294+ menu_button(p, "Main Menu", 280.0, MenuAction::Go(MenuScreen::Main));
295+ menu_button(p, "Quit", 280.0, MenuAction::Quit);
296+}
297+
298+fn how_to_play_screen(p: &mut ChildSpawnerCommands) {
299+ p.spawn(text("HOW TO PLAY", 30.0, AMBER));
300+ p.spawn(Node {
301+ flex_direction: FlexDirection::Column,
302+ row_gap: Val::Px(7.0),
303+ width: Val::Px(760.0),
304+ ..default()
305+ })
306+ .with_children(|lines| {
307+ for line in HOW_TO_PLAY {
308+ lines.spawn(text(line, 15.0, PARCH));
309+ }
310+ });
311+ menu_button(p, "Back", 280.0, MenuAction::Back);
312+}
313+
314+fn settings_screen(p: &mut ChildSpawnerCommands, settings: &Settings) {
315+ let d = &settings.display;
316+ let a = &settings.audio;
317+ p.spawn(text("SETTINGS", 30.0, AMBER));
318+ let rows = [
319+ ("Resolution", resolution_text(d.resolution), Setting::Resolution),
320+ ("Window mode", window_mode_text(d.window_mode), Setting::WindowMode),
321+ ("VSync", on_off(d.vsync), Setting::VSync),
322+ ("FPS limit", fps_text(d.fps_limit), Setting::FpsLimit),
323+ ("Show performance", on_off(d.show_performance), Setting::ShowPerf),
324+ ("Text size", percent(d.text_size), Setting::TextSize),
325+ ("Master volume", percent(a.master), Setting::Master),
326+ ("Effects volume", percent(a.effects), Setting::Effects),
327+ ("Ambient volume", percent(a.ambient), Setting::Ambient),
328+ ("Mute", on_off(a.muted), Setting::Mute),
329+ ];
330+ for (name, value, which) in rows {
331+ setting_row(p, name, &value, which);
332+ }
333+ menu_button(p, "Back", 280.0, MenuAction::Back);
334+}
335+
336+/// One settings line: name, [<] value [>].
337+fn setting_row(p: &mut ChildSpawnerCommands, name: &str, value: &str, which: Setting) {
338+ p.spawn(Node {
339+ width: Val::Px(520.0),
340+ justify_content: JustifyContent::SpaceBetween,
341+ align_items: AlignItems::Center,
342+ ..default()
343+ })
344+ .with_children(|r| {
345+ r.spawn((
346+ text(name, 17.0, PARCH),
347+ Node {
348+ width: Val::Px(210.0),
349+ ..default()
350+ },
351+ ));
352+ r.spawn(Node {
353+ align_items: AlignItems::Center,
354+ column_gap: Val::Px(8.0),
355+ ..default()
356+ })
357+ .with_children(|c| {
358+ menu_button(c, "<", 36.0, MenuAction::Step(which, -1));
359+ c.spawn((
360+ text(value, 17.0, AMBER),
361+ Node {
362+ width: Val::Px(180.0),
363+ justify_content: JustifyContent::Center,
364+ ..default()
365+ },
366+ ));
367+ menu_button(c, ">", 36.0, MenuAction::Step(which, 1));
368+ });
369+ });
370+}
371+
372+fn on_off(on: bool) -> String {
373+ if on { "On" } else { "Off" }.to_string()
374+}
375+
376+fn percent(v: f32) -> String {
377+ format!("{}%", (v * 100.0).round() as i32)
378+}
379+
380+fn resolution_text(r: [u32; 2]) -> String {
381+ format!("{}x{}", r[0], r[1])
382+}
383+
384+fn window_mode_text(mode: WindowModeSetting) -> String {
385+ match mode {
386+ WindowModeSetting::Windowed => "Windowed",
387+ WindowModeSetting::Borderless => "Borderless",
388+ WindowModeSetting::Fullscreen => "Fullscreen",
389+ }
390+ .to_string()
391+}
392+
393+fn fps_text(fps: u32) -> String {
394+ if fps == 0 {
395+ "Unlimited".to_string()
396+ } else {
397+ fps.to_string()
398+ }
399+}
400+
401+/// Position of `value` in `list`, or 0 when the file holds an unlisted value.
402+fn index_of<T: PartialEq>(list: &[T], value: &T) -> usize {
403+ list.iter().position(|v| v == value).unwrap_or(0)
404+}
405+
406+/// Moves one step through a list and stops at the ends.
407+fn step_index(index: usize, len: usize, dir: i32) -> usize {
408+ (index as i32 + dir).clamp(0, len as i32 - 1) as usize
409+}
410+
411+/// Volume moves in steps of 10%.
412+fn step_volume(v: f32, dir: i32) -> f32 {
413+ let tenths = (v * 10.0).round() as i32;
414+ (tenths + dir).clamp(0, 10) as f32 / 10.0
415+}
416+
417+fn step(settings: &mut Settings, which: Setting, dir: i32) {
418+ let d = &mut settings.display;
419+ let a = &mut settings.audio;
420+ match which {
421+ Setting::Resolution => {
422+ let i = index_of(&RESOLUTIONS[..], &d.resolution);
423+ d.resolution = RESOLUTIONS[step_index(i, RESOLUTIONS.len(), dir)];
424+ }
425+ Setting::WindowMode => {
426+ let i = index_of(&WINDOW_MODES[..], &d.window_mode);
427+ d.window_mode = WINDOW_MODES[step_index(i, WINDOW_MODES.len(), dir)];
428+ }
429+ Setting::VSync => d.vsync = !d.vsync,
430+ Setting::FpsLimit => {
431+ let i = index_of(&FPS_STEPS[..], &d.fps_limit);
432+ d.fps_limit = FPS_STEPS[step_index(i, FPS_STEPS.len(), dir)];
433+ }
434+ Setting::ShowPerf => d.show_performance = !d.show_performance,
435+ Setting::TextSize => {
436+ let i = index_of(&TEXT_SIZES[..], &d.text_size);
437+ d.text_size = TEXT_SIZES[step_index(i, TEXT_SIZES.len(), dir)];
438+ }
439+ Setting::Master => a.master = step_volume(a.master, dir),
440+ Setting::Effects => a.effects = step_volume(a.effects, dir),
441+ Setting::Ambient => a.ambient = step_volume(a.ambient, dir),
442+ Setting::Mute => a.muted = !a.muted,
443+ }
444+}
445+
446+fn on_menu_action(
447+ ev: On<Activate>,
448+ actions: Query<&MenuAction>,
449+ mut menu: ResMut<Menu>,
450+ mut settings: ResMut<Settings>,
451+ mut exit: MessageWriter<AppExit>,
452+ mut commands: Commands,
453+) {
454+ let Ok(action) = actions.get(ev.entity) else {
455+ return;
456+ };
457+ match *action {
458+ MenuAction::NewOperation => {
459+ menu.screen = None;
460+ commands.queue(|world: &mut World| reset_game(world));
461+ }
462+ MenuAction::Resume => menu.screen = None,
463+ MenuAction::Quit => {
464+ exit.write(AppExit::Success);
465+ }
466+ MenuAction::Go(screen) => menu.show(screen),
467+ MenuAction::Back => menu.go_back(),
468+ MenuAction::Step(which, dir) => {
469+ // Compare on a copy so an unchanged value does not mark the resource changed.
470+ let mut next = settings.clone();
471+ step(&mut next, which, dir);
472+ if next != *settings {
473+ *settings = next;
474+ settings::save(&settings);
475+ }
476+ }
477+ }
478+}
479+
480+fn update_menu_buttons(mut buttons: Query<(&Hovered, &mut BackgroundColor), With<MenuAction>>) {
481+ for (hovered, mut bg) in &mut buttons {
482+ let target = if hovered.get() { BTN_HOVER } else { BTN };
483+ if bg.0 != target {
484+ bg.0 = target;
485+ }
486+ }
487+}
src/model.rsadded+620 -0
@@ -0,0 +1,620 @@
1+//! Shared types for Iron Lifeline. Every other module builds on these.
2+
3+use bevy::prelude::{Component, Message, Resource, Vec2};
4+
5+/// Marks a UI node (and its descendants) that never blocks map clicks, such as tooltips.
6+#[derive(Component, Default, Clone, Copy)]
7+pub struct UiPassThrough;
8+
9+/// Index into `Network::nodes`.
10+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11+pub struct NodeId(pub usize);
12+
13+/// Goods moved over the network. Index order matches `Node::stock`.
14+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15+pub enum Good {
16+ Ammo,
17+ Food,
18+ Troops,
19+ Wounded,
20+}
21+
22+pub const GOODS: [Good; 4] = [Good::Ammo, Good::Food, Good::Troops, Good::Wounded];
23+
24+impl Good {
25+ pub fn idx(self) -> usize {
26+ match self {
27+ Good::Ammo => 0,
28+ Good::Food => 1,
29+ Good::Troops => 2,
30+ Good::Wounded => 3,
31+ }
32+ }
33+
34+ pub fn name(self) -> &'static str {
35+ match self {
36+ Good::Ammo => "Ammo",
37+ Good::Food => "Food",
38+ Good::Troops => "Troops",
39+ Good::Wounded => "Wounded",
40+ }
41+ }
42+}
43+
44+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45+pub enum NodeKind {
46+ Capital,
47+ City,
48+ Factory,
49+ Farm,
50+ Depot,
51+ Front,
52+}
53+
54+impl NodeKind {
55+ pub fn name(self) -> &'static str {
56+ match self {
57+ NodeKind::Capital => "Capital",
58+ NodeKind::City => "City",
59+ NodeKind::Factory => "Factory",
60+ NodeKind::Farm => "Farm",
61+ NodeKind::Depot => "Depot",
62+ NodeKind::Front => "Front",
63+ }
64+ }
65+
66+ pub fn accepts(self, g: Good) -> bool {
67+ match self {
68+ NodeKind::Front => matches!(g, Good::Ammo | Good::Food | Good::Troops),
69+ NodeKind::Capital | NodeKind::City => matches!(g, Good::Food | Good::Wounded),
70+ NodeKind::Depot => true,
71+ NodeKind::Factory | NodeKind::Farm => false,
72+ }
73+ }
74+
75+ /// What the node produces, in words, for tooltips.
76+ pub fn makes_text(self) -> &'static str {
77+ match self {
78+ NodeKind::Capital | NodeKind::City => "Troops",
79+ NodeKind::Factory => "Ammo",
80+ NodeKind::Farm => "Food",
81+ NodeKind::Depot | NodeKind::Front => "nothing",
82+ }
83+ }
84+}
85+
86+#[derive(Debug, Clone, Copy, PartialEq)]
87+pub struct FrontState {
88+ /// -1 collapse .. +1 breakthrough. Starts at 0.
89+ pub line: f32,
90+ /// 0..1 recent supply ratio.
91+ pub supply: f32,
92+}
93+
94+/// A building under threat, being railed to the rear one crate at a time.
95+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96+pub struct Evac {
97+ /// Game hours until the building is overrun.
98+ pub hours_left: u32,
99+ /// Crates still on site, not yet loaded.
100+ pub crates_left: u32,
101+ /// Where the crates go. Set by the first drag.
102+ pub dest: Option<NodeId>,
103+ /// Crates that have arrived at `dest`.
104+ pub delivered: u32,
105+ /// Index of the front sector threatening the building.
106+ pub threat: usize,
107+}
108+
109+#[derive(Debug, Clone)]
110+pub struct Node {
111+ pub name: String,
112+ pub kind: NodeKind,
113+ pub pos: Vec2,
114+ /// Indexed by `Good::idx()`: [ammo, food, troops, wounded].
115+ pub stock: [f32; 4],
116+ pub front: Option<FrontState>,
117+ /// 0..1, cities only.
118+ pub hunger: f32,
119+ /// Production multiplier. 1.0 unless the site lost crates in an evacuation.
120+ pub output: f32,
121+ /// Overrun by the enemy: produces nothing and its rail is cut.
122+ pub captured: bool,
123+ pub evac: Option<Evac>,
124+}
125+
126+#[derive(Debug, Clone, Copy, PartialEq)]
127+pub struct TrackSeg {
128+ pub a: NodeId,
129+ pub b: NodeId,
130+ pub length: f32,
131+ /// 0..1; below `MIN_USABLE_CONDITION` the track is blocked.
132+ pub condition: f32,
133+}
134+
135+/// Tracks with condition below this value are blocked.
136+pub const MIN_USABLE_CONDITION: f32 = 0.3;
137+/// Tracks with condition below this value slow trains to half speed.
138+pub const SLOW_CONDITION: f32 = 0.7;
139+
140+/// Speed multiplier for a train on track of the given condition.
141+pub fn speed_factor(condition: f32) -> f32 {
142+ if condition < SLOW_CONDITION { 0.5 } else { 1.0 }
143+}
144+
145+#[derive(Resource, Debug, Clone)]
146+pub struct Network {
147+ pub nodes: Vec<Node>,
148+ pub tracks: Vec<TrackSeg>,
149+}
150+
151+impl Network {
152+ /// Index of the track connecting `a` and `b` in either direction.
153+ pub fn track_between(&self, a: NodeId, b: NodeId) -> Option<usize> {
154+ self.tracks
155+ .iter()
156+ .position(|t| (t.a == a && t.b == b) || (t.a == b && t.b == a))
157+ }
158+
159+ /// True when either end of the track is captured.
160+ pub fn is_cut(&self, t: &TrackSeg) -> bool {
161+ self.nodes[t.a.0].captured || self.nodes[t.b.0].captured
162+ }
163+
164+ /// Marks a node captured and breaks the track touching it.
165+ pub fn capture(&mut self, i: usize) {
166+ self.nodes[i].captured = true;
167+ for t in self.tracks.iter_mut() {
168+ if t.a.0 == i || t.b.0 == i {
169+ t.condition = 0.0;
170+ }
171+ }
172+ }
173+
174+ /// Adjacent nodes over usable tracks (condition >= 0.3), with track length.
175+ pub fn neighbors(&self, n: NodeId) -> Vec<(NodeId, f32)> {
176+ self.tracks
177+ .iter()
178+ .filter(|t| t.condition >= MIN_USABLE_CONDITION && !self.is_cut(t))
179+ .filter_map(|t| {
180+ if t.a == n {
181+ Some((t.b, t.length))
182+ } else if t.b == n {
183+ Some((t.a, t.length))
184+ } else {
185+ None
186+ }
187+ })
188+ .collect()
189+ }
190+
191+ /// Dijkstra over usable tracks. The returned path includes both endpoints.
192+ pub fn shortest_path(&self, from: NodeId, to: NodeId) -> Option<Vec<NodeId>> {
193+ let n = self.nodes.len();
194+ if from.0 >= n || to.0 >= n {
195+ return None;
196+ }
197+ let mut dist = vec![f32::INFINITY; n];
198+ let mut prev: Vec<Option<usize>> = vec![None; n];
199+ let mut done = vec![false; n];
200+ dist[from.0] = 0.0;
201+ loop {
202+ let mut cur: Option<usize> = None;
203+ for i in 0..n {
204+ if !done[i] && dist[i].is_finite() && cur.is_none_or(|c| dist[i] < dist[c]) {
205+ cur = Some(i);
206+ }
207+ }
208+ let Some(u) = cur else { break };
209+ if u == to.0 {
210+ break;
211+ }
212+ done[u] = true;
213+ for (v, w) in self.neighbors(NodeId(u)) {
214+ let alt = dist[u] + w;
215+ if alt < dist[v.0] {
216+ dist[v.0] = alt;
217+ prev[v.0] = Some(u);
218+ }
219+ }
220+ }
221+ if !dist[to.0].is_finite() {
222+ return None;
223+ }
224+ let mut path = vec![to];
225+ let mut c = to.0;
226+ while let Some(p) = prev[c] {
227+ path.push(NodeId(p));
228+ c = p;
229+ }
230+ path.reverse();
231+ Some(path)
232+ }
233+
234+ /// Nearest node within `radius` of `pos`.
235+ pub fn node_at(&self, pos: Vec2, radius: f32) -> Option<NodeId> {
236+ self.nodes
237+ .iter()
238+ .enumerate()
239+ .map(|(i, n)| (i, n.pos.distance(pos)))
240+ .filter(|(_, d)| *d <= radius)
241+ .min_by(|a, b| a.1.total_cmp(&b.1))
242+ .map(|(i, _)| NodeId(i))
243+ }
244+}
245+
246+pub fn node(name: &str, kind: NodeKind, x: f32, y: f32, stock: [f32; 4]) -> Node {
247+ let front = (kind == NodeKind::Front).then_some(FrontState {
248+ line: 0.0,
249+ supply: 0.7,
250+ });
251+ Node {
252+ name: name.to_string(),
253+ kind,
254+ pos: Vec2::new(x, y),
255+ stock,
256+ front,
257+ hunger: 0.0,
258+ output: 1.0,
259+ captured: false,
260+ evac: None,
261+ }
262+}
263+
264+impl Default for Network {
265+ /// The operation map. World coordinates, roughly ±600 x ±340.
266+ /// Stock order: [ammo, food, troops, wounded].
267+ fn default() -> Self {
268+ let nodes = vec![
269+ node(
270+ "Varenholm",
271+ NodeKind::Capital,
272+ -500.0,
273+ 0.0,
274+ [0.0, 0.0, 10.0, 0.0],
275+ ), // 0
276+ node("Brenhollow", NodeKind::City, -340.0, 160.0, [0.0; 4]), // 1
277+ node("Kestrau", NodeKind::City, -340.0, -170.0, [0.0; 4]), // 2
278+ node(
279+ "Ostwerk",
280+ NodeKind::Factory,
281+ -470.0,
282+ 200.0,
283+ [20.0, 0.0, 0.0, 0.0],
284+ ), // 3
285+ node("Vellin", NodeKind::Factory, -470.0, -200.0, [0.0; 4]), // 4
286+ node(
287+ "Lindach",
288+ NodeKind::Farm,
289+ -250.0,
290+ 110.0,
291+ [0.0, 20.0, 0.0, 0.0],
292+ ), // 5
293+ node("Sorvik", NodeKind::Farm, -250.0, -110.0, [0.0; 4]), // 6
294+ node("Feldau", NodeKind::Depot, 0.0, 60.0, [0.0; 4]), // 7
295+ node("Rhunen", NodeKind::Depot, 0.0, -80.0, [0.0; 4]), // 8
296+ node(
297+ "North Sector",
298+ NodeKind::Front,
299+ 500.0,
300+ 200.0,
301+ [40.0, 40.0, 10.0, 0.0],
302+ ), // 9
303+ node(
304+ "Centre Sector",
305+ NodeKind::Front,
306+ 510.0,
307+ 0.0,
308+ [40.0, 40.0, 10.0, 0.0],
309+ ), // 10
310+ node(
311+ "South Sector",
312+ NodeKind::Front,
313+ 500.0,
314+ -200.0,
315+ [40.0, 40.0, 10.0, 0.0],
316+ ), // 11
317+ node(
318+ "Dornmark",
319+ NodeKind::Factory,
320+ 280.0,
321+ 170.0,
322+ [12.0, 0.0, 0.0, 0.0],
323+ ), // 12, forward factory: first evacuation target
324+ node("Halvik", NodeKind::Farm, 280.0, -160.0, [0.0, 15.0, 0.0, 0.0]), // 13, forward farm
325+ ];
326+ let mut net = Network {
327+ nodes,
328+ tracks: Vec::new(),
329+ };
330+ // Starting line: Capital-Brenhollow, Capital-Ostwerk, and the rail
331+ // from the Capital through Feldau to Centre Sector.
332+ for (a, b) in [(0usize, 1usize), (0, 3), (0, 7), (7, 10)] {
333+ let length = net.nodes[a].pos.distance(net.nodes[b].pos);
334+ net.tracks.push(TrackSeg {
335+ a: NodeId(a),
336+ b: NodeId(b),
337+ length,
338+ condition: 1.0,
339+ });
340+ }
341+ net
342+ }
343+}
344+
345+/// Cargo units one freight car holds of its good.
346+pub const CAR_CAPACITY: f32 = 10.0;
347+/// Speed lost per car beyond the first, as a fraction of the locomotive's speed.
348+const CAR_SLOWDOWN: f32 = 0.05;
349+/// Slowest a train gets, however many cars it pulls.
350+const MIN_CAR_SPEED: f32 = 0.7;
351+
352+/// The locomotive that pulls a train's cars.
353+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354+pub enum LocoKind {
355+ Light,
356+ Heavy,
357+}
358+
359+impl LocoKind {
360+ /// World units per second at 1x.
361+ pub fn speed(self) -> f32 {
362+ match self {
363+ LocoKind::Light => 175.0,
364+ LocoKind::Heavy => 100.0,
365+ }
366+ }
367+
368+ /// Most cars this locomotive can pull.
369+ pub fn max_cars(self) -> usize {
370+ match self {
371+ LocoKind::Light => 3,
372+ LocoKind::Heavy => 6,
373+ }
374+ }
375+
376+ pub fn cost(self) -> i64 {
377+ match self {
378+ LocoKind::Light => 600,
379+ LocoKind::Heavy => 1400,
380+ }
381+ }
382+
383+ pub fn upkeep_per_week(self) -> i64 {
384+ match self {
385+ LocoKind::Light => 50,
386+ LocoKind::Heavy => 120,
387+ }
388+ }
389+
390+ pub fn name(self) -> &'static str {
391+ match self {
392+ LocoKind::Light => "Light",
393+ LocoKind::Heavy => "Heavy",
394+ }
395+ }
396+}
397+
398+/// One car type. The first four carry one good each; `Flat` carries one evacuation crate.
399+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
400+pub enum CarKind {
401+ Ammo,
402+ Food,
403+ Troop,
404+ Hospital,
405+ Flat,
406+}
407+
408+impl CarKind {
409+ /// Every car type, in the order the HUD shows them.
410+ pub const ALL: [CarKind; 5] = [
411+ CarKind::Ammo,
412+ CarKind::Food,
413+ CarKind::Troop,
414+ CarKind::Hospital,
415+ CarKind::Flat,
416+ ];
417+
418+ /// The good this car carries, if any.
419+ pub fn good(self) -> Option<Good> {
420+ match self {
421+ CarKind::Ammo => Some(Good::Ammo),
422+ CarKind::Food => Some(Good::Food),
423+ CarKind::Troop => Some(Good::Troops),
424+ CarKind::Hospital => Some(Good::Wounded),
425+ CarKind::Flat => None,
426+ }
427+ }
428+
429+ pub fn cost(self) -> i64 {
430+ 100
431+ }
432+
433+ pub fn upkeep_per_week(self) -> i64 {
434+ 10
435+ }
436+
437+ /// Short label for HUD buttons and tooltips.
438+ pub fn name(self) -> &'static str {
439+ match self {
440+ CarKind::Ammo => "Ammo",
441+ CarKind::Food => "Food",
442+ CarKind::Troop => "Troop",
443+ CarKind::Hospital => "Hospital",
444+ CarKind::Flat => "Flat",
445+ }
446+ }
447+}
448+
449+/// Price of a locomotive pulling `cars`.
450+pub fn consist_cost(loco: LocoKind, cars: &[CarKind]) -> i64 {
451+ loco.cost() + cars.iter().map(|c| c.cost()).sum::<i64>()
452+}
453+
454+/// One ordered stop on a route. `load[g.idx()]` means load that good here.
455+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456+pub struct Stop {
457+ pub node: NodeId,
458+ pub load: [bool; 4],
459+}
460+
461+#[derive(Component, Debug, Clone, PartialEq)]
462+pub struct Train {
463+ pub loco: LocoKind,
464+ /// Freight cars behind the locomotive, front to back.
465+ pub cars: Vec<CarKind>,
466+ pub route: Vec<Stop>,
467+ pub stop_idx: usize,
468+ /// Node the train is currently at (or last left).
469+ pub at: NodeId,
470+ /// Remaining nodes to the next stop, excluding `at`.
471+ pub path: Vec<NodeId>,
472+ /// 0..1 along the current segment.
473+ pub progress: f32,
474+ /// [ammo, food, troops, wounded].
475+ pub cargo: [f32; 4],
476+ /// Seconds left loading.
477+ pub dwell: f32,
478+ /// True when no path to the next stop exists.
479+ pub stalled: bool,
480+ /// Crates aboard, carried by the Flat cars.
481+ pub crates: u32,
482+}
483+
484+impl Train {
485+ /// Cargo units the train can hold of `g`: one car's worth per car carrying it.
486+ pub fn capacity(&self, g: Good) -> f32 {
487+ CAR_CAPACITY * self.cars.iter().filter(|c| c.good() == Some(g)).count() as f32
488+ }
489+
490+ pub fn can_carry(&self, g: Good) -> bool {
491+ self.capacity(g) > 0.0
492+ }
493+
494+ /// Crates the train can hold: one per Flat car.
495+ pub fn crate_slots(&self) -> u32 {
496+ self.cars.iter().filter(|c| **c == CarKind::Flat).count() as u32
497+ }
498+
499+ /// World units per second at 1x: the locomotive's speed, less a little per car past the first.
500+ pub fn speed(&self) -> f32 {
501+ let extra = self.cars.len().saturating_sub(1) as f32;
502+ self.loco.speed() * (1.0 - CAR_SLOWDOWN * extra).max(MIN_CAR_SPEED)
503+ }
504+
505+ pub fn upkeep_per_week(&self) -> i64 {
506+ self.loco.upkeep_per_week() + self.cars.iter().map(|c| c.upkeep_per_week()).sum::<i64>()
507+ }
508+}
509+
510+#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq)]
511+pub struct Treasury(pub i64);
512+
513+impl Default for Treasury {
514+ fn default() -> Self {
515+ Treasury(6000)
516+ }
517+}
518+
519+/// Real seconds per game hour at 1x.
520+pub const SECS_PER_HOUR: f32 = 0.5;
521+
522+#[derive(Resource, Debug, Clone, Copy, PartialEq)]
523+pub struct SimClock {
524+ /// Total elapsed game hours.
525+ pub hour: u32,
526+ /// 0 = paused, 1, 2 or 4.
527+ pub speed: u32,
528+ /// Real-time accumulator in seconds.
529+ pub acc: f32,
530+}
531+
532+impl Default for SimClock {
533+ fn default() -> Self {
534+ SimClock {
535+ hour: 0,
536+ speed: 1,
537+ acc: 0.0,
538+ }
539+ }
540+}
541+
542+impl SimClock {
543+ /// Elapsed whole game days.
544+ pub fn day(&self) -> u32 {
545+ self.hour / 24
546+ }
547+
548+ /// Elapsed whole game weeks.
549+ pub fn week(&self) -> u32 {
550+ self.hour / (24 * 7)
551+ }
552+}
553+
554+#[derive(Resource, Debug, Clone, Default, PartialEq)]
555+pub enum Tool {
556+ #[default]
557+ Inspect,
558+ BuildTrack {
559+ from: Option<NodeId>,
560+ },
561+ NewRoute {
562+ loco: LocoKind,
563+ cars: Vec<CarKind>,
564+ stops: Vec<Stop>,
565+ },
566+ Repair,
567+}
568+
569+#[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)]
570+pub struct Selected(pub Option<NodeId>);
571+
572+#[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)]
573+pub enum Outcome {
574+ #[default]
575+ Ongoing,
576+ Victory,
577+ Defeat,
578+}
579+
580+#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
581+pub struct NodeClicked(pub NodeId);
582+
583+#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
584+pub struct TrackClicked(pub usize);
585+
586+/// Sent once per game hour by the economy.
587+#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
588+pub struct HourTick;
589+
590+/// News and log lines shown by the HUD.
591+#[derive(Message, Debug, Clone, PartialEq, Eq)]
592+pub struct Notify(pub String);
593+
594+pub const TRACK_COST_PER_UNIT: i64 = 2;
595+pub const REPAIR_COST: i64 = 150;
596+
597+/// "Ammo 20, Food 0, Troops 5, Wounded 0", whole numbers, every good listed.
598+pub fn stock_text(v: &[f32; 4]) -> String {
599+ GOODS
600+ .iter()
601+ .map(|g| format!("{} {:.0}", g.name(), v[g.idx()]))
602+ .collect::<Vec<_>>()
603+ .join(", ")
604+}
605+
606+#[cfg(test)]
607+mod tests {
608+ use super::*;
609+
610+ #[test]
611+ fn shortest_path_factory_to_centre_via_capital_and_feldau() {
612+ let net = Network::default();
613+ // Ostwerk (3) -> Varenholm (0) -> Feldau (7) -> Centre Sector (10).
614+ let path = net.shortest_path(NodeId(3), NodeId(10));
615+ assert_eq!(
616+ path,
617+ Some(vec![NodeId(3), NodeId(0), NodeId(7), NodeId(10)])
618+ );
619+ }
620+}
src/routes.rsadded+300 -0
@@ -0,0 +1,300 @@
1+//! Route building for the demo script, and the two supply line actions the HUD
2+//! chips use: add a train to a line, and scrap one train. Supply lines are made
3+//! by dragging between nodes (see `supply.rs`).
4+
5+use bevy::ecs::system::SystemParam;
6+use bevy::prelude::*;
7+use bevy::ui_widgets::Activate;
8+
9+use crate::audio::SoundEvent;
10+use crate::map::{WorldText, dashed};
11+use crate::model::{
12+ CarKind, GOODS, Good, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool, Train,
13+ Treasury, consist_cost,
14+};
15+use crate::supply::{buy_line, money, produces};
16+
17+pub struct RoutesPlugin;
18+
19+impl Plugin for RoutesPlugin {
20+ fn build(&self, app: &mut App) {
21+ app.add_systems(
22+ Update,
23+ (on_node_clicked, sync_route_labels, draw_route_preview),
24+ )
25+ .add_observer(on_scrap)
26+ .add_observer(on_add_train)
27+ .add_observer(on_remove_car)
28+ .add_observer(on_add_car);
29+ }
30+}
31+
32+/// Route preview dash and gap lengths, in world units.
33+const DASH_LEN: f32 = 10.0;
34+const GAP_LEN: f32 = 6.0;
35+/// Stop number glyph size in world units (see `map::WorldText`).
36+const STOP_LABEL_SIZE: f32 = 16.0;
37+
38+fn ink() -> Color {
39+ Color::srgb(0.15, 0.12, 0.08)
40+}
41+fn amber() -> Color {
42+ Color::srgb(1.0, 0.75, 0.2)
43+}
44+fn red() -> Color {
45+ Color::srgb(0.9, 0.15, 0.1)
46+}
47+
48+/// Removes a supply line's train from the map, refunding half its price.
49+/// Put on a HUD chip button.
50+#[derive(Component, Debug, Clone, Copy)]
51+pub(crate) struct Scrap(pub Entity);
52+
53+/// Buys one more train for the supply line between two nodes, as a second drag would.
54+/// Put on a HUD chip button.
55+#[derive(Component, Debug, Clone, Copy)]
56+pub(crate) struct AddTrain {
57+ pub from: NodeId,
58+ pub to: NodeId,
59+}
60+
61+/// Removes car `index` from a train when its car icon is pressed in the HUD.
62+/// Put on a HUD car icon button. Refunds half the car's price.
63+#[derive(Component, Debug, Clone, Copy)]
64+pub(crate) struct RemoveCar {
65+ pub entity: Entity,
66+ pub index: usize,
67+}
68+
69+/// Appends a car to a train when its car-type button is pressed in the HUD.
70+/// Put on a HUD car-type button.
71+#[derive(Component, Debug, Clone, Copy)]
72+pub(crate) struct AddCar {
73+ pub entity: Entity,
74+ pub car: CarKind,
75+}
76+
77+/// Numbered world-space marker for a stop of the route being built.
78+#[derive(Component)]
79+struct RouteLabel;
80+
81+#[derive(SystemParam)]
82+struct ScrapParams<'w, 's> {
83+ commands: Commands<'w, 's>,
84+ treasury: ResMut<'w, Treasury>,
85+ trains: Query<'w, 's, &'static Train>,
86+ notify: MessageWriter<'w, Notify>,
87+}
88+
89+#[derive(SystemParam)]
90+struct CarParams<'w, 's> {
91+ net: Res<'w, Network>,
92+ treasury: ResMut<'w, Treasury>,
93+ trains: Query<'w, 's, &'static mut Train>,
94+ notify: MessageWriter<'w, Notify>,
95+}
96+
97+/// Default load flags for a stop, by node kind, filtered by the goods the cars carry.
98+fn default_load(cars: &[CarKind], node: NodeKind) -> [bool; 4] {
99+ let wanted = match node {
100+ NodeKind::Factory => [true, false, false, false],
101+ NodeKind::Farm => [false, true, false, false],
102+ NodeKind::Capital | NodeKind::City => [false, false, true, false],
103+ NodeKind::Front => [false, false, false, true],
104+ NodeKind::Depot => [true, true, true, false],
105+ };
106+ let mut load = [false; 4];
107+ for g in GOODS {
108+ load[g.idx()] = wanted[g.idx()] && cars.iter().any(|c| c.good() == Some(g));
109+ }
110+ load
111+}
112+
113+/// The good a train carries, read from the loads of its first stop.
114+pub(crate) fn cargo_good(train: &Train) -> Option<Good> {
115+ let first = train.route.first()?;
116+ GOODS.into_iter().find(|g| first.load[g.idx()])
117+}
118+
119+/// Adds the clicked node as a stop while a route is being built (demo script).
120+fn on_node_clicked(
121+ mut clicks: MessageReader<NodeClicked>,
122+ mut tool: ResMut<Tool>,
123+ network: Res<Network>,
124+) {
125+ if !matches!(*tool, Tool::NewRoute { .. }) {
126+ return;
127+ }
128+ for NodeClicked(node) in clicks.read() {
129+ let Some(info) = network.nodes.get(node.0) else {
130+ continue;
131+ };
132+ let Tool::NewRoute { cars, stops, .. } = &mut *tool else {
133+ continue;
134+ };
135+ if stops.last().is_some_and(|s| s.node == *node) {
136+ continue;
137+ }
138+ stops.push(Stop {
139+ node: *node,
140+ load: default_load(cars, info.kind),
141+ });
142+ }
143+}
144+
145+/// Scraps a train when its [✕] chip button is pressed.
146+fn on_scrap(ev: On<Activate>, scraps: Query<&Scrap>, mut p: ScrapParams<'_, '_>) {
147+ let Ok(Scrap(entity)) = scraps.get(ev.entity) else {
148+ return;
149+ };
150+ let entity = *entity;
151+ let Ok(train) = p.trains.get(entity) else {
152+ return;
153+ };
154+ let loco = train.loco;
155+ let refund = consist_cost(loco, &train.cars) / 2;
156+ p.treasury.0 += refund;
157+ p.commands.entity(entity).despawn();
158+ p.notify.write(Notify(format!(
159+ "{} train scrapped, ${refund} refunded",
160+ loco.name()
161+ )));
162+}
163+
164+/// Takes one car off a train when its car icon is pressed. Refunds half its price.
165+fn on_remove_car(ev: On<Activate>, removes: Query<&RemoveCar>, mut p: CarParams) {
166+ let Ok(&RemoveCar { entity, index }) = removes.get(ev.entity) else {
167+ return;
168+ };
169+ let Ok(mut train) = p.trains.get_mut(entity) else {
170+ return;
171+ };
172+ if index >= train.cars.len() {
173+ return;
174+ }
175+ let car = train.cars.remove(index);
176+ let refund = car.cost() / 2;
177+ p.treasury.0 += refund;
178+ p.notify.write(Notify(format!(
179+ "{} car removed, ${refund} refunded",
180+ car.name()
181+ )));
182+}
183+
184+/// Couples a car of the chosen type onto the end of a train, if the locomotive has room
185+/// and the treasury can pay. A car of a good also turns on loading of that good at the
186+/// first stop that makes it or has it in stock, so the new car fills.
187+fn on_add_car(ev: On<Activate>, adds: Query<&AddCar>, mut p: CarParams) {
188+ let Ok(&AddCar { entity, car }) = adds.get(ev.entity) else {
189+ return;
190+ };
191+ let Ok(mut train) = p.trains.get_mut(entity) else {
192+ return;
193+ };
194+ if train.cars.len() >= train.loco.max_cars() {
195+ p.notify.write(Notify(format!("{} is full", train.loco.name())));
196+ return;
197+ }
198+ if car.cost() > p.treasury.0 {
199+ p.notify.write(Notify(format!("Need {}", money(car.cost()))));
200+ return;
201+ }
202+ p.treasury.0 -= car.cost();
203+ train.cars.push(car);
204+ if let Some(good) = car.good() {
205+ let net = &p.net;
206+ let source = train.route.iter_mut().find(|s| {
207+ let node = &net.nodes[s.node.0];
208+ produces(node.kind) == Some(good) || node.stock[good.idx()] > 0.0
209+ });
210+ if let Some(stop) = source {
211+ stop.load[good.idx()] = true;
212+ }
213+ }
214+ p.notify.write(Notify(format!("{} car added", car.name())));
215+}
216+
217+/// Adds a train to an existing line when its [+] chip button is pressed.
218+/// Same checks and charges as a drag from `from` to `to` (see `supply::plan`).
219+fn on_add_train(
220+ ev: On<Activate>,
221+ adds: Query<&AddTrain>,
222+ mut net: ResMut<Network>,
223+ mut treasury: ResMut<Treasury>,
224+ mut commands: Commands,
225+ mut notify: MessageWriter<Notify>,
226+ mut sounds: MessageWriter<SoundEvent>,
227+) {
228+ let Ok(&AddTrain { from, to }) = adds.get(ev.entity) else {
229+ return;
230+ };
231+ buy_line(
232+ &mut net,
233+ &mut treasury,
234+ &mut commands,
235+ &mut notify,
236+ &mut sounds,
237+ from,
238+ to,
239+ );
240+}
241+
242+/// Keeps one numbered marker per stop of the route being built.
243+fn sync_route_labels(
244+ mut commands: Commands,
245+ tool: Res<Tool>,
246+ network: Res<Network>,
247+ old: Query<Entity, With<RouteLabel>>,
248+) {
249+ if !tool.is_changed() {
250+ return;
251+ }
252+ for e in &old {
253+ commands.entity(e).despawn();
254+ }
255+ let Tool::NewRoute { stops, .. } = tool.as_ref() else {
256+ return;
257+ };
258+ for (i, stop) in stops.iter().enumerate() {
259+ let Some(node) = network.nodes.get(stop.node.0) else {
260+ continue;
261+ };
262+ commands.spawn((
263+ RouteLabel,
264+ Text2d::new(format!("{}", i + 1)),
265+ WorldText {
266+ size: STOP_LABEL_SIZE,
267+ },
268+ TextColor(ink()),
269+ Transform::from_xyz(node.pos.x, node.pos.y, 10.0),
270+ ));
271+ }
272+}
273+
274+/// Draws the route being built: amber dashed path per leg (red if no path), and stop rings.
275+fn draw_route_preview(mut gizmos: Gizmos, tool: Res<Tool>, network: Res<Network>) {
276+ let Tool::NewRoute { stops, .. } = tool.as_ref() else {
277+ return;
278+ };
279+ for stop in stops {
280+ if let Some(node) = network.nodes.get(stop.node.0) {
281+ gizmos.circle_2d(node.pos, 16.0, amber());
282+ }
283+ }
284+ for pair in stops.windows(2) {
285+ let (a, b) = (pair[0].node, pair[1].node);
286+ let (Some(na), Some(nb)) = (network.nodes.get(a.0), network.nodes.get(b.0)) else {
287+ continue;
288+ };
289+ match network.shortest_path(a, b) {
290+ Some(path) => {
291+ for leg in path.windows(2) {
292+ let p = network.nodes[leg[0].0].pos;
293+ let q = network.nodes[leg[1].0].pos;
294+ dashed(&mut gizmos, p, q, DASH_LEN, GAP_LEN, amber());
295+ }
296+ }
297+ None => dashed(&mut gizmos, na.pos, nb.pos, DASH_LEN, GAP_LEN, red()),
298+ }
299+ }
300+}
src/scenario.rsadded+254 -0
@@ -0,0 +1,254 @@
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+
14+use std::path::PathBuf;
15+
16+use bevy::app::AppExit;
17+use bevy::prelude::*;
18+use bevy::render::view::window::screenshot::{Screenshot, save_to_disk};
19+use bevy::time::{Real, Time};
20+
21+use crate::model::{
22+ CarKind, LocoKind, Network, NodeId, Selected, SimClock, Stop, TrackSeg, Train,
23+};
24+
25+/// Seconds between saved frames.
26+const RECORD_INTERVAL: f32 = 0.1;
27+
28+/// Command-line options. Unknown arguments are ignored.
29+#[derive(Default)]
30+pub 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+
39+impl 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+
58+fn 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+
66+fn 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+
74+fn 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.
91+fn 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)]
187+struct Stress(bool);
188+
189+/// Adds the fixed scenario network, trains and clock speed at startup.
190+pub struct ScenarioPlugin {
191+ pub stress: bool,
192+}
193+
194+impl 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)]
202+struct Recorder {
203+ dir: PathBuf,
204+ /// Real seconds since the last frame was saved.
205+ acc: f32,
206+ frame: u32,
207+}
208+
209+#[derive(Resource)]
210+struct QuitAfter(f32);
211+
212+/// Screenshot recording and timed exit. Added only when a flag asks for them.
213+#[derive(Default)]
214+pub struct CapturePlugin {
215+ pub record: Option<PathBuf>,
216+ pub quit_after: Option<f32>,
217+}
218+
219+impl 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+
237+fn 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+
250+fn 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+}
src/seasons.rsadded+383 -0
@@ -0,0 +1,383 @@
1+//! Seasons: a cycle of Spring, Summer, Autumn and Winter, two game weeks each. Each season
2+//! changes train speed, raid odds, food need and fog. The map tint, weather drawing and the
3+//! top-bar badge show the season without text walls.
4+
5+use bevy::prelude::*;
6+use bevy::time::{Real, Time};
7+
8+use crate::economy::{advance_clock, economy_tick};
9+use crate::front::front_hour_system;
10+use crate::map::unit_hash;
11+use crate::model::{Network, Notify, SimClock};
12+
13+/// Game hours per season: two game weeks.
14+const SEASON_HOURS: u32 = 24 * 14;
15+/// Hours a season change takes to blend the map tint in.
16+const BLEND_HOURS: f32 = 24.0;
17+/// Chance that an Autumn day is a fog day.
18+const FOG_CHANCE: f64 = 0.4;
19+/// Map frame size, matching `map::draw_background`.
20+const MAP_W: f32 = 1280.0;
21+const MAP_H: f32 = 720.0;
22+const SNOW_COUNT: u32 = 60;
23+const FOG_BANDS: u32 = 5;
24+const FOG_LEN: f32 = 320.0;
25+const FOG_HALF_H: f32 = 22.0;
26+
27+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28+pub enum Season {
29+ #[default]
30+ Spring,
31+ Summer,
32+ Autumn,
33+ Winter,
34+}
35+
36+impl Season {
37+ pub const ALL: [Season; 4] = [Season::Spring, Season::Summer, Season::Autumn, Season::Winter];
38+
39+ /// The season in force at `hour` game hours.
40+ pub fn from_hour(hour: u32) -> Season {
41+ Season::ALL[(hour / SEASON_HOURS) as usize % Season::ALL.len()]
42+ }
43+
44+ pub fn name(self) -> &'static str {
45+ match self {
46+ Season::Spring => "Spring",
47+ Season::Summer => "Summer",
48+ Season::Autumn => "Autumn",
49+ Season::Winter => "Winter",
50+ }
51+ }
52+
53+ /// Train speed multiplier: mud in Spring and Autumn, snow in Winter.
54+ pub fn speed_mult(self) -> f32 {
55+ match self {
56+ Season::Spring => 0.7,
57+ Season::Summer => 1.0,
58+ Season::Autumn | Season::Winter => 0.85,
59+ }
60+ }
61+
62+ /// Air raid chance multiplier: clear skies in Summer.
63+ pub fn raid_mult(self) -> f32 {
64+ match self {
65+ Season::Summer => 1.5,
66+ _ => 1.0,
67+ }
68+ }
69+
70+ /// Food need of front sectors and food eaten by cities: higher in Winter.
71+ pub fn food_mult(self) -> f32 {
72+ match self {
73+ Season::Winter => 1.5,
74+ _ => 1.0,
75+ }
76+ }
77+
78+ /// Seasons with mud on the tracks.
79+ pub fn is_muddy(self) -> bool {
80+ matches!(self, Season::Spring | Season::Autumn)
81+ }
82+
83+ /// Map background tint as RGBA; blended toward the next season over a game day.
84+ fn tint(self) -> [f32; 4] {
85+ match self {
86+ Season::Spring => [0.55, 0.70, 0.52, 0.22],
87+ Season::Summer => [0.98, 0.88, 0.62, 0.20],
88+ Season::Autumn => [0.66, 0.42, 0.18, 0.24],
89+ Season::Winter => [0.84, 0.91, 0.98, 0.40],
90+ }
91+ }
92+
93+ /// Colour of the top-bar badge.
94+ fn badge_color(self) -> Color {
95+ match self {
96+ Season::Spring => Color::srgb(0.55, 0.78, 0.45),
97+ Season::Summer => Color::srgb(0.95, 0.78, 0.35),
98+ Season::Autumn => Color::srgb(0.82, 0.48, 0.20),
99+ Season::Winter => Color::srgb(0.75, 0.88, 1.00),
100+ }
101+ }
102+
103+ /// News line sent when this season starts.
104+ fn change_text(self) -> &'static str {
105+ match self {
106+ Season::Spring => "Spring: mud slows trains",
107+ Season::Summer => "Summer: clear skies, raids up",
108+ Season::Autumn => "Autumn: mud and fog",
109+ Season::Winter => "Winter: food needs up",
110+ }
111+ }
112+}
113+
114+/// The operation's season. `season` is the one in force; `fog` is set on Autumn fog days,
115+/// when no air raids happen.
116+#[derive(Resource, Debug, Clone, Copy, Default)]
117+pub struct SeasonState {
118+ pub season: Season,
119+ /// Season before the current one, for the tint blend.
120+ previous: Season,
121+ /// Game hour the current season began.
122+ changed_at: u32,
123+ pub fog: bool,
124+ /// Game day the fog roll was made for.
125+ fog_day: u32,
126+}
127+
128+impl SeasonState {
129+ /// Map tint at `hour`: the previous season's tint fading into the current one.
130+ fn tint_color(&self, hour: u32) -> Color {
131+ let t = (hour.saturating_sub(self.changed_at) as f32 / BLEND_HOURS).min(1.0);
132+ let (a, b) = (self.previous.tint(), self.season.tint());
133+ let c = |i: usize| a[i] + (b[i] - a[i]) * t;
134+ Color::srgba(c(0), c(1), c(2), c(3))
135+ }
136+}
137+
138+pub struct SeasonsPlugin;
139+
140+impl Plugin for SeasonsPlugin {
141+ fn build(&self, app: &mut App) {
142+ app.init_resource::<SeasonState>()
143+ .add_systems(Startup, spawn_tint)
144+ .add_systems(
145+ Update,
146+ (
147+ // Season and fog are settled before this hour's economy and raids run.
148+ season_system
149+ .after(advance_clock)
150+ .before(economy_tick)
151+ .before(front_hour_system),
152+ (update_tint, draw_weather, update_badge),
153+ ),
154+ );
155+ }
156+}
157+
158+/// Marks the full-map colour wash behind the drawn map.
159+#[derive(Component)]
160+struct MapTint;
161+
162+/// Top-bar season badge parts.
163+#[derive(Component)]
164+struct SeasonBadgeTint;
165+
166+#[derive(Component)]
167+struct SeasonLabel;
168+
169+#[derive(Component)]
170+struct SeasonProgress;
171+
172+fn spawn_tint(mut commands: Commands, state: Res<SeasonState>) {
173+ commands.spawn((
174+ MapTint,
175+ Sprite::from_color(state.tint_color(0), Vec2::new(MAP_W, MAP_H)),
176+ Transform::from_xyz(0.0, 0.0, -5.0),
177+ ));
178+}
179+
180+/// Adds the season badge to the top bar: a coloured swatch, the season word, and a bar
181+/// that fills as the season runs out.
182+pub fn spawn_badge(bar: &mut ChildSpawnerCommands) {
183+ bar.spawn(Node {
184+ flex_direction: FlexDirection::Column,
185+ row_gap: Val::Px(3.0),
186+ ..default()
187+ })
188+ .with_children(|col| {
189+ col.spawn(Node {
190+ flex_direction: FlexDirection::Row,
191+ align_items: AlignItems::Center,
192+ column_gap: Val::Px(6.0),
193+ ..default()
194+ })
195+ .with_children(|row| {
196+ row.spawn((
197+ SeasonBadgeTint,
198+ Node {
199+ width: Val::Px(10.0),
200+ height: Val::Px(10.0),
201+ ..default()
202+ },
203+ BackgroundColor(Color::WHITE),
204+ ));
205+ row.spawn((
206+ SeasonLabel,
207+ Text::new(""),
208+ TextFont {
209+ font_size: FontSize::Px(14.0),
210+ ..default()
211+ },
212+ TextColor(Color::srgb(0.92, 0.88, 0.76)),
213+ ));
214+ });
215+ col.spawn((
216+ Node {
217+ width: Val::Px(90.0),
218+ height: Val::Px(3.0),
219+ ..default()
220+ },
221+ BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.4)),
222+ ))
223+ .with_children(|track| {
224+ track.spawn((
225+ SeasonProgress,
226+ SeasonBadgeTint,
227+ Node {
228+ width: Val::Percent(0.0),
229+ height: Val::Percent(100.0),
230+ ..default()
231+ },
232+ BackgroundColor(Color::WHITE),
233+ ));
234+ });
235+ });
236+}
237+
238+/// Tracks the clock: switches season at each boundary (with one news line), and rolls the
239+/// fog once per game day in Autumn.
240+fn season_system(
241+ clock: Res<SimClock>,
242+ mut state: ResMut<SeasonState>,
243+ mut notify: MessageWriter<Notify>,
244+) {
245+ let now = Season::from_hour(clock.hour);
246+ if now != state.season {
247+ state.previous = state.season;
248+ state.season = now;
249+ state.changed_at = clock.hour;
250+ notify.write(Notify(now.change_text().to_string()));
251+ }
252+ if clock.day() != state.fog_day {
253+ state.fog_day = clock.day();
254+ state.fog = now == Season::Autumn && rand::random_bool(FOG_CHANCE);
255+ }
256+}
257+
258+fn update_tint(
259+ state: Res<SeasonState>,
260+ clock: Res<SimClock>,
261+ mut tints: Query<&mut Sprite, With<MapTint>>,
262+) {
263+ let color = state.tint_color(clock.hour);
264+ for mut sprite in &mut tints {
265+ if sprite.color != color {
266+ sprite.color = color;
267+ }
268+ }
269+}
270+
271+fn update_badge(
272+ state: Res<SeasonState>,
273+ clock: Res<SimClock>,
274+ mut label: Query<(&mut Text, &mut TextColor), With<SeasonLabel>>,
275+ mut tints: Query<&mut BackgroundColor, With<SeasonBadgeTint>>,
276+ mut progress: Query<&mut Node, With<SeasonProgress>>,
277+) {
278+ let color = state.season.badge_color();
279+ for (mut text, mut text_color) in &mut label {
280+ if text.0 != state.season.name() {
281+ text.0 = state.season.name().to_string();
282+ }
283+ text_color.0 = color;
284+ }
285+ for mut bg in &mut tints {
286+ bg.0 = color;
287+ }
288+ let done = (clock.hour % SEASON_HOURS) as f32 / SEASON_HOURS as f32;
289+ for mut node in &mut progress {
290+ node.width = Val::Percent(done * 100.0);
291+ }
292+}
293+
294+/// Snow, fog and mud drawn over the map.
295+fn draw_weather(
296+ mut gizmos: Gizmos,
297+ state: Res<SeasonState>,
298+ net: Res<Network>,
299+ time: Res<Time<Real>>,
300+) {
301+ let t = time.elapsed_secs();
302+ if state.season == Season::Winter {
303+ draw_snow(&mut gizmos, t);
304+ }
305+ if state.fog {
306+ draw_fog(&mut gizmos, t);
307+ }
308+ if state.season.is_muddy() {
309+ draw_mud(&mut gizmos, &net);
310+ }
311+}
312+
313+/// Slow falling specks, each swaying a little.
314+fn draw_snow(gizmos: &mut Gizmos, t: f32) {
315+ let color = Color::srgba(1.0, 1.0, 1.0, 0.85);
316+ for i in 0..SNOW_COUNT {
317+ let seed = i * 4;
318+ let x0 = unit_hash(seed) * MAP_W - MAP_W * 0.5;
319+ let speed = 10.0 + 12.0 * unit_hash(seed + 1);
320+ let fall = (unit_hash(seed + 2) * MAP_H + t * speed) % MAP_H;
321+ let x = x0 + (t * 0.8 + i as f32).sin() * 8.0;
322+ let y = MAP_H * 0.5 - fall;
323+ let radius = 1.5 + unit_hash(seed + 3);
324+ gizmos.circle_2d(Isometry2d::from_translation(Vec2::new(x, y)), radius, color);
325+ }
326+}
327+
328+/// Pale translucent bands drifting east across the map.
329+fn draw_fog(gizmos: &mut Gizmos, t: f32) {
330+ let color = Color::srgba(0.94, 0.94, 0.90, 0.07);
331+ for k in 0..FOG_BANDS {
332+ let seed = 500 + k * 4;
333+ let speed = 14.0 + 10.0 * unit_hash(seed);
334+ let start = (unit_hash(seed + 1) * MAP_W + t * speed) % MAP_W - MAP_W * 0.5;
335+ let (x0, x1) = (start.max(-MAP_W * 0.5), (start + FOG_LEN).min(MAP_W * 0.5));
336+ if x1 <= x0 {
337+ continue;
338+ }
339+ let y = (unit_hash(seed + 2) * MAP_H - MAP_H * 0.5) + (t * 0.3 + k as f32).sin() * 12.0;
340+ let mut dy = -FOG_HALF_H;
341+ while dy <= FOG_HALF_H {
342+ gizmos.line_2d(Vec2::new(x0, y + dy), Vec2::new(x1, y + dy), color);
343+ dy += 3.0;
344+ }
345+ }
346+}
347+
348+/// Brown mud dabs beside each track.
349+fn draw_mud(gizmos: &mut Gizmos, net: &Network) {
350+ let mud = Color::srgba(0.38, 0.25, 0.12, 0.45);
351+ for (i, track) in net.tracks.iter().enumerate() {
352+ let a = net.nodes[track.a.0].pos;
353+ let b = net.nodes[track.b.0].pos;
354+ let len = a.distance(b);
355+ if len <= 0.0 {
356+ continue;
357+ }
358+ let dir = (b - a) / len;
359+ let perp = Vec2::new(-dir.y, dir.x);
360+ for k in 0..3 {
361+ let seed = 900 + i as u32 * 16 + k * 4;
362+ let along = 0.2 + 0.6 * unit_hash(seed);
363+ let side = if unit_hash(seed + 1) < 0.5 { -1.0 } else { 1.0 };
364+ let c = a.lerp(b, along) + perp * side * 5.0;
365+ let half = 3.0 + 3.0 * unit_hash(seed + 2);
366+ gizmos.line_2d(c - dir * half, c + dir * half, mud);
367+ gizmos.line_2d(c - dir * half + perp, c + dir * half + perp, mud);
368+ }
369+ }
370+}
371+
372+#[cfg(test)]
373+mod tests {
374+ use super::*;
375+
376+ #[test]
377+ fn season_follows_two_week_cycle() {
378+ assert_eq!(Season::from_hour(0), Season::Spring);
379+ assert_eq!(Season::from_hour(SEASON_HOURS - 1), Season::Spring);
380+ assert_eq!(Season::from_hour(SEASON_HOURS), Season::Summer);
381+ assert_eq!(Season::from_hour(4 * SEASON_HOURS), Season::Spring);
382+ }
383+}
src/settings.rsadded+383 -0
@@ -0,0 +1,383 @@
1+//! Player settings, stored as `settings.toml` in the platform config directory.
2+//!
3+//! The settings drive the primary window, the FPS limit and the performance
4+//! overlay. The settings menu changes them through `save`.
5+
6+use std::fs;
7+use std::io::ErrorKind;
8+use std::path::{Path, PathBuf};
9+use std::time::{Duration, Instant};
10+
11+use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
12+use bevy::prelude::*;
13+use bevy::ui::{Display, UiScale};
14+use bevy::window::{MonitorSelection, PresentMode, PrimaryWindow, VideoModeSelection, WindowMode};
15+use serde::{Deserialize, Serialize};
16+
17+use crate::hud::TOP_H;
18+use crate::model::UiPassThrough;
19+
20+const PERF_TEXT: Color = Color::srgb(0.55, 0.52, 0.45);
21+/// Left of the [?] button at the right end of the top bar (14 px inset, ~34 px wide, 16 px gap).
22+const PERF_RIGHT: f32 = 64.0;
23+/// Smallest window side accepted from the file. Anything smaller is replaced by the default.
24+const MIN_SIDE: u32 = 320;
25+/// Window height at which the UI is drawn at scale 1.0. Layout and text are sized for it.
26+const UI_REFERENCE_HEIGHT: f32 = 720.0;
27+/// Limits on the UI scale, so tiny windows stay usable and huge ones stay sane.
28+const MIN_UI_SCALE: f32 = 0.75;
29+const MAX_UI_SCALE: f32 = 4.0;
30+/// Limits on the text size setting.
31+const MIN_TEXT_SIZE: f32 = 0.8;
32+const MAX_TEXT_SIZE: f32 = 2.0;
33+
34+#[derive(Resource, Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
35+#[serde(default)]
36+pub struct Settings {
37+ pub display: DisplaySettings,
38+ pub audio: AudioSettings,
39+}
40+
41+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
42+#[serde(default)]
43+pub struct DisplaySettings {
44+ /// Window size in logical pixels.
45+ pub resolution: [u32; 2],
46+ pub window_mode: WindowModeSetting,
47+ pub vsync: bool,
48+ /// Frames per second. 0 means unlimited.
49+ pub fps_limit: u32,
50+ pub show_performance: bool,
51+ /// Multiplier on all text and UI size, on top of the window-height scale.
52+ pub text_size: f32,
53+}
54+
55+impl Default for DisplaySettings {
56+ fn default() -> Self {
57+ DisplaySettings {
58+ resolution: [1280, 720],
59+ window_mode: WindowModeSetting::Windowed,
60+ vsync: true,
61+ fps_limit: 0,
62+ show_performance: false,
63+ text_size: 1.0,
64+ }
65+ }
66+}
67+
68+#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
69+#[serde(rename_all = "lowercase")]
70+pub enum WindowModeSetting {
71+ #[default]
72+ Windowed,
73+ Borderless,
74+ Fullscreen,
75+}
76+
77+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
78+#[serde(default)]
79+pub struct AudioSettings {
80+ /// 0..1 volume multipliers.
81+ pub master: f32,
82+ pub effects: f32,
83+ pub ambient: f32,
84+ pub muted: bool,
85+}
86+
87+impl Default for AudioSettings {
88+ fn default() -> Self {
89+ AudioSettings {
90+ master: 0.8,
91+ effects: 1.0,
92+ ambient: 0.6,
93+ muted: false,
94+ }
95+ }
96+}
97+
98+impl Settings {
99+ /// Replaces values the game cannot use with defaults or clamps them into range.
100+ fn sanitized(mut self) -> Self {
101+ let [w, h] = self.display.resolution;
102+ if w < MIN_SIDE || h < MIN_SIDE {
103+ self.display.resolution = DisplaySettings::default().resolution;
104+ }
105+ let text_size = self.display.text_size;
106+ self.display.text_size = if text_size.is_finite() {
107+ text_size.clamp(MIN_TEXT_SIZE, MAX_TEXT_SIZE)
108+ } else {
109+ DisplaySettings::default().text_size
110+ };
111+ let audio = &mut self.audio;
112+ audio.master = audio.master.clamp(0.0, 1.0);
113+ audio.effects = audio.effects.clamp(0.0, 1.0);
114+ audio.ambient = audio.ambient.clamp(0.0, 1.0);
115+ self
116+ }
117+}
118+
119+/// Where the settings file lives, e.g. `~/.config/iron_lifeline/settings.toml` on Linux.
120+pub fn settings_path() -> Option<PathBuf> {
121+ directories::ProjectDirs::from("", "", "iron_lifeline")
122+ .map(|dirs| dirs.config_dir().join("settings.toml"))
123+}
124+
125+/// Reads the settings file at startup.
126+///
127+/// A missing or broken file gives the defaults and writes a fresh file. The
128+/// returned warning, if any, is for the caller to log. This never panics.
129+pub fn load() -> (Settings, Option<String>) {
130+ let Some(path) = settings_path() else {
131+ return (
132+ Settings::default(),
133+ Some("no config directory found; settings will not be saved".to_string()),
134+ );
135+ };
136+ match fs::read_to_string(&path) {
137+ Ok(text) => match toml::from_str::<Settings>(&text) {
138+ Ok(settings) => (settings.sanitized(), None),
139+ Err(err) => {
140+ let defaults = Settings::default();
141+ let mut warning = format!(
142+ "settings file {} is broken ({err}); using defaults",
143+ path.display()
144+ );
145+ if let Err(write_err) = save_to(&path, &defaults) {
146+ warning = format!("{warning}; {write_err}");
147+ }
148+ (defaults, Some(warning))
149+ }
150+ },
151+ Err(err) if err.kind() == ErrorKind::NotFound => {
152+ let defaults = Settings::default();
153+ let warning = save_to(&path, &defaults).err();
154+ (defaults, warning)
155+ }
156+ Err(err) => (
157+ Settings::default(),
158+ Some(format!("cannot read {}: {err}", path.display())),
159+ ),
160+ }
161+}
162+
163+fn save_to(path: &Path, settings: &Settings) -> Result<(), String> {
164+ let text = toml::to_string_pretty(settings)
165+ .map_err(|err| format!("cannot encode settings: {err}"))?;
166+ if let Some(dir) = path.parent() {
167+ fs::create_dir_all(dir)
168+ .map_err(|err| format!("cannot create {}: {err}", dir.display()))?;
169+ }
170+ fs::write(path, text).map_err(|err| format!("cannot write {}: {err}", path.display()))
171+}
172+
173+/// Writes the settings file. A failure is logged and never fatal.
174+pub fn save(settings: &Settings) {
175+ let Some(path) = settings_path() else {
176+ return;
177+ };
178+ if let Err(err) = save_to(&path, settings) {
179+ warn!("{err}");
180+ }
181+}
182+
183+/// Applies display settings to a window: size, window mode and vsync.
184+pub fn configure_window(display: &DisplaySettings, window: &mut Window) {
185+ let [w, h] = display.resolution;
186+ window.resolution.set(w as f32, h as f32);
187+ window.mode = match display.window_mode {
188+ WindowModeSetting::Windowed => WindowMode::Windowed,
189+ WindowModeSetting::Borderless => {
190+ WindowMode::BorderlessFullscreen(MonitorSelection::Current)
191+ }
192+ WindowModeSetting::Fullscreen => WindowMode::Fullscreen(
193+ MonitorSelection::Current,
194+ VideoModeSelection::Current,
195+ ),
196+ };
197+ window.present_mode = if display.vsync {
198+ PresentMode::AutoVsync
199+ } else {
200+ PresentMode::AutoNoVsync
201+ };
202+}
203+
204+/// The primary window at startup, already sized and moded from the settings.
205+pub fn initial_window(display: &DisplaySettings) -> Window {
206+ let mut window = Window {
207+ title: "Iron Lifeline".into(),
208+ ..default()
209+ };
210+ configure_window(display, &mut window);
211+ // The window does not exist yet, so `Current` has no monitor to resolve; use the primary one.
212+ if let WindowMode::BorderlessFullscreen(_) | WindowMode::Fullscreen(..) = window.mode {
213+ window.mode = match display.window_mode {
214+ WindowModeSetting::Fullscreen => WindowMode::Fullscreen(
215+ MonitorSelection::Primary,
216+ VideoModeSelection::Current,
217+ ),
218+ _ => WindowMode::BorderlessFullscreen(MonitorSelection::Primary),
219+ };
220+ }
221+ window
222+}
223+
224+/// Settings-driven behaviour: window, FPS limit and the performance overlay.
225+pub struct SettingsPlugin {
226+ /// A problem found by `load`, logged once at startup.
227+ pub load_warning: Option<String>,
228+}
229+
230+impl Plugin for SettingsPlugin {
231+ fn build(&self, app: &mut App) {
232+ if !app.is_plugin_added::<FrameTimeDiagnosticsPlugin>() {
233+ app.add_plugins(FrameTimeDiagnosticsPlugin::default());
234+ }
235+ app.insert_resource(LoadWarning(self.load_warning.clone()))
236+ .init_resource::<FrameStart>()
237+ .add_systems(Startup, (report_load_warning, spawn_perf_overlay))
238+ .add_systems(First, mark_frame_start)
239+ .add_systems(Last, limit_fps)
240+ .add_systems(Update, (apply_window, update_ui_scale, update_perf_overlay));
241+ }
242+}
243+
244+#[derive(Resource)]
245+struct LoadWarning(Option<String>);
246+
247+fn report_load_warning(warning: Res<LoadWarning>) {
248+ if let Some(text) = &warning.0 {
249+ warn!("{text}");
250+ }
251+}
252+
253+fn apply_window(settings: Res<Settings>, mut windows: Query<&mut Window, With<PrimaryWindow>>) {
254+ if !settings.is_changed() {
255+ return;
256+ }
257+ for mut window in &mut windows {
258+ configure_window(&settings.display, &mut window);
259+ }
260+}
261+
262+/// Scales all UI with the window height and the text size setting.
263+///
264+/// At 720 px high the UI is drawn at 1.0, so the layout keeps its proportions
265+/// at any resolution. Runs every frame; it is a cheap comparison.
266+fn update_ui_scale(
267+ settings: Res<Settings>,
268+ windows: Query<&Window, With<PrimaryWindow>>,
269+ mut ui_scale: ResMut<UiScale>,
270+) {
271+ let Ok(window) = windows.single() else {
272+ return;
273+ };
274+ let target = (window.height() / UI_REFERENCE_HEIGHT * settings.display.text_size)
275+ .clamp(MIN_UI_SCALE, MAX_UI_SCALE);
276+ if ui_scale.0 != target {
277+ ui_scale.0 = target;
278+ }
279+}
280+
281+/// Start time of the current frame, taken at the top of `First`.
282+#[derive(Resource, Default)]
283+struct FrameStart(Option<Instant>);
284+
285+fn mark_frame_start(mut start: ResMut<FrameStart>) {
286+ start.0 = Some(Instant::now());
287+}
288+
289+/// Sleeps off the rest of the frame budget so frames take 1/fps seconds.
290+fn limit_fps(settings: Res<Settings>, start: Res<FrameStart>) {
291+ let fps = settings.display.fps_limit;
292+ if fps == 0 {
293+ return;
294+ }
295+ let Some(began) = start.0 else {
296+ return;
297+ };
298+ let budget = Duration::from_secs_f64(1.0 / f64::from(fps));
299+ let spent = began.elapsed();
300+ if spent < budget {
301+ std::thread::sleep(budget - spent);
302+ }
303+}
304+
305+#[derive(Component)]
306+struct PerfRoot;
307+
308+#[derive(Component)]
309+struct PerfText;
310+
311+/// Small dim text inside the top bar, left of the [?] button. Pass-through, so it never eats clicks.
312+fn spawn_perf_overlay(mut commands: Commands) {
313+ commands.spawn((
314+ PerfRoot,
315+ Node {
316+ position_type: PositionType::Absolute,
317+ top: Val::Px(0.0),
318+ height: Val::Px(TOP_H),
319+ right: Val::Px(PERF_RIGHT),
320+ align_items: AlignItems::Center,
321+ display: Display::None,
322+ ..default()
323+ },
324+ GlobalZIndex(5),
325+ UiPassThrough,
326+ children![(
327+ Text::new(""),
328+ TextFont::from_font_size(12.0),
329+ TextColor(PERF_TEXT),
330+ PerfText,
331+ )],
332+ ));
333+}
334+
335+fn update_perf_overlay(
336+ settings: Res<Settings>,
337+ diagnostics: Res<DiagnosticsStore>,
338+ mut roots: Query<&mut Node, With<PerfRoot>>,
339+ mut texts: Query<&mut Text, With<PerfText>>,
340+) {
341+ let show = settings.display.show_performance;
342+ let target = if show { Display::Flex } else { Display::None };
343+ for mut node in &mut roots {
344+ if node.display != target {
345+ node.display = target;
346+ }
347+ }
348+ if !show {
349+ return;
350+ }
351+ let fps = diagnostics
352+ .get(&FrameTimeDiagnosticsPlugin::FPS)
353+ .and_then(|d| d.smoothed())
354+ .unwrap_or(0.0);
355+ let frame_ms = diagnostics
356+ .get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
357+ .and_then(|d| d.smoothed())
358+ .unwrap_or(0.0);
359+ let line = format!("{fps:.0} FPS {frame_ms:.1} ms");
360+ for mut text in &mut texts {
361+ if text.0 != line {
362+ text.0 = line.clone();
363+ }
364+ }
365+}
366+
367+#[cfg(test)]
368+mod tests {
369+ use super::*;
370+
371+ #[test]
372+ fn partial_file_falls_back_to_defaults_and_round_trips() {
373+ let settings: Settings =
374+ toml::from_str("[display]\nvsync = false\n").expect("partial settings parse");
375+ assert!(!settings.display.vsync);
376+ assert_eq!(settings.display.resolution, [1280, 720]);
377+ assert_eq!(settings.audio, AudioSettings::default());
378+
379+ let text = toml::to_string_pretty(&settings).expect("encode settings");
380+ let back: Settings = toml::from_str(&text).expect("decode settings");
381+ assert_eq!(back, settings);
382+ }
383+}
src/signals.rsadded+185 -0
@@ -0,0 +1,185 @@
1+//! Map signals, drawn with gizmos each frame: a good icon beside each producer, a supply row
2+//! above each front, and a slow red warning ring around any front with no rail line.
3+
4+use bevy::prelude::*;
5+
6+use crate::front::hourly_need;
7+use crate::model::{Good, Network, NodeId, NodeKind, Train};
8+use crate::seasons::SeasonState;
9+
10+const INK: Color = Color::srgb(0.22, 0.15, 0.09);
11+const RED: Color = Color::srgb(0.78, 0.12, 0.10);
12+const UNSERVED: Color = Color::srgb(0.55, 0.55, 0.52);
13+
14+/// Icon side in world units. At the default zoom a node is about 20 units across.
15+const ICON: f32 = 14.0;
16+/// Distance between scanlines when filling an icon.
17+const FILL_STEP: f32 = 1.5;
18+/// Producer icon offset from its node centre, top right, clear of the track ends.
19+const PRODUCER_OFFSET: Vec2 = Vec2::new(17.0, 17.0);
20+/// Height of the front's supply row above its centre, and the gap between its icons.
21+const FRONT_ROW_Y: f32 = 44.0;
22+const FRONT_ROW_GAP: f32 = 20.0;
23+/// A front icon pulses red while its stock covers less than this many hours of need.
24+const LOW_HOURS: f32 = 6.0;
25+/// Radius of the warning ring around a front with no rail line.
26+const CUT_RING_R: f32 = 26.0;
27+
28+/// The goods a front needs, in the order of its supply row.
29+const FRONT_GOODS: [Good; 3] = [Good::Ammo, Good::Food, Good::Troops];
30+
31+pub struct SignalsPlugin;
32+
33+impl Plugin for SignalsPlugin {
34+ fn build(&self, app: &mut App) {
35+ app.add_systems(Update, draw_signals);
36+ }
37+}
38+
39+/// Same colours as the stock bars on the map.
40+fn good_color(g: Good) -> Color {
41+ match g {
42+ Good::Ammo => Color::srgb(0.33, 0.36, 0.14),
43+ Good::Food => Color::srgb(0.87, 0.73, 0.40),
44+ Good::Troops => Color::srgb(0.10, 0.18, 0.42),
45+ Good::Wounded => Color::srgb(0.72, 0.08, 0.22),
46+ }
47+}
48+
49+/// Outline of a good's icon, in a box of side 1 centred on the origin.
50+fn shape(g: Good) -> Vec<Vec2> {
51+ match g {
52+ // Shell: a body with a pointed nose.
53+ Good::Ammo => vec![
54+ Vec2::new(-0.3, -0.5),
55+ Vec2::new(0.3, -0.5),
56+ Vec2::new(0.3, 0.1),
57+ Vec2::new(0.0, 0.5),
58+ Vec2::new(-0.3, 0.1),
59+ ],
60+ // Helmet: a dome sitting on a brim.
61+ Good::Troops => {
62+ let mut pts = vec![
63+ Vec2::new(-0.5, -0.25),
64+ Vec2::new(0.5, -0.25),
65+ Vec2::new(0.5, -0.12),
66+ ];
67+ for i in 0..=12 {
68+ let a = std::f32::consts::PI * i as f32 / 12.0;
69+ pts.push(Vec2::new(0.45 * a.cos(), -0.05 + 0.45 * a.sin()));
70+ }
71+ pts.push(Vec2::new(-0.5, -0.12));
72+ pts
73+ }
74+ // Food: a filled disc.
75+ Good::Food | Good::Wounded => (0..16)
76+ .map(|i| {
77+ let a = std::f32::consts::TAU * i as f32 / 16.0;
78+ Vec2::new(0.5 * a.cos(), 0.5 * a.sin())
79+ })
80+ .collect(),
81+ }
82+}
83+
84+fn icon_points(g: Good, center: Vec2) -> Vec<Vec2> {
85+ shape(g).iter().map(|p| center + *p * ICON).collect()
86+}
87+
88+/// Fills a simple polygon with horizontal scanlines.
89+fn fill(gizmos: &mut Gizmos, pts: &[Vec2], color: Color) {
90+ let lo = pts.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
91+ let hi = pts.iter().map(|p| p.y).fold(f32::NEG_INFINITY, f32::max);
92+ let mut y = lo + FILL_STEP * 0.5;
93+ while y < hi {
94+ let mut xs: Vec<f32> = Vec::new();
95+ for (a, b) in pts.iter().zip(pts.iter().cycle().skip(1)) {
96+ if (a.y <= y) != (b.y <= y) {
97+ xs.push(a.x + (b.x - a.x) * (y - a.y) / (b.y - a.y));
98+ }
99+ }
100+ xs.sort_by(f32::total_cmp);
101+ for pair in xs.chunks_exact(2) {
102+ gizmos.line_2d(Vec2::new(pair[0], y), Vec2::new(pair[1], y), color);
103+ }
104+ y += FILL_STEP;
105+ }
106+}
107+
108+fn outline(gizmos: &mut Gizmos, pts: &[Vec2], color: Color) {
109+ gizmos.linestrip_2d(pts.iter().copied().chain(pts.first().copied()), color);
110+}
111+
112+/// A filled good icon with an ink outline.
113+fn draw_icon(gizmos: &mut Gizmos, g: Good, center: Vec2) {
114+ let pts = icon_points(g, center);
115+ fill(gizmos, &pts, good_color(g));
116+ outline(gizmos, &pts, INK);
117+}
118+
119+/// A good the front is not receiving: grey outline with a red slash.
120+fn draw_unserved(gizmos: &mut Gizmos, g: Good, center: Vec2) {
121+ outline(gizmos, &icon_points(g, center), UNSERVED);
122+ let h = ICON * 0.5;
123+ gizmos.line_2d(center + Vec2::new(-h, h), center + Vec2::new(h, -h), RED);
124+}
125+
126+fn ring(gizmos: &mut Gizmos, center: Vec2, radius: f32, color: Color) {
127+ gizmos.circle_2d(Isometry2d::from_translation(center), radius, color);
128+}
129+
130+fn draw_signals(
131+ mut gizmos: Gizmos,
132+ net: Res<Network>,
133+ trains: Query<&Train>,
134+ season: Res<SeasonState>,
135+ time: Res<Time>,
136+) {
137+ let t = time.elapsed_secs();
138+ // Both pulses run 0..1. `fast` drives the low-stock ring, `slow` the rail-cut ring.
139+ let fast = 0.5 + 0.5 * (t * 5.0).sin();
140+ let slow = 0.5 + 0.5 * (t * 2.0).sin();
141+ let capital = net
142+ .nodes
143+ .iter()
144+ .position(|n| n.kind == NodeKind::Capital)
145+ .map(NodeId);
146+
147+ for (i, node) in net.nodes.iter().enumerate() {
148+ let c = node.pos;
149+ let made = match node.kind {
150+ NodeKind::Factory => Some(Good::Ammo),
151+ NodeKind::Farm => Some(Good::Food),
152+ NodeKind::Capital | NodeKind::City => Some(Good::Troops),
153+ NodeKind::Depot | NodeKind::Front => None,
154+ };
155+ if let Some(g) = made {
156+ draw_icon(&mut gizmos, g, c + PRODUCER_OFFSET);
157+ }
158+ if node.kind != NodeKind::Front {
159+ continue;
160+ }
161+
162+ let id = NodeId(i);
163+ let connected = capital.is_some_and(|cap| net.shortest_path(cap, id).is_some());
164+ if !connected {
165+ for dr in [0.0, 1.0, 2.0] {
166+ ring(&mut gizmos, c, CUT_RING_R + 3.0 * slow + dr, RED);
167+ }
168+ }
169+
170+ for (k, g) in FRONT_GOODS.iter().enumerate() {
171+ let center = c + Vec2::new((k as f32 - 1.0) * FRONT_ROW_GAP, FRONT_ROW_Y);
172+ let delivered = trains
173+ .iter()
174+ .any(|tr| tr.can_carry(*g) && tr.route.iter().any(|s| s.node == id));
175+ if !delivered {
176+ draw_unserved(&mut gizmos, *g, center);
177+ continue;
178+ }
179+ draw_icon(&mut gizmos, *g, center);
180+ if node.stock[g.idx()] < LOW_HOURS * hourly_need(*g, season.season.food_mult()) {
181+ ring(&mut gizmos, center, ICON * 0.5 + 2.0 + 2.5 * fast, RED);
182+ }
183+ }
184+ }
185+}
src/supply.rsadded+424 -0
@@ -0,0 +1,424 @@
1+//! The drag gesture: left-drag from one node to another to run a supply line.
2+//!
3+//! The source sends the good it makes; the target must accept it. A straight
4+//! track is laid when no usable rail path exists, and a train that carries the
5+//! good is bought. Dragging the same pair again adds another train.
6+
7+use bevy::ecs::system::SystemParam;
8+use bevy::prelude::*;
9+use bevy::window::PrimaryWindow;
10+
11+use crate::audio::SoundEvent;
12+use crate::build::{new_segments, segments_cost};
13+use crate::evac;
14+use crate::map::{MapHover, WorldText, dashed, good_color, picking};
15+use crate::model::{
16+ CarKind, Good, LocoKind, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool,
17+ TrackSeg, Treasury, consist_cost,
18+};
19+use crate::trains::new_train;
20+
21+pub struct SupplyPlugin;
22+
23+impl Plugin for SupplyPlugin {
24+ fn build(&self, app: &mut App) {
25+ app.init_resource::<Drag>()
26+ .add_systems(Startup, spawn_drag_label)
27+ .add_systems(Update, (drag_gesture, draw_drag).chain().after(picking));
28+ }
29+}
30+
31+/// Pointer movement in logical pixels that turns a press into a drag.
32+const DRAG_THRESHOLD: f32 = 6.0;
33+/// Glyph size of the floating cost label, in world units (see `map::WorldText`).
34+const LABEL_SIZE: f32 = 27.0;
35+/// Offset of the floating label from the cursor.
36+const LABEL_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
37+const DRAG_DASH: f32 = 12.0;
38+const DRAG_GAP: f32 = 8.0;
39+const RING_RADIUS: f32 = 24.0;
40+
41+const INK: Color = Color::srgb(0.22, 0.15, 0.09);
42+const GREEN: Color = Color::srgb(0.1, 0.5, 0.1);
43+const RED: Color = Color::srgb(0.8, 0.1, 0.1);
44+const VALID_RING: Color = Color::srgb(1.0, 0.92, 0.45);
45+
46+/// The good a node sends out, if any. Depots only store.
47+pub fn produces(kind: NodeKind) -> Option<Good> {
48+ match kind {
49+ NodeKind::Factory => Some(Good::Ammo),
50+ NodeKind::Farm => Some(Good::Food),
51+ NodeKind::Capital | NodeKind::City => Some(Good::Troops),
52+ NodeKind::Front => Some(Good::Wounded),
53+ NodeKind::Depot => None,
54+ }
55+}
56+
57+/// The good a drag from a `from` node to a `to` node sends, if `to` takes it.
58+pub fn flow(from: NodeKind, to: NodeKind) -> Option<Good> {
59+ let good = produces(from)?;
60+ match good {
61+ // Wounded only go home: to a Capital or City, never to a Depot.
62+ Good::Wounded => matches!(to, NodeKind::Capital | NodeKind::City).then_some(good),
63+ _ => to.accepts(good).then_some(good),
64+ }
65+}
66+
67+/// The default consist that carries a good: a locomotive and its cars.
68+pub fn consist_for(good: Good) -> (LocoKind, Vec<CarKind>) {
69+ match good {
70+ Good::Ammo => (LocoKind::Heavy, vec![CarKind::Ammo; 4]),
71+ Good::Food => (LocoKind::Light, vec![CarKind::Food; 2]),
72+ Good::Troops => (LocoKind::Light, vec![CarKind::Troop; 2]),
73+ Good::Wounded => (LocoKind::Light, vec![CarKind::Hospital; 3]),
74+ }
75+}
76+
77+/// Whole dollars with thousands separators: "$1,840".
78+pub fn money(v: i64) -> String {
79+ let digits = v.unsigned_abs().to_string();
80+ let mut out = String::new();
81+ for (i, c) in digits.chars().enumerate() {
82+ if i > 0 && (digits.len() - i).is_multiple_of(3) {
83+ out.push(',');
84+ }
85+ out.push(c);
86+ }
87+ if v < 0 {
88+ format!("-${out}")
89+ } else {
90+ format!("${out}")
91+ }
92+}
93+
94+/// What a drag from one node to another would do and cost.
95+#[derive(Debug, Clone, PartialEq)]
96+pub struct Plan {
97+ /// Good carried by the new train, if any.
98+ pub good: Option<Good>,
99+ /// True when the train carries evacuation crates from an evacuating site.
100+ pub evac: bool,
101+ /// Cost of the new track segments, if no usable rail path exists.
102+ pub track: Option<i64>,
103+ /// The new segments to lay, split at any node the straight line passes.
104+ pub segments: Vec<TrackSeg>,
105+ /// Total cost: track plus train.
106+ pub total: i64,
107+}
108+
109+/// Works out the plan for a drag, or the reason it cannot be done.
110+pub fn plan(net: &Network, from: NodeId, to: NodeId) -> Result<Plan, String> {
111+ let a = &net.nodes[from.0];
112+ let b = &net.nodes[to.0];
113+ if from == to {
114+ return Err(format!("Drag from {} to another node", a.name));
115+ }
116+ if a.captured || b.captured {
117+ let lost = if a.captured { a } else { b };
118+ return Err(format!("{} is captured", lost.name));
119+ }
120+ let evac = a.evac.is_some();
121+ if evac {
122+ evac::check_dest(net, from, to)?;
123+ }
124+ let good = if evac { None } else { flow(a.kind, b.kind) };
125+ let segments = if net.shortest_path(from, to).is_some() {
126+ Vec::new()
127+ } else {
128+ let segs = new_segments(net, from, to);
129+ if segs.is_empty() {
130+ return Err(format!("{}-{} is cut: repair it first", a.name, b.name));
131+ }
132+ segs
133+ };
134+ let track = (!segments.is_empty()).then(|| segments_cost(&segments));
135+ if good.is_none() && !evac && track.is_none() {
136+ return Err(format!("Nothing to send from {} to {}", a.name, b.name));
137+ }
138+ let train_cost = if evac {
139+ let (loco, cars) = evac::evac_consist();
140+ consist_cost(loco, &cars)
141+ } else {
142+ good.map_or(0, |g| {
143+ let (loco, cars) = consist_for(g);
144+ consist_cost(loco, &cars)
145+ })
146+ };
147+ let total = track.unwrap_or(0) + train_cost;
148+ Ok(Plan {
149+ good,
150+ evac,
151+ track,
152+ segments,
153+ total,
154+ })
155+}
156+
157+/// Load flags for a stop that loads exactly one good.
158+fn load_of(good: Good) -> [bool; 4] {
159+ let mut load = [false; 4];
160+ load[good.idx()] = true;
161+ load
162+}
163+
164+/// State of the pointer press in progress.
165+#[derive(Resource, Default)]
166+struct Drag {
167+ /// Node the press started on.
168+ from: Option<NodeId>,
169+ /// Cursor position at the press, in logical pixels.
170+ press: Vec2,
171+ /// True once the pointer moved past the threshold with the Inspect tool.
172+ active: bool,
173+ /// Last cursor position over the map, in world units.
174+ world: Option<Vec2>,
175+}
176+
177+/// Floating cost label that follows the cursor during a drag.
178+#[derive(Component)]
179+struct DragLabel;
180+
181+#[derive(SystemParam)]
182+struct GestureParams<'w, 's> {
183+ buttons: Res<'w, ButtonInput<MouseButton>>,
184+ hover: Res<'w, MapHover>,
185+ window: Single<'w, 's, &'static Window, With<PrimaryWindow>>,
186+ tool: Res<'w, Tool>,
187+ net: ResMut<'w, Network>,
188+ treasury: ResMut<'w, Treasury>,
189+ drag: ResMut<'w, Drag>,
190+ commands: Commands<'w, 's>,
191+ notify: MessageWriter<'w, Notify>,
192+ sounds: MessageWriter<'w, SoundEvent>,
193+ node_clicked: MessageWriter<'w, NodeClicked>,
194+}
195+
196+fn spawn_drag_label(mut commands: Commands) {
197+ commands.spawn((
198+ DragLabel,
199+ Text2d::new(""),
200+ WorldText { size: LABEL_SIZE },
201+ TextColor(INK),
202+ Visibility::Hidden,
203+ Transform::from_xyz(0.0, 0.0, 21.0),
204+ ));
205+}
206+
207+/// Press, drag and release on the map.
208+///
209+/// A press and release without movement is a plain click and sends `NodeClicked`
210+/// on release, so selection and the B and R tools keep working. Movement with
211+/// the Inspect tool turns it into a supply line dragged to the node under the cursor.
212+fn drag_gesture(mut p: GestureParams) {
213+ let cursor = p.window.cursor_position();
214+ if p.buttons.just_pressed(MouseButton::Left) {
215+ p.drag.from = p.hover.node;
216+ p.drag.press = cursor.unwrap_or_default();
217+ p.drag.active = false;
218+ p.drag.world = None;
219+ }
220+
221+ let inspect = matches!(*p.tool, Tool::Inspect);
222+ if p.buttons.pressed(MouseButton::Left) && p.drag.from.is_some() && inspect {
223+ if let Some(c) = cursor
224+ && (c - p.drag.press).length() > DRAG_THRESHOLD
225+ {
226+ p.drag.active = true;
227+ }
228+ if p.drag.active
229+ && let Some(w) = p.hover.world
230+ {
231+ p.drag.world = Some(w);
232+ }
233+ }
234+
235+ if !p.buttons.just_released(MouseButton::Left) {
236+ return;
237+ }
238+ let Some(from) = p.drag.from.take() else {
239+ return;
240+ };
241+ let active = std::mem::take(&mut p.drag.active);
242+ p.drag.world = None;
243+ if !active {
244+ p.node_clicked.write(NodeClicked(from));
245+ return;
246+ }
247+ if let Some(to) = p.hover.node
248+ && to != from
249+ {
250+ buy_line(
251+ &mut p.net,
252+ &mut p.treasury,
253+ &mut p.commands,
254+ &mut p.notify,
255+ &mut p.sounds,
256+ from,
257+ to,
258+ );
259+ }
260+}
261+
262+/// Buys a supply line from `from` to `to`: charges, lays track if needed, buys the
263+/// train that carries the good, and tells the player. Shared by the drag gesture and
264+/// the [+] chip, so both behave the same.
265+pub(crate) fn buy_line(
266+ net: &mut Network,
267+ treasury: &mut Treasury,
268+ commands: &mut Commands,
269+ notify: &mut MessageWriter<Notify>,
270+ sounds: &mut MessageWriter<SoundEvent>,
271+ from: NodeId,
272+ to: NodeId,
273+) {
274+ let plan = match plan(net, from, to) {
275+ Ok(plan) => plan,
276+ Err(msg) => {
277+ notify.write(Notify(msg));
278+ return;
279+ }
280+ };
281+ if plan.total > treasury.0 {
282+ notify.write(Notify(format!("Need {}", money(plan.total))));
283+ return;
284+ }
285+ treasury.0 -= plan.total;
286+
287+ let a = net.nodes[from.0].name.clone();
288+ let b = net.nodes[to.0].name.clone();
289+ net.tracks.extend(plan.segments.iter().copied());
290+
291+ let message = if plan.evac {
292+ let (loco, cars) = evac::evac_consist();
293+ commands.spawn(new_train(
294+ loco,
295+ cars,
296+ vec![
297+ Stop {
298+ node: from,
299+ load: [false; 4],
300+ },
301+ Stop {
302+ node: to,
303+ load: [false; 4],
304+ },
305+ ],
306+ ));
307+ if let Some(e) = net.nodes[from.0].evac.as_mut() {
308+ e.dest = Some(to);
309+ }
310+ sounds.write(SoundEvent::TrainDeparts);
311+ format!("Evacuating {a} -> {b}")
312+ } else {
313+ match plan.good {
314+ Some(good) => {
315+ let (loco, cars) = consist_for(good);
316+ commands.spawn(new_train(
317+ loco,
318+ cars,
319+ vec![
320+ Stop {
321+ node: from,
322+ load: load_of(good),
323+ },
324+ Stop {
325+ node: to,
326+ load: [false; 4],
327+ },
328+ ],
329+ ));
330+ sounds.write(SoundEvent::TrainDeparts);
331+ format!("{} line: {a} -> {b}", good.name())
332+ }
333+ None => {
334+ sounds.write(SoundEvent::TrackLaid);
335+ format!("Laid track {a}-{b} for {}", money(plan.total))
336+ }
337+ }
338+ };
339+ let message = if plan.track.is_some() && plan.good.is_some() {
340+ format!("{message} (new track)")
341+ } else {
342+ message
343+ };
344+ notify.write(Notify(message));
345+}
346+
347+/// Dashed line from the source to the cursor, ring on every node that takes the good,
348+/// and the floating cost label.
349+fn draw_drag(
350+ mut gizmos: Gizmos,
351+ drag: Res<Drag>,
352+ net: Res<Network>,
353+ treasury: Res<Treasury>,
354+ hover: Res<MapHover>,
355+ mut labels: Query<
356+ (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility),
357+ With<DragLabel>,
358+ >,
359+) {
360+ let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else {
361+ return;
362+ };
363+ let (Some(from), true) = (drag.from, drag.active) else {
364+ *visibility = Visibility::Hidden;
365+ return;
366+ };
367+ let source = &net.nodes[from.0];
368+ let evacuating = source.evac.is_some();
369+ let good = produces(source.kind);
370+ let target = hover.node.filter(|t| *t != from);
371+
372+ for (i, node) in net.nodes.iter().enumerate() {
373+ if NodeId(i) == from {
374+ continue;
375+ }
376+ let valid = if evacuating {
377+ evac::check_dest(&net, from, NodeId(i)).is_ok()
378+ } else {
379+ good.is_none() || flow(source.kind, node.kind).is_some()
380+ };
381+ if valid {
382+ gizmos.circle_2d(Isometry2d::from_translation(node.pos), RING_RADIUS, VALID_RING);
383+ }
384+ }
385+
386+ let line_color = if evacuating {
387+ RED
388+ } else {
389+ good.map_or(Color::srgba(0.2, 0.15, 0.1, 0.8), good_color)
390+ };
391+ let end = target.map(|t| net.nodes[t.0].pos).or(drag.world);
392+ let planned = target.map(|t| plan(&net, from, t));
393+ match &planned {
394+ // New track: draw each segment, so the split at a passed node shows.
395+ Some(Ok(p)) if !p.segments.is_empty() => {
396+ for s in &p.segments {
397+ let (start, stop) = (net.nodes[s.a.0].pos, net.nodes[s.b.0].pos);
398+ dashed(&mut gizmos, start, stop, DRAG_DASH, DRAG_GAP, line_color);
399+ }
400+ }
401+ _ => {
402+ if let Some(end) = end {
403+ dashed(&mut gizmos, source.pos, end, DRAG_DASH, DRAG_GAP, line_color);
404+ }
405+ }
406+ }
407+
408+ let Some(result) = planned else {
409+ *visibility = Visibility::Hidden;
410+ return;
411+ };
412+ let (label, label_color) = match result {
413+ Ok(plan) if plan.total > treasury.0 => (money(plan.total), RED),
414+ Ok(plan) => (money(plan.total), GREEN),
415+ Err(msg) => (msg, RED),
416+ };
417+ let at = drag.world.or(end).unwrap_or(source.pos) + LABEL_OFFSET;
418+ if text.0 != label {
419+ text.0 = label;
420+ }
421+ *color = TextColor(label_color);
422+ transform.translation = at.extend(21.0);
423+ *visibility = Visibility::Visible;
424+}
src/trains.rsadded+499 -0
@@ -0,0 +1,499 @@
1+//! Train simulation and train drawing.
2+
3+use bevy::prelude::*;
4+
5+use crate::audio::SoundEvent;
6+use crate::map::good_color;
7+use crate::model::{
8+ CAR_CAPACITY, CarKind, GOODS, LocoKind, MIN_USABLE_CONDITION, Network, NodeId, Notify,
9+ SimClock, Stop, Train, speed_factor,
10+};
11+use 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.
15+pub 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.
33+pub 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+
49+fn 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.
54+pub 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)]
64+pub 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)]
68+pub struct TrainCounter(pub u32);
69+
70+/// Private per-train bookkeeping for stalls.
71+#[derive(Component, Debug, Default)]
72+struct 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+
79+const DWELL_SECS: f32 = 1.0;
80+const STALL_RETRY_SECS: f32 = 1.0;
81+/// Locomotive length, and car length and spacing, in world units.
82+const LOCO_LEN: f32 = 18.0;
83+const CAR_LEN: f32 = 12.0;
84+const CAR_GAP: f32 = 2.0;
85+const TRAIN_HALF_WIDTH: f32 = 4.0;
86+const 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.
96+pub 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.
116+fn 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.
132+fn 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.
151+fn 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.
176+fn 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+
226+fn 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.
306+fn 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.
315+struct Frame {
316+ center: Vec2,
317+ dir: Vec2,
318+ nrm: Vec2,
319+}
320+
321+impl Frame {
322+ fn at(&self, x: f32, y: f32) -> Vec2 {
323+ self.center + self.dir * x + self.nrm * y
324+ }
325+}
326+
327+fn 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+
441+pub struct TrainsPlugin;
442+
443+impl 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)]
455+mod 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+}
src/tutorial.rsadded+366 -0
@@ -0,0 +1,366 @@
1+//! Opening tutorial that teaches by pointing. Arrows and pulsing rings are drawn on the map
2+//! with a short caption each, and the player's own drags move the tutorial along.
3+//!
4+//! The steps are: send Ammo, Food and Troops into the Centre Sector by dragging from a source
5+//! node to it, then supply the North and South Sectors for a few seconds. The tutorial is
6+//! skipped in the scenario and demo runs.
7+
8+use std::f32::consts::TAU;
9+
10+use bevy::ecs::system::SystemParam;
11+use bevy::prelude::*;
12+use bevy::time::{Real, Time};
13+
14+use crate::map::WorldText;
15+use crate::menu::Menu;
16+use crate::model::{Network, NodeId, Train};
17+
18+const INK: Color = Color::srgb(0.22, 0.15, 0.09);
19+const RUST: Color = Color::srgb(0.66, 0.26, 0.12);
20+
21+/// Glyph size of the captions, in world units.
22+const CAPTION_SIZE: f32 = 30.0;
23+/// Average advance of the caption font in ems, to estimate its width before layout.
24+const CAPTION_CHAR_EM: f32 = 0.6;
25+/// Gap between the target node centre and the caption's right edge, clear of the node icon
26+/// and the arrow head.
27+const CAPTION_NODE_GAP: f32 = 40.0;
28+/// How far below the target a step's caption sits. Keeps it off the node name label above
29+/// the node and off the arrow shaft coming in from the left.
30+const CAPTION_DROP: f32 = 20.0;
31+/// Caption centres are kept this far inside the map frame, in world units. The frame is
32+/// 1280 by 720, so the x limit leaves a margin at each side.
33+const CAPTION_X_LIMIT: f32 = 560.0;
34+const CAPTION_Y_LIMIT: f32 = 340.0;
35+/// Radius of the pulsing ring around a node, at rest.
36+const RING_RADIUS: f32 = 26.0;
37+/// Seconds per pulse of the rings.
38+const PULSE_PERIOD: f32 = 1.2;
39+/// Distance from the source centre where the arrow starts, clear of its ring.
40+const ARROW_START_GAP: f32 = 32.0;
41+/// Distance from the target centre where the arrow tip sits, clear of the node icon.
42+const ARROW_TIP_GAP: f32 = 26.0;
43+/// Length of the arrowhead.
44+const ARROW_HEAD_LEN: f32 = 18.0;
45+/// Half the width of the arrowhead base.
46+const ARROW_HEAD_HALF_W: f32 = 9.0;
47+/// Spacing between the parallel lines that make the shaft thick.
48+const SHAFT_LINE_STEP: f32 = 1.2;
49+/// Number of parallel lines on each side of the shaft centre line.
50+const SHAFT_LINES: i32 = 2;
51+/// World units per real second the dashes and chevrons travel.
52+const FLOW_SPEED: f32 = 42.0;
53+/// Length of a dash and the gap after it.
54+const DASH_ON: f32 = 14.0;
55+const DASH_PERIOD: f32 = 22.0;
56+/// Distance between chevrons along the shaft.
57+const CHEVRON_PERIOD: f32 = 66.0;
58+/// Size of a chevron's arms.
59+const CHEVRON_ARM: f32 = 6.0;
60+/// Real seconds the supply step lasts.
61+const SUPPLY_SECONDS: f32 = 8.0;
62+
63+/// One arrow step: drag from `from` to `to` to send what `from` makes.
64+struct Lesson {
65+ from: &'static str,
66+ to: &'static str,
67+ caption: &'static str,
68+}
69+
70+const LESSONS: [Lesson; 3] = [
71+ Lesson {
72+ from: "Ostwerk",
73+ to: "Centre Sector",
74+ caption: "Drag: send Ammo",
75+ },
76+ Lesson {
77+ from: "Lindach",
78+ to: "Centre Sector",
79+ caption: "Drag: send Food",
80+ },
81+ Lesson {
82+ from: "Varenholm",
83+ to: "Centre Sector",
84+ caption: "Drag: send Troops",
85+ },
86+];
87+
88+const SUPPLY_NODES: [&str; 2] = ["North Sector", "South Sector"];
89+const SUPPLY_CAPTION: &str = "Now supply these";
90+
91+pub struct TutorialPlugin {
92+ /// False in the scenario and demo runs, which have their own script.
93+ pub enabled: bool,
94+}
95+
96+impl Plugin for TutorialPlugin {
97+ fn build(&self, app: &mut App) {
98+ if !self.enabled {
99+ return;
100+ }
101+ app.init_resource::<Tutorial>()
102+ .add_systems(Update, run_tutorial);
103+ }
104+}
105+
106+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107+enum Stage {
108+ /// Index into `LESSONS`.
109+ Send(usize),
110+ Supply,
111+ Done,
112+}
113+
114+#[derive(Resource)]
115+struct Tutorial {
116+ stage: Stage,
117+ /// Stage whose caption is currently on screen.
118+ shown: Option<Stage>,
119+ caption: Option<Entity>,
120+ /// Real seconds left in the supply step.
121+ supply_left: f32,
122+}
123+
124+impl Default for Tutorial {
125+ fn default() -> Self {
126+ Self {
127+ stage: Stage::Send(0),
128+ shown: None,
129+ caption: None,
130+ supply_left: SUPPLY_SECONDS,
131+ }
132+ }
133+}
134+
135+/// Marker for the caption text of the current step.
136+#[derive(Component)]
137+struct TutorialCaption;
138+
139+enum Body {
140+ Arrow(Vec2, Vec2),
141+ Rings(Vec<Vec2>),
142+}
143+
144+struct Shape {
145+ caption: &'static str,
146+ /// Centre of the caption in world units.
147+ anchor: Vec2,
148+ body: Body,
149+}
150+
151+/// Centre for a caption placed to the left of `target`, `drop` below its height. The result
152+/// is clamped so the whole caption stays inside the map frame.
153+fn caption_anchor(target: Vec2, caption: &str, drop: f32) -> Vec2 {
154+ let half_w = caption.chars().count() as f32 * CAPTION_CHAR_EM * CAPTION_SIZE * 0.5;
155+ let x = (target.x - CAPTION_NODE_GAP - half_w)
156+ .clamp(-CAPTION_X_LIMIT + half_w, CAPTION_X_LIMIT - half_w);
157+ let y = (target.y - drop).clamp(-CAPTION_Y_LIMIT, CAPTION_Y_LIMIT);
158+ Vec2::new(x, y)
159+}
160+
161+fn node_named(net: &Network, name: &str) -> Option<(NodeId, Vec2)> {
162+ net.nodes
163+ .iter()
164+ .enumerate()
165+ .find(|(_, n)| n.name == name)
166+ .map(|(i, n)| (NodeId(i), n.pos))
167+}
168+
169+/// True when some train's route visits both nodes.
170+fn sent(trains: &Query<&Train>, a: NodeId, b: NodeId) -> bool {
171+ trains.iter().any(|t| {
172+ t.route.iter().any(|s| s.node == a) && t.route.iter().any(|s| s.node == b)
173+ })
174+}
175+
176+/// What to draw for a stage, or `None` when its nodes are not on the map.
177+fn shape_for(stage: Stage, net: &Network) -> Option<Shape> {
178+ match stage {
179+ Stage::Send(i) => {
180+ let lesson = &LESSONS[i];
181+ let (_, a) = node_named(net, lesson.from)?;
182+ let (_, b) = node_named(net, lesson.to)?;
183+ Some(Shape {
184+ caption: lesson.caption,
185+ anchor: caption_anchor(b, lesson.caption, CAPTION_DROP),
186+ body: Body::Arrow(a, b),
187+ })
188+ }
189+ Stage::Supply => {
190+ let points = SUPPLY_NODES
191+ .iter()
192+ .map(|name| node_named(net, name).map(|(_, p)| p))
193+ .collect::<Option<Vec<Vec2>>>()?;
194+ // Beside the northernmost sector, so the caption sits on no node.
195+ let top = points.iter().copied().max_by(|a, b| a.y.total_cmp(&b.y))?;
196+ Some(Shape {
197+ caption: SUPPLY_CAPTION,
198+ anchor: caption_anchor(top, SUPPLY_CAPTION, 0.0),
199+ body: Body::Rings(points),
200+ })
201+ }
202+ Stage::Done => None,
203+ }
204+}
205+
206+fn clear_caption(commands: &mut Commands, tut: &mut Tutorial) {
207+ if let Some(entity) = tut.caption.take() {
208+ commands.entity(entity).despawn();
209+ }
210+ tut.shown = None;
211+}
212+
213+/// What the tutorial reads and draws, grouped to keep the system signature short.
214+#[derive(SystemParam)]
215+struct TutorialParams<'w, 's> {
216+ net: Res<'w, Network>,
217+ trains: Query<'w, 's, &'static Train>,
218+ time: Res<'w, Time<Real>>,
219+ menu: Res<'w, Menu>,
220+ gizmos: Gizmos<'w, 's>,
221+ captions: Query<'w, 's, &'static mut Visibility, With<TutorialCaption>>,
222+}
223+
224+fn run_tutorial(mut commands: Commands, mut tut: ResMut<Tutorial>, p: TutorialParams) {
225+ let TutorialParams {
226+ net,
227+ trains,
228+ time,
229+ menu,
230+ mut gizmos,
231+ mut captions,
232+ } = p;
233+ // The tutorial waits behind any open menu, so captions hide and the clock stops.
234+ let open = menu.is_open();
235+ for mut visibility in &mut captions {
236+ *visibility = if open {
237+ Visibility::Hidden
238+ } else {
239+ Visibility::Visible
240+ };
241+ }
242+ if open {
243+ return;
244+ }
245+
246+ // Advance once the goal of the current step is met.
247+ let next = match tut.stage {
248+ Stage::Send(i) => match (
249+ node_named(&net, LESSONS[i].from),
250+ node_named(&net, LESSONS[i].to),
251+ ) {
252+ (Some((a, _)), Some((b, _))) if sent(&trains, a, b) => Some(if i + 1 < LESSONS.len() {
253+ Stage::Send(i + 1)
254+ } else {
255+ Stage::Supply
256+ }),
257+ _ => None,
258+ },
259+ Stage::Supply | Stage::Done => None,
260+ };
261+ if let Some(stage) = next {
262+ tut.stage = stage;
263+ if stage == Stage::Supply {
264+ tut.supply_left = SUPPLY_SECONDS;
265+ }
266+ }
267+ if tut.stage == Stage::Supply {
268+ tut.supply_left -= time.delta_secs();
269+ if tut.supply_left <= 0.0 {
270+ tut.stage = Stage::Done;
271+ }
272+ }
273+
274+ let Some(shape) = shape_for(tut.stage, &net) else {
275+ clear_caption(&mut commands, &mut tut);
276+ return;
277+ };
278+
279+ if tut.shown != Some(tut.stage) {
280+ clear_caption(&mut commands, &mut tut);
281+ let entity = commands
282+ .spawn((
283+ TutorialCaption,
284+ Text2d(shape.caption.to_string()),
285+ WorldText {
286+ size: CAPTION_SIZE,
287+ },
288+ TextColor(INK),
289+ TextLayout::justify(Justify::Center),
290+ Transform::from_xyz(shape.anchor.x, shape.anchor.y, 2.0),
291+ Visibility::Visible,
292+ ))
293+ .id();
294+ tut.caption = Some(entity);
295+ tut.shown = Some(tut.stage);
296+ }
297+
298+ let t = time.elapsed_secs();
299+ match shape.body {
300+ Body::Arrow(from, to) => {
301+ draw_arrow(&mut gizmos, from, to, t);
302+ draw_ring(&mut gizmos, from, t);
303+ }
304+ Body::Rings(points) => {
305+ for p in points {
306+ draw_ring(&mut gizmos, p, t);
307+ }
308+ }
309+ }
310+}
311+
312+/// Pulsing ring that marks where to grab or where to supply.
313+fn draw_ring(gizmos: &mut Gizmos, center: Vec2, t: f32) {
314+ let pulse = (t * TAU / PULSE_PERIOD).sin() * 0.5 + 0.5;
315+ let r = RING_RADIUS + pulse * 4.0;
316+ let iso = Isometry2d::from_translation(center);
317+ gizmos.circle_2d(iso, r, RUST);
318+ gizmos.circle_2d(iso, r + 1.5, RUST);
319+}
320+
321+/// Thick dashed shaft with chevrons flowing from `from` to `to`, and a filled head at `to`.
322+fn draw_arrow(gizmos: &mut Gizmos, from: Vec2, to: Vec2, t: f32) {
323+ let delta = to - from;
324+ let length = delta.length();
325+ if length <= ARROW_START_GAP + ARROW_TIP_GAP + ARROW_HEAD_LEN {
326+ return;
327+ }
328+ let dir = delta / length;
329+ let perp = dir.perp();
330+ let start = from + dir * ARROW_START_GAP;
331+ let tip = to - dir * ARROW_TIP_GAP;
332+ let shaft_end = tip - dir * ARROW_HEAD_LEN;
333+ let shaft_len = (shaft_end - start).length();
334+
335+ // Dashes, drawn as several parallel lines so the shaft reads as thick.
336+ let dash_phase = (t * FLOW_SPEED).rem_euclid(DASH_PERIOD);
337+ for k in -SHAFT_LINES..=SHAFT_LINES {
338+ let off = perp * (k as f32 * SHAFT_LINE_STEP);
339+ let mut s = dash_phase - DASH_PERIOD;
340+ while s < shaft_len {
341+ let a = s.max(0.0);
342+ let b = (s + DASH_ON).min(shaft_len);
343+ if b > a {
344+ gizmos.line_2d(start + dir * a + off, start + dir * b + off, RUST);
345+ }
346+ s += DASH_PERIOD;
347+ }
348+ }
349+
350+ // Chevrons moving along the shaft in the direction of travel.
351+ let chevron_phase = (t * FLOW_SPEED).rem_euclid(CHEVRON_PERIOD);
352+ let mut p = chevron_phase;
353+ while p < shaft_len {
354+ let c = start + dir * p;
355+ gizmos.line_2d(c - dir * CHEVRON_ARM + perp * CHEVRON_ARM, c, RUST);
356+ gizmos.line_2d(c - dir * CHEVRON_ARM - perp * CHEVRON_ARM, c, RUST);
357+ p += CHEVRON_PERIOD;
358+ }
359+
360+ // Filled head: fan of lines from the tip across the base.
361+ let base = shaft_end;
362+ for i in -6..=6 {
363+ let off = perp * (i as f32 * ARROW_HEAD_HALF_W / 6.0);
364+ gizmos.line_2d(tip, base + off, RUST);
365+ }
366+}