forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

map.rs1121 lines, 38.2 KiBHistoryRawDownload
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
6use bevy::ecs::system::SystemParam;
7use bevy::input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll};
8use bevy::prelude::*;
9use bevy::sprite::Anchor;
10use bevy::time::{Real, Time};
11use bevy::ui::{CalculatedClip, ComputedNode, UiGlobalTransform, UiScale};
12use bevy::window::PrimaryWindow;
13
14use crate::menu::Menu;
15use crate::model::{
16 GOODS, Good, MIN_USABLE_CONDITION, Network, Node, NodeId, NodeKind, SLOW_CONDITION, Selected,
17 TrackClicked, UiPassThrough,
18};
19use crate::settings::Settings;
20
21/// Default zoom limits (orthographic scale). The view is 720 world units tall at scale 1.
22const MIN_SCALE: f32 = 0.5;
23const MAX_SCALE: f32 = 2.5;
24/// World units of the map frame (the playfield), centred on the origin.
25const MAP_W: f32 = 1280.0;
26const MAP_H: f32 = 720.0;
27/// Blank space kept between the map frame and the window edges, in logical px.
28const FIT_MARGIN_X: f32 = 16.0;
29const FIT_MARGIN_Y: f32 = 8.0;
30/// Arrow-key pan speed in logical pixels per second.
31const KEY_PAN_SPEED: f32 = 450.0;
32/// Node pick radius in logical pixels, so clicks feel the same at any zoom or window size.
33const NODE_PICK_RADIUS: f32 = 20.0;
34/// Track pick distance in logical pixels.
35const 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).
38const 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).
40const NODE_LABEL_OFFSET: f32 = 46.0;
41/// Gap between a node centre and a label placed beside or above it.
42const LABEL_SIDE_GAP: f32 = 14.0;
43/// Average advance of the label font in ems, to estimate label width before layout.
44const LABEL_CHAR_EM: f32 = 0.6;
45/// Gap kept clear at each end of a track so it does not run into node glyphs.
46const NODE_GLYPH_RADIUS: f32 = 12.0;
47/// Spacing of crossties along a track.
48const TIE_SPACING: f32 = 12.0;
49/// Half-length of a crosstie.
50const TIE_HALF_LEN: f32 = 4.0;
51/// Stock bar scale: world units per stock unit, capped at `BAR_MAX_WIDTH`.
52const BAR_UNITS_PER_STOCK: f32 = 0.4;
53const BAR_MAX_WIDTH: f32 = 40.0;
54
55const INK: Color = Color::srgb(0.22, 0.15, 0.09);
56const RUST: Color = Color::srgb(0.66, 0.26, 0.12);
57const RED: Color = Color::srgb(0.78, 0.12, 0.10);
58const AMBER: Color = Color::srgb(1.0, 0.70, 0.10);
59const HOVER_RING: Color = Color::srgb(1.0, 0.98, 0.90);
60/// Name of a captured site, and the parchment that greys its glyph.
61const CAPTURED_INK: Color = Color::srgb(0.52, 0.48, 0.42);
62const PARCH: Color = Color::srgba(0.86, 0.81, 0.68, 0.6);
63/// Slowed track, and the repair badge on any damaged track.
64const SLOW_ORANGE: Color = Color::srgb(1.0, 0.55, 0.10);
65const CRATER: Color = Color::srgb(0.16, 0.10, 0.06);
66/// Warm tint of lightly scorched track.
67const SCORCH: Color = Color::srgb(0.80, 0.42, 0.16);
68/// Any track below this condition shows its damage, however mild.
69const DAMAGED_CONDITION: f32 = 0.95;
70/// Gap cut into blocked track, and the distance between the two rails.
71const GAP_LEN: f32 = 14.0;
72const RAIL_HALF: f32 = 2.5;
73/// Repair badge sits this far off the track's midpoint.
74const BADGE_OFFSET: f32 = 16.0;
75const BADGE_R: f32 = 8.0;
76
77pub struct MapPlugin;
78
79impl 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)]
103pub struct ZoomLimits {
104 pub min: f32,
105 pub max: f32,
106}
107
108impl 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`.
124fn 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)]
141struct 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.
154fn 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)]
189pub 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)]
206pub 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)]
213struct NodeLabel(usize);
214
215/// Sides of a node a name label can sit on, in tie-break order.
216#[derive(Clone, Copy)]
217enum LabelSide {
218 Below,
219 Above,
220 Right,
221 Left,
222}
223
224const 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.
233fn 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
268fn 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`.
285fn 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.
311fn 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.
325fn 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
346fn 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`?
351fn 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.
386fn 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.
438fn 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.
449fn 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.
480fn 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.
524type 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)]
538pub(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.
561pub 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.
576fn 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`.
594fn 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.
612pub(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
669fn 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
680fn 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
690fn iso(p: Vec2) -> Isometry2d {
691 Isometry2d::from_translation(p)
692}
693
694/// Closed polygon outline.
695fn 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.
701fn 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
709pub(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
723fn 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.
740fn 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.
756fn 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.
772pub(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.
781fn 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.
792fn 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.
823fn 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.
837fn 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
857fn 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.
863fn 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.
878fn 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.
891fn 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
902fn 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
1019fn 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.
1076fn 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.
1085fn 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
1107fn 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}