forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

routes.rs300 lines, 9.1 KiBHistoryRawDownload
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
5use bevy::ecs::system::SystemParam;
6use bevy::prelude::*;
7use bevy::ui_widgets::Activate;
8
9use crate::audio::SoundEvent;
10use crate::map::{WorldText, dashed};
11use crate::model::{
12 CarKind, GOODS, Good, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool, Train,
13 Treasury, consist_cost,
14};
15use crate::supply::{buy_line, money, produces};
16
17pub struct RoutesPlugin;
18
19impl 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.
33const DASH_LEN: f32 = 10.0;
34const GAP_LEN: f32 = 6.0;
35/// Stop number glyph size in world units (see `map::WorldText`).
36const STOP_LABEL_SIZE: f32 = 16.0;
37
38fn ink() -> Color {
39 Color::srgb(0.15, 0.12, 0.08)
40}
41fn amber() -> Color {
42 Color::srgb(1.0, 0.75, 0.2)
43}
44fn 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)]
51pub(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)]
56pub(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)]
64pub(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)]
72pub(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)]
79struct RouteLabel;
80
81#[derive(SystemParam)]
82struct 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)]
90struct 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.
98fn 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.
114pub(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).
120fn 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.
146fn 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.
165fn 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.
187fn 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`).
219fn 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.
243fn 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.
275fn 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}