diff --git a/README.md b/README.md index 827b82f2..757ba6ed 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ staged checks pass. | Read | For | | --- | --- | | [Plan](docs/PLAN.md) | Game design, architecture and phased development | +| [Field-kit verification](docs/FIELD_KIT_RESULTS.md) | UI, Survey Log, numbered groups and movement checks | | [Conventions](docs/CONVENTIONS.md) | Code structure and contribution checks | | [Art style](docs/ART_STYLE.md) | Visual identity and Blender asset generation | | [Audio style](docs/AUDIO_STYLE.md) | Sound identity and the synthesis pipeline | diff --git a/docs/ART_STYLE.md b/docs/ART_STYLE.md index 05efc551..bc84c284 100644 --- a/docs/ART_STYLE.md +++ b/docs/ART_STYLE.md @@ -61,3 +61,12 @@ slope, height and world-space noise, so any heightfield is shaded for free. - A `-col` suffix on an object name makes Godot generate a static collider. - Materials are swapped on import by name (`fl_palette`, `fl_terrain`) in `game/presentation/import/model_post_import.gd`. + +## Interface + +Concord field equipment uses steel-blue chamfered plates, subtle outlines and +cyan instrument lamps. Orange marks warnings. `HudStyle`, `PlateStyle` and +`HudTheme` provide the shared controls; `UiTheme` applies the stock-control theme +before screens are built. Chakra Petch supplies body, button and heading weights. +Its SIL Open Font Licence is bundled under `game/assets/fonts/OFL.txt`, included +in exports and displayed in Credits. diff --git a/docs/AUDIO_STYLE.md b/docs/AUDIO_STYLE.md index 046beacb..5b22f31a 100644 --- a/docs/AUDIO_STYLE.md +++ b/docs/AUDIO_STYLE.md @@ -101,7 +101,7 @@ loudness targets and the naming, and says how to add a sound. | `discovery_resolve_biological` | breathy reeds gliding D A B G#, the G# turning up to A in a trill, chirps around it: alive | | `discovery_resolve_antecedent` | the whole motif on bells, chime and reed over a Lydian swell, then its answer A C# rising to the high D (−20, 6.2 s) | | `discovery_resolve_enemy` | the motif bent: D A Bb on ring-modulated Combine saws, the last note sagging G# → G with a growl | - | `ui_codex_open` / `_close` / `_entry` | two marimba notes up / down; the motif's last step B → G# on glass with a paper flick | + | `ui_survey_log_open` / `_close` / `_entry` (files `ui_codex_*.mp3`) | two marimba notes up / down; the motif's last step B → G# on glass with a paper flick | | `ui_intel_tick`, `ui_option_button` | a tiny glass tick on A6; a click with a glass G# above it (spending Intel) | | `field_orbital_scan`, `field_supply_drop`, `field_antecedent_power` | a sonar sweep from orbit with data rain; a falling pod, a landing thump and a D–A chime; reversed bells swelling into a strike on D and G# | | `advisor_discovery`, `advisor_field_option_ready` | Meridian dyads D+A → A+D (the ship heard it too); G#+D twice, lifting into A+D | @@ -1116,9 +1116,9 @@ first, −9 dB after it, 0 dB when all are found), via `MusicDirector.set_layer_ keep it at 0 (explore), −3 (calm), −8 (tension), −4 (aftermath), −6 (victory), silent in combat and defeat. `intel_changed` for the player plays `ui_intel_tick` when Intel rises (the first report is the baseline); `field_option_used` plays `field_` (ids containing -`antecedent`/`scan`/`supply`/`drop` fall back to the three effects); `codex_entry_added` plays -`ui_codex_entry`. Codex open/close and the option button are `Events.ui_feedback(&"codex_open")`, -`&"codex_close"`, `&"option_button"`. Advisor kinds `discovery` (priority 70, throttle 4 s) and +`antecedent`/`scan`/`supply`/`drop` fall back to the three effects); `survey_log_entry_added` plays +`ui_survey_log_entry`. Survey Log open/close and the option button are `Events.ui_feedback(&"survey_log_open")`, +`&"survey_log_close"`, `&"option_button"`. Advisor kinds `discovery` (priority 70, throttle 4 s) and `field_option_ready` (45, 20 s) are raised by gameplay as ordinary `advisor_alert`s. Base loops (`BaseLoops`) sit on the player's entities, at most six, nearest first, hums ranked diff --git a/docs/FIELD_KIT_RESULTS.md b/docs/FIELD_KIT_RESULTS.md new file mode 100644 index 00000000..7d422eb3 --- /dev/null +++ b/docs/FIELD_KIT_RESULTS.md @@ -0,0 +1,74 @@ +# Field kit, Survey Log and control-group verification + +The interface now uses shared steel-blue plates with cut corners, cyan instrument +lamps and Chakra Petch. `HudStyle` and `HudTheme` define the look; `UiTheme` applies +it to stock controls. The font's OFL notice is included in every export and Credits. + +The player-facing discovery journal is the **Survey Log**. Discovery save keys and +the saved `codex` key-binding action remain unchanged so existing progress and +custom keys load. Resource paths for discovery definitions also stay the same. + +## Numbered groups + +- Ctrl/Cmd + 1–9 stores; the plain number recalls; a quick second press centres the camera. +- Alt/Option + number also stores when the browser reserves Ctrl/Cmd for its tabs. +- Shift + number adds the selection, or starts an empty group. +- A badge shows the group number and living count. Click recalls; right-click replaces it. + +Observed in the running Godot game through real mouse/key input: select unit 43, +Ctrl+1 stores it, click unit 44, plain 1 selects 43 again. The browser test stores +multiple units with Alt+1, adds another with Shift+1, deselects and recalls the +same members with plain 1 and the badge. Unit tests also cover Ctrl/Cmd, macOS +Option characters, dead members, saved groups and sticky Shift. + +## Checks observed locally + +| Check | Result | +| --- | --- | +| `tools/check.sh` | Format/lint, 746 gameplay tests (7997 assertions), 416 real-time audio tests (6372 assertions), boot and all 11 mission smoke tests passed | +| Python build/deployment tools | 13 tests passed | +| Chromium hardware gameplay | 24 cases passed | +| Chromium software WebGL, explicit Performance profile | 23 cases passed | +| Screen qualification at 2000×754 | 100% and 130% UI scale passed through title, settings, help, controls, credits, missions, briefing, campaign, star map, Meridian, tech web, loadout, HUD, Survey Log and pause screens | +| Campaign browser route | Launch, save, reload and Continue passed | +| Overlay layering | Tutorial cards hide under pause and Survey Log, retain their state and return afterward; both native checks and real browser input passed | +| Exports | Web, WebDiagnostics and macOS release exports succeeded | + +The hardware/software full browser suites preceded the final modal and narrow-strip +fixes; focused screen/campaign qualification and native geometry checks cover them. +After review, a blocked-segment regression failed before the guard and passed +after it (41 focused native tests, 209 assertions). Three repetitions each of +construction/save recovery and legacy graphics retention passed after their +layout/fixture timing fixes. CI gates the combined release on the latest commit. +At narrow sizes the command strip stays between selection and minimap panels; +its horizontal scrollbar keeps later commands reachable. A real browser check +selects a Fabricator at 1152×648 / 130% UI, stores all nine groups, drags the scrollbar to +Survey Lab and enters placement. Native geometry checks cover the same layout. + +No game balance statistics were changed. One commander test previously required +both retrieval members to die along a particular route through gunfire. A member +can now escape, so that test forms the squad and applies losses explicitly before +checking larger squads, delay, surviving reserves and persistence. + +## Movement measurements and limits + +[ADR 0022](adr/0022-traffic.md) records the traffic rules, reproducible benchmark +and measurements. Contacts use the next integration positions, slow queues still +look for close blockers, idle friends make room, and route shortcuts require a +clear segment. No frame-dependent RVO callback drives ground movement. + +The final stress run settled 202/202 units near their reachable endpoints in +147.6 simulation seconds; 201 were within one body radius and all were within one +body width plus clearance. Its sim tick measured mean 4.50 ms, p95 6.24 ms on M4. +This is a dense-queue stress result, not a browser FPS or exact formation-lock +promise. The old idle-only arrival counter could count a unit waiting to return +to its post, or one that had given up far away; the new report distinguishes them. + +Run the optional browser screen matrix with: + +```sh +WEB_UI_QUALIFY=1 WEB_CAMPAIGN=1 npm test -- ui_style.spec.cjs campaign.spec.cjs +``` + +Run it from `tools/web_tests` after `tools/export.sh Web WebDiagnostics`. +Evidence is retained locally under `build/evidence/field-kit/` and in CI artifacts. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 7180b9a5..7c934e88 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -55,7 +55,8 @@ world's tick). 2.2 ms). 3. **Tell the navigation server only what changed.** Units set their RVO position, velocity and priority only when they differ from the last value sent: most units - stand still most of the time. + stand still most of the time. (The RVO agents have since been replaced by + Traffic, ADR 0022.) 4. **Quieter signals.** A weapon re-announces its aim only when the aim point moved more than 0.2 m (the visual eases toward it anyway). 5. **Skip idle systems.** The stealth pass does nothing when no unit hides and no @@ -91,3 +92,12 @@ cut (~40): 490–710 ms in the middle of play. `NavmeshPathService.prepare_flood now does that while the landing loads, so a switch only applies the cuts made since. Path searches may visit up to 65 536 polygons (the server's default of 4096 cut long detours short), which costs more only for long or unreachable targets, once per order. + +## Ground traffic and arrival accuracy (2026-11-15) + +Ground avoidance now runs on simulation ticks (ADR 0022). See +[traffic measurements](adr/0022-traffic.md) for the 26/64/202-body results and the +arrival definition. In accelerated headless runs the benchmark reports simulation +seconds; its frame monitor values are not real-time rendering FPS. Arrival also +waits for idle units to finish returning to their posts and verifies proximity to +the path endpoint, rather than treating every stopped order as success. diff --git a/docs/PLAN.md b/docs/PLAN.md index af586393..4708ef45 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -17,7 +17,7 @@ Section 9 records the decisions taken with the project owner. 2. **Landing.** Your dropship, the Lander, sets down and *becomes your HQ*. Build a base, harvest, produce units. 3. **Explore.** The map is full of things the orbital scan could not resolve. Scanning them earns **Intel** and often changes the mission: a shortcut, a resource bonus, a dormant machine, a weakness in the enemy base. 4. **Resolve the objective** — which is not always "destroy the enemy". -5. **Return to orbit** with Intel, artefacts and codex entries. New route options open. +5. **Return to orbit** with Intel, artefacts and Survey Log entries. New route options open. **What makes it its own game: Intel is the third resource, and you can only get it by looking.** Alloy and Flux come from harvesting. Intel comes only from discovery. It is spent two ways: @@ -77,7 +77,7 @@ Three knowledge states per map cell: **charted** (orbital scan: terrain shape on | Antecedent | Scanning ruins, recovering caches | Tech-web branches that cannot be bought any other way | | Enemy | Observing Combine structures unseen | Their build state, patrol routes, a weak point | -Every discovery writes a short **codex** entry. Larger finds are multi-step: a ruin points to a second site, which needs a unit you may not have yet. Some cannot be completed on the first visit, which is a reason to return to a planet. +Every discovery writes a short **Survey Log** entry. Larger finds are multi-step: a ruin points to a second site, which needs a unit you may not have yet. Some cannot be completed on the first visit, which is a reason to return to a planet. ### 2.5 Planets @@ -135,7 +135,7 @@ farlanding/ campaign/ Star map, ship, tech web, persistent state presentation/ Camera, selection visuals, VFX, fog rendering audio/ Audio service, music director, sound-event map - ui/ HUD, menus, codex + ui/ HUD, menus, Survey Log data/ .tres definitions: units, weapons, techs, discoveries, planets, missions, sounds assets/ Exported models, textures, audio (generated — never hand-edited) maps/ @@ -216,7 +216,7 @@ Sound gets its own track in every phase rather than a pass at the end, because i | Movement | Engine/servo loops per chassis, footfalls for walkers | | Buildings | Placement, construction loop, completion, idle hum, production, destruction | | World | Planet ambience bed, positional spot sounds, weather, hazard warnings | -| Discovery | Signal pulse, scan loop, resolve stingers per type, codex entry | +| Discovery | Signal pulse, scan loop, resolve stingers per type, Survey Log entry | | Stealth | Suspicion rising, alert, all-clear | | Music | Adaptive score per planet (below), ship theme, victory and defeat | @@ -271,8 +271,8 @@ Each phase ends in something playable and has all three tracks. A phase is done - **Done when:** a full Conquest match against the AI is winnable, losable and fun. *Milestone: the classic loop works.* ### Phase 4 — Exploration and Intel -- **Code:** orbital-scan layer, signals, Surveyor scanning, discovery definitions and payoffs, Intel, Survey Lab field options, codex, Custodians. -- **Art:** discovery sites, Antecedent ruins kit, scan effects, codex illustrations. +- **Code:** orbital-scan layer, signals, Surveyor scanning, discovery definitions and payoffs, Intel, Survey Lab field options, Survey Log, Custodians. +- **Art:** discovery sites, Antecedent ruins kit, scan effects, Survey Log illustrations. - **Audio:** signal pulse, scan loop, resolve stingers, the Trail motif, explore music. - **Done when:** playtesters detour to find out what a `?` is without being told to. *Milestone: the game has its identity.* diff --git a/docs/PLAYER_GUIDE.md b/docs/PLAYER_GUIDE.md index fe0b0610..79c7caee 100644 --- a/docs/PLAYER_GUIDE.md +++ b/docs/PLAYER_GUIDE.md @@ -7,7 +7,7 @@ Detailed controls and mission rules follow, including planet-specific mechanics. shows the route of landings: hover one for its orbital scan (planet, rule, mission type, unresolved `?` signals), click an open one and press LAUNCH. A won landing banks the Intel you still hold when it ends (a lost one banks nothing, but its finds stay in -the codex) and opens the landings it leads to; the route branches, and taking one side +the Survey Log) and opens the landings it leads to; the route branches, and taking one side closes the other. On the Meridian (MERIDIAN on the star map) spend banked Intel on the tech web: clear the Survey Lab, Lancer, Sentry and Arc, upgrade Haulers, scanners and optics; some techs need an Antecedent find from an earlier landing. Pick a loadout @@ -40,11 +40,19 @@ Field notes explain each new thing the first time you meet it. | Left click (classic scheme) | select, and command by context: move, attack, harvest, scan, build, carry, rally | | Right click (classic scheme) | deselect, cancel placement or aiming | | Shift | add to selection, queue orders | -| Ctrl+1–9 / 1–9 | store / recall a control group | +| Alt+1–9 (Option on a Mac) or Ctrl/Cmd+1–9 | make the selection a control group (browsers keep Ctrl/Cmd+number, and on Linux Alt+number, for their tabs) | +| Shift+1–9 | add the selection to that group, or start it: works in every browser | +| 1–9 | select the group again · twice: centre the camera on it | | WASD, arrows, screen edge, middle drag | pan · wheel: zoom · Q/E: turn | -| C | codex · F1: all controls · F3: debug overlay | +| C | Survey Log · F1: all controls · F3: debug overlay | | F5 / F9 (native), K / L (Web) | quicksave / quickload | -| Esc or P | pause menu: resume, save, load, settings, how to play, restart, quit | +| Esc or P | pause menu: resume, save, load, settings, how to play, controls, restart, quit | + +Each control group shows as a badge above the selection panel (bottom left): "1 · 5" is +group 1 with five units. Click a badge to select the group (twice to centre on it), +right-click it to make the current selection that group; it +lights up when the group is stored or added to and goes away when its last unit is lost. +**Controls** (title screen and pause menu) lists every mouse button and key in one page. These are the default keys: every one can be rebound per mouse scheme under Settings > KEYS (a key already in use is named, and pressing it again swaps the two). @@ -62,3 +70,7 @@ resolution scale, "Reset hints"), ACCESSIBILITY (team colour palettes for red-gr and blue-yellow colour blindness, subtitles for the Advisor and their size, interface size 100/115/130%, fewer flashes, sticky Shift, game speed of single missions) and KEYS. **How to play** and **Credits** are on the title screen. + +On narrow windows or larger interface scale, the command strip scrolls sideways +to keep the minimap and selection information clear. Drag its scrollbar or use +horizontal scrolling to reach later build and production options. diff --git a/docs/WEB_DEVELOPMENT.md b/docs/WEB_DEVELOPMENT.md index 23eb8186..b1f18bd5 100644 --- a/docs/WEB_DEVELOPMENT.md +++ b/docs/WEB_DEVELOPMENT.md @@ -50,6 +50,7 @@ npm ci npx playwright install chromium npm test WEB_BROAD=1 npm test +WEB_UI_QUALIFY=1 npm test -- ui_style.spec.cjs WEB_AUDIO_QA=1 npm test -- --grep real-mixer WEB_PERFORMANCE=1 npm test -- --grep 233-unit WEB_BROWSER=firefox npm test diff --git a/docs/adr/0004-unit-navigation.md b/docs/adr/0004-unit-navigation.md index 1fef229b..8bbd4aeb 100644 --- a/docs/adr/0004-unit-navigation.md +++ b/docs/adr/0004-unit-navigation.md @@ -1,6 +1,6 @@ # 0004 — Unit navigation: navmesh + group corridors + server RVO -- Status: accepted +- Status: accepted; decision 3 (server-side RVO) was replaced by ADR 0022 (Traffic) - Date: 2026-11-12 ## Context diff --git a/docs/adr/0009-discovery-and-intel.md b/docs/adr/0009-discovery-and-intel.md index 0fce36e0..425d672c 100644 --- a/docs/adr/0009-discovery-and-intel.md +++ b/docs/adr/0009-discovery-and-intel.md @@ -6,7 +6,7 @@ PLAN §1 and §2.4 make Intel the third resource, earned only by looking: Surveyors scan discovery sites, each discovery type pays out something felt in play, every discovery -writes a codex entry, and Intel is spent at the Survey Lab on field options. Custodians +writes a Survey Log entry, and Intel is spent at the Survey Lab on field options. Custodians (§2.1) guard Antecedent sites. All of it must follow §3.3: data-driven definitions, one command path, sim talks outward only through `Events`, saveable state, and an enemy commander that gains nothing from what the player finds. @@ -17,7 +17,7 @@ commander that gains nothing from what the player finds. | Resource | File | Holds | |---|---|---| -| `DiscoveryDef` | `core/defs/discovery_def.gd`, `data/discoveries/*.tres` | type (`geological`, `biological`, `antecedent`, `enemy`), Intel reward, scan time, radius, `leads_to` (chain), codex title/text, one payoff kind with its numbers, glow colour | +| `DiscoveryDef` | `core/defs/discovery_def.gd`, `data/discoveries/*.tres` | type (`geological`, `biological`, `antecedent`, `enemy`), Intel reward, scan time, radius, `leads_to` (chain), log title/text (`log_title`, `log_text`), one payoff kind with its numbers, glow colour | | `FieldOptionDef` | `core/defs/field_option_def.gd`, `data/field_options/*.tres` | effect (`reveal`, `supply_drop`, `strike`), Intel cost, cooldown, `requires_unlock`, effect numbers | | `UnitDef` additions | `scan_rate`, `scan_range`; `starts_dormant`, `wake_radius`, `guard_radius` | Surveyor scanning; Custodian dormancy | | `BuildingDef.field_options` | `data/buildings/concord_survey_lab.tres` | Options a building offers | @@ -41,8 +41,8 @@ kind is a few lines in `Discovery._apply_payoff()`. anything that ends the order (new order, stop, death, being pushed aside); with no scanner left the progress is lost. Several scanners add up. - `Discovery` (`sim/systems/discovery/discovery.gd`, service `discovery`) is a SimWorld - child ticked after units: it resolves sites (Intel, codex, `discovery_made`, - `codex_entry_added`, payoff, chain), runs heal fields and the player's view of sites. + child ticked after units: it resolves sites (Intel, Survey Log, `discovery_made`, + `survey_log_entry_added`, payoff, chain), runs heal fields and the player's view of sites. `FieldOptions` (same folder) keeps unlocks and cooldowns per faction and applies effects; `FieldOptionCommand` (receiver: an operational lab offering the option) is the only way to use one. `field_option_used` fires on use, the Advisor's @@ -78,8 +78,9 @@ commands and when a click selects or deselects). The cursor is drawn in code ## Consequences - Discoveries are cheap to add; payoff kinds are deliberately few and need code. -- A scan in progress is not saved (it starts over); sites, the codex, unlocks, cooldowns - and heal fields are. Reveals that follow an entity end on load. +- A scan in progress is not saved (it starts over); sites, the Survey Log (saved under + the key `codex`), unlocks, cooldowns and heal fields are. Reveals that follow an + entity end on load. - The Custodian faction joins the vision round robin, so with three factions each grid updates about 3.3 times a second instead of 5. Acceptable at this scale; revisit if the fog feels sluggish. diff --git a/docs/adr/0012-campaign-layer.md b/docs/adr/0012-campaign-layer.md index d861da40..8c552b54 100644 --- a/docs/adr/0012-campaign-layer.md +++ b/docs/adr/0012-campaign-layer.md @@ -41,7 +41,7 @@ Phase 8 brings Thalassa's map and tide. `CampaignState` is a pure `RefCounted` over its `CampaignDef`: banked `intel`, owned `techs`, `opened` / `won` / `closed` nodes, per-node `results` (attempts, won, Intel -banked, seconds), `discoveries` (the campaign codex), `loadout` (slot → option) and +banked, seconds), `discoveries` (the campaign Survey Log), `loadout` (slot → option) and `current_node`. Rules: - A node is **open** when opened (start node, or led to by a won node), not won or diff --git a/docs/adr/0022-traffic.md b/docs/adr/0022-traffic.md new file mode 100644 index 00000000..c67c73ab --- /dev/null +++ b/docs/adr/0022-traffic.md @@ -0,0 +1,125 @@ +# 0022 — Traffic: how ground units pass each other + +- Status: accepted (replaces decision 3 of ADR 0004, server-side RVO) +- Date: 2026-11-15 + +## Context + +Units drove into each other and did not pass naturally. ADR 0004 used the +navigation server's RVO agents for avoidance. Reading the code and playing showed +why that was not enough: + +- A standing unit had the highest priority and never moved, so a mover in a narrow + place pressed against it until it gave up. +- Avoidance was the only thing keeping bodies apart. When it failed, units + overlapped; nothing separated them again. +- The safe velocity came back through a server callback tied to physics frames, + one sim tick late, with a 0.8 s look-ahead. Fast units reacted too late and + swerved at the last moment. +- The safe velocity was a sideways slide the unit's facing knew nothing about. +- None of it ran in the tests (the test `PathService` has no navigation map), so + passing behaviour had no test at all, and the outcome depended on frame timing. + +## Decision + +Avoidance moves into the simulation as one system, `Traffic` +(`game/sim/systems/navigation/traffic.gd`), and the server-side agents and +obstacles are removed. + +1. **One pass per sim tick, before the units move.** `SimWorld` calls + `Traffic.solve()`. It reads each ground unit's `TrafficBody` (position, intended + velocity, radius, faction, whether it moves, whether it would step aside) and + writes four answers back. `Locomotion` applies them in its own tick. +2. **Steer.** For each moving unit and each body that it would touch within + `HORIZON` (2 s), or already within 2 m of contact, a sideways pull away from where the other body will be at the + closest moment. The pull is stronger the sooner and the nearer the meeting. + - Oncoming traffic adds a pull to the right, so two units meeting head-on both + keep right. + - The smaller unit bends more; a unit passing a standing body does all of it. + - A unit ahead that drives the same way at 70 % or more of our top speed is + followed, not passed. + - Whether something is in the way is judged by the unit's *wish* (straight along + its path), not by its bent velocity. Otherwise bending away removes the reason + to bend and the unit oscillates. + - The pull changes the travel direction inside `Mover.plan()`, so the body turns + toward where it goes. `Locomotion` eases it in and out. +3. **Speed cap.** A unit brakes for a body in its lane, using half its braking + power and stopping 0.3 m short, because the order to brake arrives a tick late. + Moving traffic keeps additional clearance; a parked neighbour merely beside + the lane is steered around without needlessly braking. +4. **Step aside.** A standing unit with nothing to do steps sideways out of the + line of a friend that would hit it within 1.2 s, and walks back to its post once + nothing has driven by for 2 s. A unit with orders, a target or a cloak holds its + ground, and so does every enemy. +5. **Push.** Bodies predicted to overlap after the pending movement step are moved apart. + The push is applied after integration, matching the positions it resolves. Whoever is freer to + move makes all the room: a moving body for a standing one, a standing body with + nothing to do for one that holds its ground. A body that holds its ground (it + works, scans or fires where it stands) is never shifted, so two of them working + on the same spot stay as they are. +6. **Walkable ground wins.** A give-way or return step requires its whole straight + segment to be walkable, not only its endpoint. A push or a steered move that would leave the walk + grid is not made; the unit then follows its path alone for half a second. +7. Flying units stay out (the `FlightSystem` keeps them apart, ADR 0016). + +Formations already hand out slots so that paths do not cross (`Formation.assign`), +so that part needed no change. Groups retain each unit's own speed: faster units queue behind or pass slower +ones. Nearby path corners are skipped when the next leg is directly walkable; +a unit does not have to touch the shared funnel point after clearing an obstacle. +Traffic waiting consumes the stuck budget slowly, and a blocked unit retries its +route instead of declaring success several vehicle lengths short of its slot. + +## Results + +`game/tests/test_traffic.gd` (14 tests, straight-line paths, vehicle-like units of +radius 1.2 m at 6 m/s). Without Traffic two units meeting head-on end up 1.9 m +inside each other. With it, in every case no two bodies are ever more than 0.1 m +inside each other and every unit arrives: + +- two units head-on (both pass on the right); +- two columns of four head-on; +- two units crossing at right angles; +- a standing friend in the way (it steps aside and walks back); +- a unit holding its ground, and an enemy, in the way (driven around, not moved); +- a fast small unit behind a slow large one; +- two units spawned on top of each other (pushed apart); +- the same inputs twice give the same positions. + +Navigation checks on Kessel Proving, Apple M4, headless, 10 Hz simulation: + +| Bodies | 95% near destination / all settled | Tick mean / p95 / max | +| --- | --- | --- | +| 26 | 44.9 s / 52.8 s | 0.67 / 1.07 / 1.61 ms | +| 64 | 63.1 s / 66.9 s | 1.38 / 2.13 / 2.57 ms | +| 202 | 141.1 s / 147.6 s | 4.50 / 6.24 / 8.60 ms | + +Arrival means no active order, path, movement or pending return to an idle post, +within one body width plus clearance of the assigned reachable endpoint. The +202-body run finished with all 202 in that area, 201 within one body radius. +The 64-body run finished with all 64 within one radius. This distinguishes actual +arrival from giving up far away, and from briefly stopping while turning. + +These are simulation seconds, so `--fixed-fps 60` can accelerate headless runs; +frame timing in that mode is not real-time FPS. Historical RVO numbers (mean +3.33 ms / p95 5.61 ms, all 'arrived' at 51.3 s) used a weaker idle-only completion +counter and allowed overlap; they are not a like-for-like throughput comparison. +Dense physical queues take longer than a ghosting group. These measurements do +not establish a frame-rate guarantee for the rendered browser game. + +Reproduce with `godot --headless --fixed-fps 60 --path game +res://tests/bench/bench_navigation.tscn -- --units=200 --seconds=240 --details`. +The report records strict one-radius accuracy separately and explains its arrival +threshold. Normal traffic tests also cover slow queues making room and taking a +visible next route leg while retaining corners blocked by a wall. + +## Consequences + +- Passing is deterministic and runs in the tests and the balance runs the same as + in play. +- `PathService.get_avoidance_map()` and the RVO obstacles over buildings are gone. + Buildings were already cut out of the navmesh and the walk grid. +- Cost grows with the number of *moving* units and how many bodies are within + their look-ahead (at most 14 m). If a much larger battle makes it show, the first + step is to solve only every second tick for units far from any other. +- A save keeps a step aside in progress and the post to walk back to (Locomotion + save version 3). diff --git a/docs/media/browser-kessel.png b/docs/media/browser-kessel.png index d3bc0855..491e1b68 100644 Binary files a/docs/media/browser-kessel.png and b/docs/media/browser-kessel.png differ diff --git a/game/assets/fonts/ChakraPetch-Medium.ttf b/game/assets/fonts/ChakraPetch-Medium.ttf new file mode 100644 index 00000000..2e2d8da5 Binary files /dev/null and b/game/assets/fonts/ChakraPetch-Medium.ttf differ diff --git a/game/assets/fonts/ChakraPetch-Medium.ttf.import b/game/assets/fonts/ChakraPetch-Medium.ttf.import new file mode 100644 index 00000000..ac97191c --- /dev/null +++ b/game/assets/fonts/ChakraPetch-Medium.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dte7co0h0a4mr" +path="res://.godot/imported/ChakraPetch-Medium.ttf-78a016a08515eee6e20491208eeba7e4.fontdata" + +[deps] + +source_file="res://assets/fonts/ChakraPetch-Medium.ttf" +dest_files=["res://.godot/imported/ChakraPetch-Medium.ttf-78a016a08515eee6e20491208eeba7e4.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/game/assets/fonts/ChakraPetch-Regular.ttf b/game/assets/fonts/ChakraPetch-Regular.ttf new file mode 100644 index 00000000..c1167ce4 Binary files /dev/null and b/game/assets/fonts/ChakraPetch-Regular.ttf differ diff --git a/game/assets/fonts/ChakraPetch-Regular.ttf.import b/game/assets/fonts/ChakraPetch-Regular.ttf.import new file mode 100644 index 00000000..9d3f4b6e --- /dev/null +++ b/game/assets/fonts/ChakraPetch-Regular.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://ddh628q0xmbce" +path="res://.godot/imported/ChakraPetch-Regular.ttf-da050ac5f5f58524f1048d8edddf525b.fontdata" + +[deps] + +source_file="res://assets/fonts/ChakraPetch-Regular.ttf" +dest_files=["res://.godot/imported/ChakraPetch-Regular.ttf-da050ac5f5f58524f1048d8edddf525b.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/game/assets/fonts/ChakraPetch-SemiBold.ttf b/game/assets/fonts/ChakraPetch-SemiBold.ttf new file mode 100644 index 00000000..802d5987 Binary files /dev/null and b/game/assets/fonts/ChakraPetch-SemiBold.ttf differ diff --git a/game/assets/fonts/ChakraPetch-SemiBold.ttf.import b/game/assets/fonts/ChakraPetch-SemiBold.ttf.import new file mode 100644 index 00000000..01fb92c7 --- /dev/null +++ b/game/assets/fonts/ChakraPetch-SemiBold.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dqeqfwbhftt4i" +path="res://.godot/imported/ChakraPetch-SemiBold.ttf-87a6da42122dc6ad3132f6ee6c79d8d9.fontdata" + +[deps] + +source_file="res://assets/fonts/ChakraPetch-SemiBold.ttf" +dest_files=["res://.godot/imported/ChakraPetch-SemiBold.ttf-87a6da42122dc6ad3132f6ee6c79d8d9.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/game/assets/fonts/OFL.txt b/game/assets/fonts/OFL.txt new file mode 100644 index 00000000..4b4c452c --- /dev/null +++ b/game/assets/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Chakra Petch Project Authors (https://github.com/m4rc1e/Chakra-Petch.git) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/game/audio/audio_service.gd b/game/audio/audio_service.gd index 7b857c88..a5e5a75f 100644 --- a/game/audio/audio_service.gd +++ b/game/audio/audio_service.gd @@ -10,7 +10,7 @@ ## AudioEventRouter (Events -> sounds, Advisor alert queue), MovementLoops, ## BaseLoops (construction, production, mining, building hum), the ## MusicDirector, the SignalPulses (discovery-site pulses and scan loops) and -## the DiscoverySoundRouter (resolve phrases, Intel, field options, codex). +## the DiscoverySoundRouter (resolve phrases, Intel, field options, Survey Log). ## While a discovery resolves, a BusDucker briefly lowers music, ambience and ## effects. Phase 5 adds the StealthSoundRouter (alert stingers, spotted, ## cloaks, the stealth music mood), SuspicionTones (the watchers' rising tone) diff --git a/game/audio/discovery_cues.gd b/game/audio/discovery_cues.gd index 932597e7..b433e61f 100644 --- a/game/audio/discovery_cues.gd +++ b/game/audio/discovery_cues.gd @@ -19,7 +19,7 @@ const SITES_GROUP: StringName = &"discovery_sites" const PULSE: StringName = &"signal_pulse" const SCAN_LOOP: StringName = &"scan_loop" const SCAN_CUT: StringName = &"scan_interrupted" -const CODEX_ENTRY: StringName = &"ui_codex_entry" +const SURVEY_LOG_ENTRY: StringName = &"ui_survey_log_entry" const INTEL_TICK: StringName = &"ui_intel_tick" const ENEMY_INTEL: StringName = &"discovery_enemy_intel" const ANTECEDENT_SWELL: StringName = &"mus_swell_antecedent" diff --git a/game/audio/discovery_sound_router.gd b/game/audio/discovery_sound_router.gd index b8b4606e..84502fb8 100644 --- a/game/audio/discovery_sound_router.gd +++ b/game/audio/discovery_sound_router.gd @@ -16,9 +16,9 @@ extends Node ## the last enemy gain is kept, so the ending can tell an out-surveyed ## defeat (`enemy_gained_within`). ## - field_option_used (player faction): the option's effect `field_`. -## - codex_entry_added: `ui_codex_entry`. -## Codex open/close and the option button are interface feedback -## (`Events.ui_feedback(&"codex_open")` -> `ui_codex_open`, by the naming rule). +## - survey_log_entry_added: `ui_survey_log_entry`. +## Survey Log open/close and the option button are interface feedback +## (`Events.ui_feedback(&"survey_log_open")` -> `ui_survey_log_open`, by the naming rule). ## Resolve phrases shorter than this still duck for this long. const MIN_DUCK_SECONDS: float = 1.5 @@ -45,7 +45,7 @@ func _ready() -> void: Events.discovery_made.connect(handle_discovery_made) Events.intel_changed.connect(handle_intel_changed) Events.field_option_used.connect(handle_field_option_used) - Events.codex_entry_added.connect(handle_codex_entry_added) + Events.survey_log_entry_added.connect(handle_survey_log_entry_added) Events.mission_started.connect(_on_mission_started) refresh_trail() @@ -77,8 +77,8 @@ func handle_field_option_used(option: Resource, faction: int, _at: Vector3 = Vec _play(DiscoveryCues.field_option_events(option)) -func handle_codex_entry_added(_entry: Resource) -> void: - _play([DiscoveryCues.CODEX_ENTRY]) +func handle_survey_log_entry_added(_entry: Resource) -> void: + _play([DiscoveryCues.SURVEY_LOG_ENTRY]) ## Recomputes the trail layer from the sites in the tree. `just_resolved` diff --git a/game/campaign/campaign_state.gd b/game/campaign/campaign_state.gd index 37fc43e3..267de19c 100644 --- a/game/campaign/campaign_state.gd +++ b/game/campaign/campaign_state.gd @@ -31,7 +31,7 @@ var won: Array[StringName] = [] var closed: Array[StringName] = [] ## Per node id: { attempts, won, intel_banked, seconds }. var results: Dictionary[StringName, Dictionary] = {} -## Discovery ids made on any landing (the campaign's codex), in order. +## Discovery ids made on any landing (the campaign's Survey Log), in order. var discoveries: Array[StringName] = [] ## Loadout: slot id -> option id. var loadout: Dictionary[StringName, StringName] = {} diff --git a/game/core/defs/carryover_def.gd b/game/core/defs/carryover_def.gd index 661943b2..fb28262e 100644 --- a/game/core/defs/carryover_def.gd +++ b/game/core/defs/carryover_def.gd @@ -1,10 +1,10 @@ class_name CarryoverDef extends Resource ## What a discovery made on one landing changes on the landings after it (ADR 0012): -## the codex remembers it, and every later landing starts with `effects`. +## the Survey Log remembers it, and every later landing starts with `effects`. @export var id: StringName = &"" -## The discovery id that must be in the campaign's codex. +## The discovery id that must be in the campaign's Survey Log. @export var discovery: StringName = &"" ## One line for the briefing and the Meridian. @export var description: String = "" diff --git a/game/core/defs/discovery_def.gd b/game/core/defs/discovery_def.gd index fecf4752..40d84d36 100644 --- a/game/core/defs/discovery_def.gd +++ b/game/core/defs/discovery_def.gd @@ -1,7 +1,7 @@ class_name DiscoveryDef extends Resource ## Data definition of one discovery: what a site on the map turns out to be once a -## Surveyor has scanned it, what it pays out and what it writes into the codex +## Surveyor has scanned it, what it pays out and what it writes into the Survey Log ## (PLAN 2.4). One `.tres` per discovery; the site entity is a DiscoverySite. ## The four discovery types. @@ -11,7 +11,7 @@ const ANTECEDENT: StringName = &"antecedent" const ENEMY: StringName = &"enemy" ## Payoffs. -## Nothing beyond Intel and the codex entry. +## Nothing beyond Intel and the log entry. const PAYOFF_NONE: StringName = &"none" ## A resource node (`payoff_node`) appears at the site, offset by `payoff_offset`. const PAYOFF_DEPOSIT: StringName = &"deposit" @@ -47,9 +47,9 @@ const PAYOFF_FORECAST: StringName = &"forecast" ## Id of the discovery whose site this one charts when it is resolved (a chain); ## that site stays hidden and cannot be scanned until then. @export var leads_to: StringName = &"" -@export_group("Codex") -@export var codex_title: String = "" -@export_multiline var codex_text: String = "" +@export_group("Survey Log") +@export var log_title: String = "" +@export_multiline var log_text: String = "" @export_group("Payoff") ## One of the PAYOFF_* kinds. @export var payoff: StringName = PAYOFF_NONE diff --git a/game/core/defs/planet_rule.gd b/game/core/defs/planet_rule.gd index d18de677..7b58faa0 100644 --- a/game/core/defs/planet_rule.gd +++ b/game/core/defs/planet_rule.gd @@ -6,7 +6,7 @@ extends Resource ## Resource and a system script; the engine does not change (ADR 0011). @export var id: StringName = &"" -## What the rule does, in one line (briefing, codex). +## What the rule does, in one line (briefing, Survey Log). @export_multiline var summary: String = "" ## The PlanetRuleSystem subclass that runs this rule on a mission's sim clock. @export var system: Script diff --git a/game/core/defs/unit_def.gd b/game/core/defs/unit_def.gd index 44b8b0d3..c963bc3f 100644 --- a/game/core/defs/unit_def.gd +++ b/game/core/defs/unit_def.gd @@ -6,7 +6,7 @@ extends EntityDef @export_range(0.0, 100.0, 0.1, "suffix:m/s") var move_speed: float = 5.0 @export_range(0.0, 1440.0, 1.0, "suffix:°/s") var turn_speed: float = 360.0 @export_range(0.0, 200.0, 0.5, "suffix:m") var vision_range: float = 20.0 -## Body radius for avoidance, formation spacing and click picking. +## Body radius for passing other units, formation spacing and click picking. @export_range(0.1, 20.0, 0.05, "suffix:m") var radius: float = 0.5 ## Also used for braking. @export_range(0.1, 200.0, 0.1, "suffix:m/s²") var acceleration: float = 10.0 diff --git a/game/core/events.gd b/game/core/events.gd index de5bb727..e1b91a4d 100644 --- a/game/core/events.gd +++ b/game/core/events.gd @@ -88,8 +88,8 @@ signal intel_changed(faction: int, intel: int) ## A field option bought at the Survey Lab took effect at `at`. `option` is its definition. signal field_option_used(option: Resource, faction: int, at: Vector3) -## The player's codex gained an entry. `entry` is the DiscoveryDef it describes. -signal codex_entry_added(entry: Resource) +## The player's Survey Log gained an entry. `entry` is the DiscoveryDef it describes. +signal survey_log_entry_added(entry: Resource) ## A mission objective became known to the player. `objective` is an Objective: ## `id`, `title`, `kind` (&"primary", &"secondary", &"hidden"), `state` diff --git a/game/core/key_bindings.gd b/game/core/key_bindings.gd index e72751d5..ff1e2217 100644 --- a/game/core/key_bindings.gd +++ b/game/core/key_bindings.gd @@ -40,7 +40,8 @@ const ACTIONS: Array[Array] = [ [&"pause_menu", "Pause menu (Esc also works)", GAME, "k80"], [&"quicksave", "Quicksave", GAME, "k4194336"], [&"quickload", "Quickload", GAME, "k4194340"], - [&"codex", "Codex", GAME, "k67"], + # The Survey Log. "codex" is the saved action id (settings.cfg key overrides): keep it. + [&"codex", "Survey Log", GAME, "k67"], [&"controls_help", "Controls panel", GAME, "k4194332"], [&"debug_overlay", "Debug overlay", GAME, "k4194334"], ] @@ -238,12 +239,30 @@ static func has_action(action: StringName) -> bool: ## The control group (1..9) whose key `event` is, or 0. Modifiers do not matter -## (Ctrl + the key stores the group). +## (Ctrl/Cmd or Alt/Option + the key stores the group, Shift + the key adds to it). +## Option on macOS types another character ("1" becomes "¡"), so a group bound by +## label also matches by the key's place when Alt is held. static func group_of(event: InputEvent) -> int: for group: int in range(1, GROUP_COUNT + 1): var action: StringName = StringName("control_group_%d" % group) if InputMap.has_action(action) and event.is_action(action): return group + var key: InputEventKey = event as InputEventKey + if key == null or not key.alt_pressed or key.physical_keycode == KEY_NONE: + return 0 + var placed: Key = _keycode("p%d" % key.physical_keycode) + for group: int in range(1, GROUP_COUNT + 1): + var action: StringName = StringName("control_group_%d" % group) + if not InputMap.has_action(action): + continue + for bound: InputEvent in InputMap.action_get_events(action): + var bound_key: InputEventKey = bound as InputEventKey + if bound_key == null: + continue + if bound_key.keycode != KEY_NONE and bound_key.keycode == placed: + return group + if bound_key.physical_keycode == key.physical_keycode: + return group return 0 diff --git a/game/data/campaign/techs/antecedent_lens.tres b/game/data/campaign/techs/antecedent_lens.tres index 420f5bc9..76a3f181 100644 --- a/game/data/campaign/techs/antecedent_lens.tres +++ b/game/data/campaign/techs/antecedent_lens.tres @@ -12,7 +12,7 @@ target = &"antecedent_power" script = ExtResource("e0") id = &"antecedent_lens" title = "Antecedent Lens" -description = "Built from the trail ruin's resonance map. The Beacon Lance field option is ready from the start of every landing. Needs the Kessel trail ruin in the codex." +description = "Built from the trail ruin's resonance map. The Beacon Lance field option is ready from the start of every landing. Needs the Kessel trail ruin in the Survey Log." branch = &"survey" intel_cost = 265 requires = Array[StringName]([&"deep_scan"]) diff --git a/game/data/campaign/techs/cache_alloys.tres b/game/data/campaign/techs/cache_alloys.tres index c8afa578..3c327a3d 100644 --- a/game/data/campaign/techs/cache_alloys.tres +++ b/game/data/campaign/techs/cache_alloys.tres @@ -13,7 +13,7 @@ factor = 1.15 script = ExtResource("e0") id = &"cache_alloys" title = "Cache Alloys" -description = "Plating cast from the sealed cache's alloy: every unit and building has 15% more health. Needs the Kessel sealed cache in the codex." +description = "Plating cast from the sealed cache's alloy: every unit and building has 15% more health. Needs the Kessel sealed cache in the Survey Log." branch = &"industry" intel_cost = 310 requires = Array[StringName]([&"rapid_drills"]) diff --git a/game/data/discoveries/emberfall_ash_lichen.tres b/game/data/discoveries/emberfall_ash_lichen.tres index 485f9cd2..bf8f4a76 100644 --- a/game/data/discoveries/emberfall_ash_lichen.tres +++ b/game/data/discoveries/emberfall_ash_lichen.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 7.0 radius = 3.5 leads_to = &"" -codex_title = "Ash lichen" -codex_text = "Black lichen that feeds on the heat of the ash. Broken, it weeps a resin that seals scorched plating." +log_title = "Ash lichen" +log_text = "Black lichen that feeds on the heat of the ash. Broken, it weeps a resin that seals scorched plating." payoff = &"heal_field" payoff_radius = 16.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/emberfall_combine_vent_survey.tres b/game/data/discoveries/emberfall_combine_vent_survey.tres index af673fb4..9e8d6c86 100644 --- a/game/data/discoveries/emberfall_combine_vent_survey.tres +++ b/game/data/discoveries/emberfall_combine_vent_survey.tres @@ -13,8 +13,8 @@ intel_reward = 40 scan_time = 8.0 radius = 5.0 leads_to = &"" -codex_title = "Combine vent survey" -codex_text = "Combine markers around a cooling vent, with the rota of the rigs that come to tend their Siphons. It names where every Combine machine was posted." +log_title = "Combine vent survey" +log_text = "Combine markers around a cooling vent, with the rota of the rigs that come to tend their Siphons. It names where every Combine machine was posted." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/emberfall_obsidian_flow.tres b/game/data/discoveries/emberfall_obsidian_flow.tres index 8690d5b7..826f3fd3 100644 --- a/game/data/discoveries/emberfall_obsidian_flow.tres +++ b/game/data/discoveries/emberfall_obsidian_flow.tres @@ -14,8 +14,8 @@ intel_reward = 45 scan_time = 10.0 radius = 5.0 leads_to = &"" -codex_title = "Obsidian flow" -codex_text = "An old flow of black glass that has sealed a vent. Scanning it cracks the seal: a quiet Flux vent opens beside it, one that does not erupt." +log_title = "Obsidian flow" +log_text = "An old flow of black glass that has sealed a vent. Scanning it cracks the seal: a quiet Flux vent opens beside it, one that does not erupt." payoff = &"deposit" payoff_node = ExtResource("n_node") payoff_offset = Vector3(9, 0, 0) diff --git a/game/data/discoveries/emberfall_seismic_fissure.tres b/game/data/discoveries/emberfall_seismic_fissure.tres index 037a46ed..5b0ded99 100644 --- a/game/data/discoveries/emberfall_seismic_fissure.tres +++ b/game/data/discoveries/emberfall_seismic_fissure.tres @@ -13,8 +13,8 @@ intel_reward = 45 scan_time = 9.0 radius = 5.0 leads_to = &"" -codex_title = "Seismic fissure" -codex_text = "A crack that hums with the caldera's pulse. Read for a few minutes, it tells which vent is filling fastest: the gauge names the next to erupt, and the vent's own gauge says NEXT." +log_title = "Seismic fissure" +log_text = "A crack that hums with the caldera's pulse. Read for a few minutes, it tells which vent is filling fastest: the gauge names the next to erupt, and the vent's own gauge says NEXT." payoff = &"forecast" payoff_seconds = 420.0 color = Color(0.95, 0.5, 0.25, 1) diff --git a/game/data/discoveries/emberfall_slag_cache.tres b/game/data/discoveries/emberfall_slag_cache.tres index c156107a..80c4c5ea 100644 --- a/game/data/discoveries/emberfall_slag_cache.tres +++ b/game/data/discoveries/emberfall_slag_cache.tres @@ -14,8 +14,8 @@ intel_reward = 70 scan_time = 10.0 radius = 1.5 leads_to = &"" -codex_title = "Slag cache" -codex_text = "An Antecedent store sealed in glassy slag. Cracked open, it spills worked alloy across the plain." +log_title = "Slag cache" +log_text = "An Antecedent store sealed in glassy slag. Cracked open, it spills worked alloy across the plain." payoff = &"deposit" payoff_node = ExtResource("n_node") payoff_offset = Vector3(0, 0, 9) diff --git a/game/data/discoveries/emberfall_trail_furnace.tres b/game/data/discoveries/emberfall_trail_furnace.tres index e452b65b..5f24d063 100644 --- a/game/data/discoveries/emberfall_trail_furnace.tres +++ b/game/data/discoveries/emberfall_trail_furnace.tres @@ -13,8 +13,8 @@ intel_reward = 110 scan_time = 16.0 radius = 5.5 leads_to = &"" -codex_title = "The furnace under the ash" -codex_text = "The same pale stone as the vault on Thalassa, half buried in ash and still warm. It was built to draw on the caldera, and its core answers the Survey Lab. The trail runs on, outward." +log_title = "The furnace under the ash" +log_text = "The same pale stone as the vault on Thalassa, half buried in ash and still warm. It was built to draw on the caldera, and its core answers the Survey Lab. The trail runs on, outward." payoff = &"unlock_option" unlocks_option = &"antecedent_power" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/hollow_combine_survey_rig.tres b/game/data/discoveries/hollow_combine_survey_rig.tres index 28ac4831..2d9d6a07 100644 --- a/game/data/discoveries/hollow_combine_survey_rig.tres +++ b/game/data/discoveries/hollow_combine_survey_rig.tres @@ -13,8 +13,8 @@ intel_reward = 45 scan_time = 8.0 radius = 3.0 leads_to = &"" -codex_title = "Combine survey rig" -codex_text = "A Combine rig bolted to the deck, logging which engines its crews have woken and where they have posted guards. Its log names where every Combine machine stands." +log_title = "Combine survey rig" +log_text = "A Combine rig bolted to the deck, logging which engines its crews have woken and where they have posted guards. Its log names where every Combine machine stands." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/hollow_core_annal.tres b/game/data/discoveries/hollow_core_annal.tres index 9936853c..4527c45e 100644 --- a/game/data/discoveries/hollow_core_annal.tres +++ b/game/data/discoveries/hollow_core_annal.tres @@ -13,8 +13,8 @@ intel_reward = 160 scan_time = 18.0 radius = 1.5 leads_to = &"" -codex_title = "The annal by the dais" -codex_text = "A list cut into the stone, in the same marks as every beacon. We can read it now. It names Kessel, Thalassa, Emberfall and Verdance, in the order we landed on them, and after them a long column of worlds we have never heard of. Below the list, a store of charge the Survey Lab can turn on a point of our choosing." +log_title = "The annal by the dais" +log_text = "A list cut into the stone, in the same marks as every beacon. We can read it now. It names Kessel, Thalassa, Emberfall and Verdance, in the order we landed on them, and after them a long column of worlds we have never heard of. Below the list, a store of charge the Survey Lab can turn on a point of our choosing." payoff = &"unlock_option" unlocks_option = &"antecedent_power" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/hollow_custodian_cradle.tres b/game/data/discoveries/hollow_custodian_cradle.tres index 4bcea268..10db456e 100644 --- a/game/data/discoveries/hollow_custodian_cradle.tres +++ b/game/data/discoveries/hollow_custodian_cradle.tres @@ -13,8 +13,8 @@ intel_reward = 80 scan_time = 12.0 radius = 3.0 leads_to = &"" -codex_title = "Where the Custodians rest" -codex_text = "A cradle of brass arms where a Custodian lay for repair, long ago. Its field still mends whatever stands in it. The arms keep a log of what woke each guardian: footsteps, mostly, and the hum of an engine coming back. A survey team that learns that rhythm can walk closer before anything stirs." +log_title = "Where the Custodians rest" +log_text = "A cradle of brass arms where a Custodian lay for repair, long ago. Its field still mends whatever stands in it. The arms keep a log of what woke each guardian: footsteps, mostly, and the hum of an engine coming back. A survey team that learns that rhythm can walk closer before anything stirs." payoff = &"heal_field" payoff_radius = 12.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/hollow_engine_schematic.tres b/game/data/discoveries/hollow_engine_schematic.tres index d2352ce7..f6b9185d 100644 --- a/game/data/discoveries/hollow_engine_schematic.tres +++ b/game/data/discoveries/hollow_engine_schematic.tres @@ -13,7 +13,7 @@ intel_reward = 90 scan_time = 12.0 radius = 3.0 leads_to = &"" -codex_title = "The engines were never locked" -codex_text = "Plates set into the deck show an engine in section, the way a manual would. The engines have no owner and no lock: they answer whoever stands beside them and asks long enough. The plates also show where to ask. With what they teach, a team could wake an engine in half the time." +log_title = "The engines were never locked" +log_text = "Plates set into the deck show an engine in section, the way a manual would. The engines have no owner and no lock: they answer whoever stands beside them and asks long enough. The plates also show where to ask. With what they teach, a team could wake an engine in half the time." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/hollow_plate_seam.tres b/game/data/discoveries/hollow_plate_seam.tres index 750374d4..990ae280 100644 --- a/game/data/discoveries/hollow_plate_seam.tres +++ b/game/data/discoveries/hollow_plate_seam.tres @@ -14,8 +14,8 @@ intel_reward = 50 scan_time = 9.0 radius = 3.0 leads_to = &"" -codex_title = "A sprung plate" -codex_text = "One deck plate has lifted along its seam. Under it is not rock but more structure, layer on layer of worked alloy, and the alloy under the seam has come loose. The same plating, bolted round an engine, would keep it running through a long fight." +log_title = "A sprung plate" +log_text = "One deck plate has lifted along its seam. Under it is not rock but more structure, layer on layer of worked alloy, and the alloy under the seam has come loose. The same plating, bolted round an engine, would keep it running through a long fight." payoff = &"deposit" payoff_node = ExtResource("n_node") payoff_offset = Vector3(0, 0, 9) diff --git a/game/data/discoveries/hollow_trail_terminus.tres b/game/data/discoveries/hollow_trail_terminus.tres index eb4b247a..f6b3b8c8 100644 --- a/game/data/discoveries/hollow_trail_terminus.tres +++ b/game/data/discoveries/hollow_trail_terminus.tres @@ -13,7 +13,7 @@ intel_reward = 120 scan_time = 16.0 radius = 3.0 leads_to = &"hollow_core_annal" -codex_title = "The last beacon" -codex_text = "Every beacon since Kessel's rim has pointed onward. This one points inward. Its bearing does not leave the deck: it runs to a block of carved stone beside the dais, where the Beacon Core stands. The trail ends here, on a world somebody built." +log_title = "The last beacon" +log_text = "Every beacon since Kessel's rim has pointed onward. This one points inward. Its bearing does not leave the deck: it runs to a block of carved stone beside the dais, where the Beacon Core stands. The trail ends here, on a world somebody built." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/kessel_basalt_shelf.tres b/game/data/discoveries/kessel_basalt_shelf.tres index 80404c10..87e5f4aa 100644 --- a/game/data/discoveries/kessel_basalt_shelf.tres +++ b/game/data/discoveries/kessel_basalt_shelf.tres @@ -14,8 +14,8 @@ intel_reward = 40 scan_time = 12.0 radius = 5.0 leads_to = &"" -codex_title = "Basalt shelf" -codex_text = "Layered basalt with alloy-bearing veins close to the surface. A rich deposit is marked beside the shelf." +log_title = "Basalt shelf" +log_text = "Layered basalt with alloy-bearing veins close to the surface. A rich deposit is marked beside the shelf." payoff = &"deposit" payoff_node = ExtResource("n_rich") payoff_offset = Vector3(-9, 0, 0) diff --git a/game/data/discoveries/kessel_combine_relay.tres b/game/data/discoveries/kessel_combine_relay.tres index dd3d109f..aeb550a2 100644 --- a/game/data/discoveries/kessel_combine_relay.tres +++ b/game/data/discoveries/kessel_combine_relay.tres @@ -13,8 +13,8 @@ intel_reward = 40 scan_time = 12.0 radius = 1.5 leads_to = &"" -codex_title = "Combine relay stake" -codex_text = "A relay the Combine left behind to talk to its rigs. Tapping it shows their positions for a while." +log_title = "Combine relay stake" +log_text = "A relay the Combine left behind to talk to its rigs. Tapping it shows their positions for a while." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/kessel_combine_survey_cut.tres b/game/data/discoveries/kessel_combine_survey_cut.tres index 956baccf..07549aac 100644 --- a/game/data/discoveries/kessel_combine_survey_cut.tres +++ b/game/data/discoveries/kessel_combine_survey_cut.tres @@ -13,8 +13,8 @@ intel_reward = 40 scan_time = 12.0 radius = 5.0 leads_to = &"" -codex_title = "Combine survey cut" -codex_text = "A fresh cut made by a Combine rig, with its survey markers still in place. Their logs give away where every Combine machine was posted." +log_title = "Combine survey cut" +log_text = "A fresh cut made by a Combine rig, with its survey markers still in place. Their logs give away where every Combine machine was posted." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/kessel_dust_bloom.tres b/game/data/discoveries/kessel_dust_bloom.tres index b3583ab6..b472e506 100644 --- a/game/data/discoveries/kessel_dust_bloom.tres +++ b/game/data/discoveries/kessel_dust_bloom.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 10.0 radius = 3.5 leads_to = &"" -codex_title = "Dust bloom" -codex_text = "A colony of low succulents that seals cracked surfaces with a resin. Their spores settle on hull plating too: machines near the bloom mend for a while." +log_title = "Dust bloom" +log_text = "A colony of low succulents that seals cracked surfaces with a resin. Their spores settle on hull plating too: machines near the bloom mend for a while." payoff = &"heal_field" payoff_radius = 16.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/kessel_fumarole.tres b/game/data/discoveries/kessel_fumarole.tres index 30a13cb6..a69f50dd 100644 --- a/game/data/discoveries/kessel_fumarole.tres +++ b/game/data/discoveries/kessel_fumarole.tres @@ -14,8 +14,8 @@ intel_reward = 45 scan_time = 15.0 radius = 5.0 leads_to = &"" -codex_title = "Cold fumarole" -codex_text = "The orbital scan read this as a heat signature. On the ground it is a fumarole that has gone quiet, and a Flux vent has opened beside it." +log_title = "Cold fumarole" +log_text = "The orbital scan read this as a heat signature. On the ground it is a fumarole that has gone quiet, and a Flux vent has opened beside it." payoff = &"deposit" payoff_node = ExtResource("n_vent") payoff_offset = Vector3(0, 0, -9) diff --git a/game/data/discoveries/kessel_lichen_garden.tres b/game/data/discoveries/kessel_lichen_garden.tres index 6c879002..7ba04e0e 100644 --- a/game/data/discoveries/kessel_lichen_garden.tres +++ b/game/data/discoveries/kessel_lichen_garden.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 10.0 radius = 3.5 leads_to = &"" -codex_title = "Lichen garden" -codex_text = "Crusted lichen in a sheltered hollow, feeding on the Flux that seeps from below. Disturbed, it releases a mending resin over everything nearby." +log_title = "Lichen garden" +log_text = "Crusted lichen in a sheltered hollow, feeding on the Flux that seeps from below. Disturbed, it releases a mending resin over everything nearby." payoff = &"heal_field" payoff_radius = 16.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/kessel_ore_seam.tres b/game/data/discoveries/kessel_ore_seam.tres index ecf36ddf..43baadb4 100644 --- a/game/data/discoveries/kessel_ore_seam.tres +++ b/game/data/discoveries/kessel_ore_seam.tres @@ -14,8 +14,8 @@ intel_reward = 40 scan_time = 12.0 radius = 5.0 leads_to = &"" -codex_title = "Ore seam, western scarp" -codex_text = "A dust storm stripped the scarp down to a seam of high-grade alloy ore. The survey marks a rich deposit just below the outcrop." +log_title = "Ore seam, western scarp" +log_text = "A dust storm stripped the scarp down to a seam of high-grade alloy ore. The survey marks a rich deposit just below the outcrop." payoff = &"deposit" payoff_node = ExtResource("n_rich") payoff_offset = Vector3(0, 0, 9) diff --git a/game/data/discoveries/kessel_sealed_cache.tres b/game/data/discoveries/kessel_sealed_cache.tres index 80ff0e80..50727c28 100644 --- a/game/data/discoveries/kessel_sealed_cache.tres +++ b/game/data/discoveries/kessel_sealed_cache.tres @@ -13,8 +13,8 @@ intel_reward = 100 scan_time = 15.0 radius = 1.5 leads_to = &"" -codex_title = "Sealed cache" -codex_text = "A small Antecedent container, sealed for longer than the basin has had weather. Its contents are inscriptions: a great deal of Intel for the Meridian's archive." +log_title = "Sealed cache" +log_text = "A small Antecedent container, sealed for longer than the basin has had weather. Its contents are inscriptions: a great deal of Intel for the Meridian's archive." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/kessel_trail_beacon.tres b/game/data/discoveries/kessel_trail_beacon.tres index f668e754..a246f297 100644 --- a/game/data/discoveries/kessel_trail_beacon.tres +++ b/game/data/discoveries/kessel_trail_beacon.tres @@ -13,8 +13,8 @@ intel_reward = 60 scan_time = 18.0 radius = 3.0 leads_to = &"kessel_trail_ruin" -codex_title = "The beacon on the western rim" -codex_text = "An Antecedent beacon, still faintly warm. Its signal is not a call but a bearing: it points across the basin to a second structure the orbital scan missed." +log_title = "The beacon on the western rim" +log_text = "An Antecedent beacon, still faintly warm. Its signal is not a call but a bearing: it points across the basin to a second structure the orbital scan missed." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/kessel_trail_ruin.tres b/game/data/discoveries/kessel_trail_ruin.tres index b55d0d39..6e380f2f 100644 --- a/game/data/discoveries/kessel_trail_ruin.tres +++ b/game/data/discoveries/kessel_trail_ruin.tres @@ -13,8 +13,8 @@ intel_reward = 90 scan_time = 21.0 radius = 5.5 leads_to = &"" -codex_title = "The ruin the beacon pointed to" -codex_text = "A ring of pale stone around a buried power core. The core answers the Survey Lab: its stored charge can be turned on a point of our choosing." +log_title = "The ruin the beacon pointed to" +log_text = "A ring of pale stone around a buried power core. The core answers the Survey Lab: its stored charge can be turned on a point of our choosing." payoff = &"unlock_option" unlocks_option = &"antecedent_power" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/thalassa_drowned_cache.tres b/game/data/discoveries/thalassa_drowned_cache.tres index f14b8313..33678bb6 100644 --- a/game/data/discoveries/thalassa_drowned_cache.tres +++ b/game/data/discoveries/thalassa_drowned_cache.tres @@ -13,7 +13,7 @@ intel_reward = 100 scan_time = 10.0 radius = 1.5 leads_to = &"" -codex_title = "Drowned cache" -codex_text = "A sealed Antecedent container in the bed of a tidal pan, reachable only at low water. Its inscriptions are a great deal of Intel for the Meridian's archive." +log_title = "Drowned cache" +log_text = "A sealed Antecedent container in the bed of a tidal pan, reachable only at low water. Its inscriptions are a great deal of Intel for the Meridian's archive." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/thalassa_kelp_bed.tres b/game/data/discoveries/thalassa_kelp_bed.tres index 3cf71871..c0c34796 100644 --- a/game/data/discoveries/thalassa_kelp_bed.tres +++ b/game/data/discoveries/thalassa_kelp_bed.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 7.0 radius = 3.5 leads_to = &"" -codex_title = "Kelp bed" -codex_text = "Kelp that survives the dry hours by sealing itself in a resin skin. Broken open, the resin mends whatever it runs over." +log_title = "Kelp bed" +log_text = "Kelp that survives the dry hours by sealing itself in a resin skin. Broken open, the resin mends whatever it runs over." payoff = &"heal_field" payoff_radius = 16.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/thalassa_reef_garden.tres b/game/data/discoveries/thalassa_reef_garden.tres index 395911e0..05906d9a 100644 --- a/game/data/discoveries/thalassa_reef_garden.tres +++ b/game/data/discoveries/thalassa_reef_garden.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 7.0 radius = 3.5 leads_to = &"" -codex_title = "Reef garden, northern flats" -codex_text = "A garden of hard-shelled reef growth that only opens at low water. It feeds on the same Flux the vents give off." +log_title = "Reef garden, northern flats" +log_text = "A garden of hard-shelled reef growth that only opens at low water. It feeds on the same Flux the vents give off." payoff = &"heal_field" payoff_radius = 14.0 payoff_amount = 8.0 diff --git a/game/data/discoveries/thalassa_salt_flat.tres b/game/data/discoveries/thalassa_salt_flat.tres index cdfed00d..1620caca 100644 --- a/game/data/discoveries/thalassa_salt_flat.tres +++ b/game/data/discoveries/thalassa_salt_flat.tres @@ -14,8 +14,8 @@ intel_reward = 40 scan_time = 8.0 radius = 5.0 leads_to = &"" -codex_title = "Salt flat, southern sands" -codex_text = "The tide leaves a crust of salt and ore grit here twice a day. Under it the survey finds a seam the sea has been washing clean: a rich deposit, just above the high-water line." +log_title = "Salt flat, southern sands" +log_text = "The tide leaves a crust of salt and ore grit here twice a day. Under it the survey finds a seam the sea has been washing clean: a rich deposit, just above the high-water line." payoff = &"deposit" payoff_node = ExtResource("n_rich") payoff_offset = Vector3(0, 0, 9) diff --git a/game/data/discoveries/thalassa_survey_stake.tres b/game/data/discoveries/thalassa_survey_stake.tres index c5a4f6f2..0ca43622 100644 --- a/game/data/discoveries/thalassa_survey_stake.tres +++ b/game/data/discoveries/thalassa_survey_stake.tres @@ -13,8 +13,8 @@ intel_reward = 40 scan_time = 8.0 radius = 5.0 leads_to = &"" -codex_title = "Combine survey stake" -codex_text = "A survey cut on the flats, staked out at low water. The markers still carry the rigs' call signs and positions." +log_title = "Combine survey stake" +log_text = "A survey cut on the flats, staked out at low water. The markers still carry the rigs' call signs and positions." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/thalassa_tide_gauge.tres b/game/data/discoveries/thalassa_tide_gauge.tres index 8be56201..286fe063 100644 --- a/game/data/discoveries/thalassa_tide_gauge.tres +++ b/game/data/discoveries/thalassa_tide_gauge.tres @@ -13,8 +13,8 @@ intel_reward = 40 scan_time = 8.0 radius = 1.5 leads_to = &"" -codex_title = "Combine tide gauge" -codex_text = "The Combine times its convoys by this gauge. Its log names every rig that asked for the tide table, and where it stood." +log_title = "Combine tide gauge" +log_text = "The Combine times its convoys by this gauge. Its log names every rig that asked for the tide table, and where it stood." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/thalassa_trail_echo.tres b/game/data/discoveries/thalassa_trail_echo.tres index 1814e8af..adb83fa9 100644 --- a/game/data/discoveries/thalassa_trail_echo.tres +++ b/game/data/discoveries/thalassa_trail_echo.tres @@ -13,7 +13,7 @@ intel_reward = 60 scan_time = 12.0 radius = 3.0 leads_to = &"thalassa_trail_vault" -codex_title = "The beacon in the shallows" -codex_text = "A beacon of the same make as the one on Kessel's rim, answering it. Its bearing crosses the channel to a structure on the northern shoal." +log_title = "The beacon in the shallows" +log_text = "A beacon of the same make as the one on Kessel's rim, answering it. Its bearing crosses the channel to a structure on the northern shoal." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/thalassa_trail_vault.tres b/game/data/discoveries/thalassa_trail_vault.tres index 7831ee40..2831afa8 100644 --- a/game/data/discoveries/thalassa_trail_vault.tres +++ b/game/data/discoveries/thalassa_trail_vault.tres @@ -13,8 +13,8 @@ intel_reward = 90 scan_time = 14.0 radius = 5.5 leads_to = &"" -codex_title = "The vault on the northern shoal" -codex_text = "Pale stone like the ruin on Kessel, built where the sea never reaches. The trail runs on from here, and the core it guards still holds a charge the Survey Lab can turn on a point of our choosing." +log_title = "The vault on the northern shoal" +log_text = "Pale stone like the ruin on Kessel, built where the sea never reaches. The trail runs on from here, and the core it guards still holds a charge the Survey Lab can turn on a point of our choosing." payoff = &"unlock_option" unlocks_option = &"antecedent_power" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/discoveries/verdance_combine_listening_post.tres b/game/data/discoveries/verdance_combine_listening_post.tres index 84676dc6..eff73138 100644 --- a/game/data/discoveries/verdance_combine_listening_post.tres +++ b/game/data/discoveries/verdance_combine_listening_post.tres @@ -13,8 +13,8 @@ intel_reward = 45 scan_time = 8.0 radius = 3.0 leads_to = &"" -codex_title = "Combine listening post" -codex_text = "A relay hidden under the crowns, logging the Hornets' flight paths and the trees they cannot see under. Its log names where every Combine machine was posted." +log_title = "Combine listening post" +log_text = "A relay hidden under the crowns, logging the Hornets' flight paths and the trees they cannot see under. Its log names where every Combine machine was posted." payoff = &"reveal_enemy" payoff_radius = 9.0 payoff_seconds = 45.0 diff --git a/game/data/discoveries/verdance_glowcap_ring.tres b/game/data/discoveries/verdance_glowcap_ring.tres index 969d1098..3e66ad86 100644 --- a/game/data/discoveries/verdance_glowcap_ring.tres +++ b/game/data/discoveries/verdance_glowcap_ring.tres @@ -13,8 +13,8 @@ intel_reward = 35 scan_time = 7.0 radius = 3.5 leads_to = &"" -codex_title = "Glowcap ring" -codex_text = "A ring of pale fungus around a fallen bough, lit faintly from inside. Its spores settle on damaged plating and seal hairline cracks: anything resting near it mends." +log_title = "Glowcap ring" +log_text = "A ring of pale fungus around a fallen bough, lit faintly from inside. Its spores settle on damaged plating and seal hairline cracks: anything resting near it mends." payoff = &"heal_field" payoff_radius = 16.0 payoff_amount = 10.0 diff --git a/game/data/discoveries/verdance_lantern_moths.tres b/game/data/discoveries/verdance_lantern_moths.tres index 9a9c4766..fa5b80e9 100644 --- a/game/data/discoveries/verdance_lantern_moths.tres +++ b/game/data/discoveries/verdance_lantern_moths.tres @@ -13,7 +13,7 @@ intel_reward = 45 scan_time = 8.0 radius = 3.0 leads_to = &"verdance_trail_root" -codex_title = "Lantern moths" -codex_text = "Moths that roost in a hollow trunk and see in the green dark under the crowns, where our optics see nothing past a few metres. They gather in thousands round something pale in the north-west grove. Their eyes filter the canopy's light: a lens cut the same way would let a sensor see much further in the understory." +log_title = "Lantern moths" +log_text = "Moths that roost in a hollow trunk and see in the green dark under the crowns, where our optics see nothing past a few metres. They gather in thousands round something pale in the north-west grove. Their eyes filter the canopy's light: a lens cut the same way would let a sensor see much further in the understory." payoff = &"none" color = Color(0.45, 0.95, 0.5, 1) diff --git a/game/data/discoveries/verdance_root_vein.tres b/game/data/discoveries/verdance_root_vein.tres index 6a6ad7d1..1d217678 100644 --- a/game/data/discoveries/verdance_root_vein.tres +++ b/game/data/discoveries/verdance_root_vein.tres @@ -14,8 +14,8 @@ intel_reward = 45 scan_time = 9.0 radius = 4.0 leads_to = &"" -codex_title = "Root-split vein" -codex_text = "The roots of the grove have prised the bedrock open along an ore seam. Mapped, the split shows where the richest of it lies just under the moss, still in the crown's shade." +log_title = "Root-split vein" +log_text = "The roots of the grove have prised the bedrock open along an ore seam. Mapped, the split shows where the richest of it lies just under the moss, still in the crown's shade." payoff = &"deposit" payoff_node = ExtResource("n_node") payoff_offset = Vector3(-9, 0, 0) diff --git a/game/data/discoveries/verdance_seed_vault.tres b/game/data/discoveries/verdance_seed_vault.tres index fa637f20..d90653b1 100644 --- a/game/data/discoveries/verdance_seed_vault.tres +++ b/game/data/discoveries/verdance_seed_vault.tres @@ -14,8 +14,8 @@ intel_reward = 75 scan_time = 11.0 radius = 1.5 leads_to = &"" -codex_title = "Seed vault" -codex_text = "An Antecedent store under the oldest tree in the basin, guarded by its own machines. It holds no seeds any more, only worked alloy grown through with roots; opened, it spills out beside the trunk." +log_title = "Seed vault" +log_text = "An Antecedent store under the oldest tree in the basin, guarded by its own machines. It holds no seeds any more, only worked alloy grown through with roots; opened, it spills out beside the trunk." payoff = &"deposit" payoff_node = ExtResource("n_node") payoff_offset = Vector3(0, 0, -9) diff --git a/game/data/discoveries/verdance_trail_root.tres b/game/data/discoveries/verdance_trail_root.tres index a1df27a8..a959cbcb 100644 --- a/game/data/discoveries/verdance_trail_root.tres +++ b/game/data/discoveries/verdance_trail_root.tres @@ -13,7 +13,7 @@ intel_reward = 120 scan_time = 16.0 radius = 5.0 leads_to = &"" -codex_title = "The spire in the roots" -codex_text = "Pale Antecedent stone again, a spire the size of the furnace on Emberfall, lifted a metre off the ground by the roots that grew around it. It has been listening to the trees: its core keeps a map of every crown in the basin. The trail runs on, deeper in." +log_title = "The spire in the roots" +log_text = "Pale Antecedent stone again, a spire the size of the furnace on Emberfall, lifted a metre off the ground by the roots that grew around it. It has been listening to the trees: its core keeps a map of every crown in the basin. The trail runs on, deeper in." payoff = &"none" color = Color(0.75, 0.6, 1.0, 1) diff --git a/game/data/hints/catalog.tres b/game/data/hints/catalog.tres index 5df3e4b2..41d80d8e 100644 --- a/game/data/hints/catalog.tres +++ b/game/data/hints/catalog.tres @@ -46,7 +46,7 @@ mission_types = Array[StringName]([&"conquest", &"survey"]) script = ExtResource("1_hint") id = &"scan_site" title = "Scan a signal" -text = "A \"?\" on the map is an unresolved signal from the orbital scan. {command} it with a Surveyor to walk over and scan it: Intel, a codex entry and sometimes more. Scans stop if the Surveyor leaves." +text = "A \"?\" on the map is an unresolved signal from the orbital scan. {command} it with a Surveyor to walk over and scan it: Intel, a log entry and sometimes more. Scans stop if the Surveyor leaves." trigger = &"selected" subject = &"scanner" diff --git a/game/data/sounds/ui/ui_codex_close.tres b/game/data/sounds/ui/ui_survey_log_close.tres similarity index 93% rename from game/data/sounds/ui/ui_codex_close.tres rename to game/data/sounds/ui/ui_survey_log_close.tres index 4a6935b9..fe0329bf 100644 --- a/game/data/sounds/ui/ui_codex_close.tres +++ b/game/data/sounds/ui/ui_survey_log_close.tres @@ -5,7 +5,7 @@ [resource] script = ExtResource("1_script") -id = &"ui_codex_close" +id = &"ui_survey_log_close" streams = Array[AudioStream]([ExtResource("2_stream")]) bus = &"UI" priority = 90 diff --git a/game/data/sounds/ui/ui_codex_entry.tres b/game/data/sounds/ui/ui_survey_log_entry.tres similarity index 93% rename from game/data/sounds/ui/ui_codex_entry.tres rename to game/data/sounds/ui/ui_survey_log_entry.tres index 01a75689..1676baf9 100644 --- a/game/data/sounds/ui/ui_codex_entry.tres +++ b/game/data/sounds/ui/ui_survey_log_entry.tres @@ -5,7 +5,7 @@ [resource] script = ExtResource("1_script") -id = &"ui_codex_entry" +id = &"ui_survey_log_entry" streams = Array[AudioStream]([ExtResource("2_stream")]) bus = &"UI" priority = 90 diff --git a/game/data/sounds/ui/ui_codex_open.tres b/game/data/sounds/ui/ui_survey_log_open.tres similarity index 94% rename from game/data/sounds/ui/ui_codex_open.tres rename to game/data/sounds/ui/ui_survey_log_open.tres index 5300db36..5d439e1a 100644 --- a/game/data/sounds/ui/ui_codex_open.tres +++ b/game/data/sounds/ui/ui_survey_log_open.tres @@ -5,7 +5,7 @@ [resource] script = ExtResource("1_script") -id = &"ui_codex_open" +id = &"ui_survey_log_open" streams = Array[AudioStream]([ExtResource("2_stream")]) bus = &"UI" priority = 90 diff --git a/game/export_presets.cfg b/game/export_presets.cfg index 1433091d..0e38649e 100644 --- a/game/export_presets.cfg +++ b/game/export_presets.cfg @@ -7,7 +7,7 @@ advanced_options=false dedicated_server=false custom_features="" export_filter="all_resources" -include_filter="" +include_filter="assets/fonts/OFL.txt" exclude_filter="tests/*, addons/gut/*, presentation/showcase/*" export_path="../build/macos/Farlanding.zip" patches=PackedStringArray() @@ -64,7 +64,7 @@ advanced_options=false dedicated_server=false custom_features="" export_filter="all_resources" -include_filter="" +include_filter="assets/fonts/OFL.txt" exclude_filter="tests/*, addons/gut/*, presentation/showcase/*" export_path="../build/windows/Farlanding.exe" patches=PackedStringArray() @@ -113,7 +113,7 @@ advanced_options=false dedicated_server=false custom_features="" export_filter="all_resources" -include_filter="" +include_filter="assets/fonts/OFL.txt" exclude_filter="tests/*, addons/gut/*, presentation/showcase/*" export_path="../build/linux/Farlanding.x86_64" patches=PackedStringArray() @@ -142,7 +142,7 @@ runnable=true advanced_options=true custom_features="" export_filter="all_resources" -include_filter="" +include_filter="assets/fonts/OFL.txt" exclude_filter="tests/*, addons/gut/*, presentation/showcase/*" export_path="../build/web/index.html" script_export_mode=2 @@ -167,7 +167,7 @@ runnable=true advanced_options=true custom_features="web_diagnostics" export_filter="all_resources" -include_filter="addons/gut/double_templates/*.txt" +include_filter="addons/gut/double_templates/*.txt, assets/fonts/OFL.txt" exclude_filter="tests/test_*, tests/check_scripts.gd, addons/gut/gut_loader_the_scene.tscn, tests/maps/*, tests/smoke/*, tests/ui/*, tests/economy/*, tests/planet/*, tests/combat/*, tests/missions/*, tests/props/*, tests/discovery/*, tests/balance/*, tests/ai/*, tests/campaign/*, tests/stealth/*, tests/save/*, presentation/showcase/*" export_path="../build/web-diagnostics/index.html" script_export_mode=2 diff --git a/game/main.gd b/game/main.gd index efa50c91..63f8a60c 100644 --- a/game/main.gd +++ b/game/main.gd @@ -1,9 +1,9 @@ class_name Main extends Node ## The game's flow (PLAN 1, 2.6; Phases 5 to 9). The title screen offers Continue, -## New campaign (after a difficulty choice), Single missions, How to play, Settings, -## Credits and Quit. How to play and the credits are an InfoPanel over any screen; -## the Advisor's subtitles (SubtitleLine) sit under every menu. +## New campaign (after a difficulty choice), Single missions, How to play, Controls, +## Settings, Credits and Quit. How to play, Controls and the credits are an InfoPanel +## over any screen; the Advisor's subtitles (SubtitleLine) sit under every menu. ## ## Difficulty (Difficulty): a new campaign takes the one chosen on the title and keeps ## it in its state (the Meridian may change it); a single mission is played at the one @@ -121,6 +121,7 @@ func _ready() -> void: _title.missions_pressed.connect(show_select) _title.settings_pressed.connect(open_settings) _title.how_to_play_pressed.connect(func() -> void: _info.open_how_to_play()) + _title.controls_pressed.connect(func() -> void: _info.open_controls()) _title.credits_pressed.connect(open_credits) _title.quit_pressed.connect(func() -> void: get_tree().quit()) _select = MissionSelect.new() @@ -166,6 +167,7 @@ func _ready() -> void: _pause.resume_pressed.connect(resume) _pause.settings_pressed.connect(open_settings) _pause.how_to_play_pressed.connect(func() -> void: _info.open_how_to_play()) + _pause.controls_pressed.connect(func() -> void: _info.open_controls()) _pause.restart_pressed.connect(_on_restart) _pause.quit_pressed.connect(_back_from_landing) _pause.save_pressed.connect(func() -> void: _slots.open(true)) @@ -251,7 +253,7 @@ func _unhandled_input(event: InputEvent) -> void: return if key.keycode != KEY_ESCAPE and not key.is_action_pressed(&"pause_menu", false, true): return - # Anything in the map that wanted Esc (cancel placement, close the codex) had it. + # Anything in the map that wanted Esc (cancel placement, close the Survey Log) had it. if map != null and not paused and not _debrief.visible: open_pause() get_viewport().set_input_as_handled() @@ -416,6 +418,7 @@ func start_mission( var hud: Hud = found_hud if found_hud is Hud else null if hud != null: hud.menu_requested.connect(open_pause) + hud.survey_log_toggled.connect(func(is_open: bool) -> void: _hints.obscured = is_open) _apply_graphics() _apply_speed() _hints.begin_mission(mission) diff --git a/game/missions/landing_modifiers.gd b/game/missions/landing_modifiers.gd index ce06b1a7..7be694ff 100644 --- a/game/missions/landing_modifiers.gd +++ b/game/missions/landing_modifiers.gd @@ -4,7 +4,7 @@ extends RefCounted ## sim applies (locked entity types, stat scales), extra starting units and ## resources, field options unlocked or charged in advance, and discovery sites the ## orbital scan already charted from an earlier landing. The campaign builds it from -## its tech web, loadout and codex; a mission without one plays its MissionDef as is. +## its tech web, loadout and Survey Log; a mission without one plays its MissionDef as is. ## Locks and stat scales for the player's faction. var perks: FactionPerks = FactionPerks.new() diff --git a/game/missions/mission.gd b/game/missions/mission.gd index 047b734d..c0c17da2 100644 --- a/game/missions/mission.gd +++ b/game/missions/mission.gd @@ -368,7 +368,7 @@ func finish(won: bool) -> void: ) result.intel_held = world.economy.stockpile(player_faction).intel if world.discovery != null: - for found: DiscoveryDef in world.discovery.codex(player_faction): + for found: DiscoveryDef in world.discovery.survey_log(player_faction): result.discoveries.append(found.id) for found: Objective in objectives: if found.is_known: diff --git a/game/presentation/selection/control_groups.gd b/game/presentation/selection/control_groups.gd index b56ac03b..b9fe74b1 100644 --- a/game/presentation/selection/control_groups.gd +++ b/game/presentation/selection/control_groups.gd @@ -1,6 +1,13 @@ class_name ControlGroups extends RefCounted -## Numbered control groups (1..9). Ctrl+N stores the selection, N recalls it. +## Numbered control groups (1..9). Ctrl/Cmd or Alt/Option + N stores the selection, +## Shift + N adds it, N recalls it (SelectionController reads the keys; the HUD's +## GroupBar shows the groups). + +## Any group's members changed (stored, added to, or restored from a save). +signal changed +## The player stored a selection in group `index` or added one to it. +signal stored(index: int) const COUNT: int = 9 @@ -10,21 +17,34 @@ var _groups: Dictionary[int, Array] = {} func assign(index: int, units: Array[Unit]) -> void: assert(index >= 1 and index <= COUNT, "Control group out of range: %d" % index) _groups[index] = units.duplicate() + changed.emit() + stored.emit(index) + + +## Adds `units` to group `index` after its living members (each unit once). +func add(index: int, units: Array[Unit]) -> void: + assert(index >= 1 and index <= COUNT, "Control group out of range: %d" % index) + var merged: Array[Unit] = _living(index) + for unit: Unit in units: + if not merged.has(unit): + merged.append(unit) + _groups[index] = merged + changed.emit() + stored.emit(index) ## Living members of group `index`, in the order they were stored. func recall(index: int) -> Array[Unit]: - var result: Array[Unit] = [] - var stored: Array = _groups.get(index, []) - for entry: Variant in stored: - if is_instance_valid(entry): - var unit: Unit = entry - if unit.is_inside_tree(): - result.append(unit) + var result: Array[Unit] = _living(index) _groups[index] = result.duplicate() return result +## How many living units group `index` holds now. +func count(index: int) -> int: + return _living(index).size() + + ## Stored groups by unit save id (a saved game keeps the player's groups). func to_dict() -> Dictionary: var saved: Dictionary = {} @@ -55,3 +75,16 @@ func from_dict(data: Dictionary, lookup: Callable) -> void: if unit != null: units.append(unit) _groups[index] = units + changed.emit() + + +## Members of group `index` that still exist, are in the world and are not dying. +func _living(index: int) -> Array[Unit]: + var result: Array[Unit] = [] + var stored_units: Array = _groups.get(index, []) + for entry: Variant in stored_units: + if is_instance_valid(entry): + var unit: Unit = entry + if unit.is_inside_tree() and not unit.is_dead: + result.append(unit) + return result diff --git a/game/presentation/selection/selection_controller.gd b/game/presentation/selection/selection_controller.gd index 3cb5ea27..a6423a2a 100644 --- a/game/presentation/selection/selection_controller.gd +++ b/game/presentation/selection/selection_controller.gd @@ -15,9 +15,11 @@ extends Node ## In both: left drag box-selects units (Shift adds), Shift+click toggles a unit, ## double-click selects every visible unit of that type, Shift queues orders. While ## placing a building (BuildPlacement) or aiming a field option, left click confirms -## and right click or Esc cancels. The stop key stops. Ctrl + a group key (1..9 by -## default; the keys are the player's, KeyBindings) stores a control group, the key -## recalls it, a quick second press centres the camera on it. With sticky Shift +## and right click or Esc cancels. The stop key stops. Ctrl/Cmd or Alt/Option + a +## group key (1..9 by default; the keys are the player's, KeyBindings) stores a +## control group (browsers keep Ctrl/Cmd + a number for their tabs, Alt reaches the +## game), Shift + the key adds the selection to it, the key recalls it, a quick +## second press centres the camera on it. With sticky Shift ## (Settings.sticky_shift) a press of Shift holds it until the next. Team colours ## follow the chosen palette (TeamColors), also when it changes. The cursor shows what ## a command click would do (CursorIcons). Enemies out of sight cannot be clicked: @@ -502,11 +504,12 @@ func _handle_key(key: InputEventKey) -> void: return var group: int = KeyBindings.group_of(key) if group > 0: - if key.ctrl_pressed or key.meta_pressed: - _groups.assign(group, selection) - Events.ui_feedback.emit(&"group_assign") + if key.ctrl_pressed or key.meta_pressed or key.alt_pressed: + store_group(group) + elif shift_held(key): + add_selection_to_group(group) else: - _recall_group(group) + recall_group(group) get_viewport().set_input_as_handled() return if selection.is_empty(): @@ -516,7 +519,23 @@ func _handle_key(key: InputEventKey) -> void: get_viewport().set_input_as_handled() -func _recall_group(group: int) -> void: +## Stores the selection in control group `group` (1..9), replacing what it held. +func store_group(group: int) -> void: + _groups.assign(group, selection) + Events.ui_feedback.emit(&"group_assign") + + +## Adds the selection to control group `group` (1..9), keeping what it held. +func add_selection_to_group(group: int) -> void: + if selection.is_empty(): + return + _groups.add(group, selection) + Events.ui_feedback.emit(&"group_assign") + + +## Selects control group `group` (1..9); a second recall of it within +## DOUBLE_TAP_SECONDS centres the camera on it (the key and the HUD's GroupBar). +func recall_group(group: int) -> void: var units: Array[Unit] = _groups.recall(group) var now: float = Time.get_ticks_msec() / 1000.0 var double_tap: bool = group == _last_group_key and now - _last_group_time < DOUBLE_TAP_SECONDS @@ -526,7 +545,7 @@ func _recall_group(group: int) -> void: return Events.ui_feedback.emit(&"group_recall") set_selection(units) - if double_tap: + if double_tap and camera != null: var centre: Vector3 = Vector3.ZERO for unit: Unit in units: centre += unit.global_position diff --git a/game/project.godot b/game/project.godot index d285c5c7..24a80f35 100644 --- a/game/project.godot +++ b/game/project.godot @@ -25,6 +25,7 @@ Game="*res://core/game.gd" Settings="*res://core/settings.gd" MCPRuntimeProbe="*res://addons/godot_mcp/mcp_runtime_probe.gd" Audio="*res://audio/audio_service.gd" +UiTheme="*res://ui/ui_theme.gd" [debug] @@ -117,8 +118,6 @@ camera_pan_back={ [rendering] -renderer/rendering_method.web="gl_compatibility" - textures/vram_compression/import_etc2_astc=true [shader_globals] diff --git a/game/sim/components/locomotion.gd b/game/sim/components/locomotion.gd index 9755dd25..e6471e7a 100644 --- a/game/sim/components/locomotion.gd +++ b/game/sim/components/locomotion.gd @@ -3,8 +3,9 @@ extends Node ## Movement component (ground units; flying units too, ADR 0016: they get a ## straight-line PathService and keep `flight_altitude` above the terrain). ## Wraps a Mover, asks the PathService for a path once per -## destination, follows the terrain through a HeightField, and (when the path backend -## offers a navigation map) joins server-side RVO avoidance. Runs on sim ticks; the +## destination, follows the terrain through a HeightField, and (when the world has a +## Traffic, ADR 0022) passes other ground units: it bends and brakes around them, and +## steps aside for a friend while it stands with nothing to do. Runs on sim ticks; the ## parent Node3D is moved every frame by `interpolate()`. ## Ground speed changed (metres per second). Presentation drives wheels/legs from it. @@ -13,7 +14,8 @@ signal motion_changed(speed: float) signal arrived ## 2: the wanted destination and the wait for the tide (ADR 0014). -const SAVE_VERSION: int = 2 +## 3: a step aside in progress and the post to walk back to (ADR 0022). +const SAVE_VERSION: int = 3 ## A path ending further than this from where the unit was sent falls short. const TIDE_SHORT: float = 3.0 ## No progress toward the current corner for this long counts as stuck. @@ -22,9 +24,20 @@ const STUCK_SECONDS: float = 1.5 const STUCK_PROGRESS: float = 0.3 ## Stuck re-paths allowed per destination before the unit gives up and stops. const MAX_REPATHS: int = 2 -## RVO priorities: idle units hold their ground, moving units steer around them. -const PRIORITY_IDLE: float = 1.0 -const PRIORITY_MOVING: float = 0.5 +## A nearby corner can be skipped once the next leg is directly walkable. +const SKIP_DISTANCE: float = 12.0 +## Traffic queues accumulate stuck time slowly, including near their final slot. +const WAITING_SHARE: float = 0.2 +## A step aside is dropped when it takes longer than this. +const GIVE_WAY_SECONDS: float = 2.5 +## After stepping aside, a unit walks back once nothing has driven by for this long. +const RETURN_SECONDS: float = 2.0 +## ... unless it ended up this close to where it stood anyway. +const RETURN_DISTANCE: float = 0.6 +## Share of the way the sideways pull moves toward Traffic's newest value per tick. +const STEER_EASE: float = 0.5 +## After traffic steered a unit onto closed ground, it follows its path alone this long. +const PLAIN_SECONDS: float = 0.5 var mover: Mover = Mover.new() ## Body radius in metres (from the UnitDef). @@ -32,15 +45,28 @@ var radius: float = 0.5 ## The path backend this unit moves with (also used by commands for formations). var paths: PathService = PathService.new() +## True while the unit must stay where it stands (it works, fires or hides there): it +## does not step aside for friends. The Unit sets it every tick. +var holds_ground: bool = false var _heights: HeightField = null var _destination: Vector3 = Vector3.ZERO var _travelling: bool = false var _previous_position: Vector3 = Vector3.ZERO var _previous_yaw: float = 0.0 -var _agent: RID = RID() -var _safe_velocity: Vector3 = Vector3.ZERO -var _has_safe_velocity: bool = false +var _traffic: Traffic = null +var _body: TrafficBody = null +## True while the path being followed is a step aside (or the walk back), not an order. +var _giving_way: bool = false +var _give_way_seconds: float = 0.0 +## Where the unit stood before it stepped aside; INF = it has not. +var _post: Vector3 = Vector3.INF +var _quiet_seconds: float = 0.0 +## The sideways pull in use: Traffic's, eased. +var _steer: Vector3 = Vector3.ZERO +## True when the velocity being applied was bent by traffic. +var _steered: bool = false +var _plain_seconds: float = 0.0 var _stuck_seconds: float = 0.0 var _best_corner_distance: float = INF var _stuck_corner: int = -1 @@ -48,9 +74,6 @@ var _reported_speed: float = 0.0 var _repaths: int = 0 var _facing: bool = false var _face_point: Vector3 = Vector3.ZERO -var _agent_priority: float = -1.0 -var _agent_position: Vector3 = Vector3.INF -var _agent_velocity: Vector3 = Vector3.INF var _base_speed: float = INF var _speed_limit: float = INF var _speed_scale: float = 1.0 @@ -65,13 +88,16 @@ var _altitude: float = 0.0 ## Configures the component from a definition and places it. Call once after the -## unit entered the tree. +## unit entered the tree. With `traffic`, the unit (of `faction`) passes the other +## units in it; flying units stay out. func setup( def: UnitDef, start: Vector3, start_yaw: float, p_paths: PathService, heights: HeightField, + traffic: Traffic = null, + faction: int = 0, ) -> void: _base_speed = def.move_speed mover.max_speed = _top_speed() @@ -85,14 +111,21 @@ func setup( mover.yaw = start_yaw _previous_position = mover.position _previous_yaw = mover.yaw - _create_agent(def) + if traffic != null and not def.flies: + _traffic = traffic + _body = TrafficBody.new() + _body.radius = def.radius + _body.acceleration = def.acceleration + _body.faction = faction + _traffic.add(_body) + _update_body() interpolate(1.0) func _exit_tree() -> void: - if _agent.is_valid(): - NavigationServer3D.free_rid(_agent) - _agent = RID() + if _body != null: + _traffic.remove(_body) + _body = null ## Requests a path to `target` and starts following it. Returns false (and stays put) @@ -100,6 +133,7 @@ func _exit_tree() -> void: func move_to(target: Vector3) -> bool: _repaths = 0 _facing = false + _end_give_way() _wanted = target return _request_path(target) @@ -109,6 +143,7 @@ func move_to(target: Vector3) -> bool: func follow_path(path: PackedVector3Array, wanted: Vector3 = Vector3.INF) -> bool: _repaths = 0 _facing = false + _end_give_way() _wanted = wanted if wanted == Vector3.INF: _wanted = path[path.size() - 1] if not path.is_empty() else mover.position @@ -179,13 +214,12 @@ func _top_speed() -> float: func _apply_top_speed() -> void: mover.max_speed = _top_speed() - if _agent.is_valid(): - NavigationServer3D.agent_set_max_speed(_agent, mover.max_speed) ## Brakes to a halt and forgets the destination. func stop() -> void: mover.clear_path() + _end_give_way() _travelling = false _facing = false _tide_wait = false @@ -216,23 +250,38 @@ func tick(dt: float) -> void: _previous_position = mover.position _previous_yaw = mover.yaw var start: Vector3 = mover.position - if _has_safe_velocity and mover.has_path(): - mover.integrate(_safe_velocity, dt) - # Avoidance must not push a unit off the walkable area: fall back to the plan. - if not paths.is_walkable(mover.position): + mover.integrate(mover.velocity, dt) + if _body != null: + _shift(_body.push) + # Traffic must not take a unit off the walkable area: stay, and follow the + # path alone for a moment. + if _steered and not paths.is_walkable(mover.position): mover.position = start - mover.integrate(mover.velocity, dt) - else: - mover.integrate(mover.velocity, dt) - var reached: bool = mover.plan(dt) + _plain_seconds = PLAIN_SECONDS + _tick_give_way(dt) + var steer: Vector3 = Vector3.ZERO + var speed_cap: float = INF + _plain_seconds = maxf(_plain_seconds - dt, 0.0) + if _body != null and _plain_seconds <= 0.0: + steer = _body.steer + speed_cap = _body.speed_cap + _skip_visible_corners() + # Eased in and out, so the unit swings around instead of jerking sideways. + _steer = _steer.lerp(steer, STEER_EASE) + if _steer.length_squared() < 0.0004: + _steer = Vector3.ZERO + _steered = _steer != Vector3.ZERO + var reached: bool = mover.plan(dt, _steer, speed_cap) if _facing and not mover.has_path(): _turn_toward_face_point(dt) mover.position = _on_ground(mover.position) - if reached: + if reached and _giving_way: + _giving_way = false + elif reached: _finish() elif _travelling: _check_stuck(dt) - _update_agent() + _update_body() if not is_equal_approx(mover.speed, _reported_speed): _reported_speed = mover.speed motion_changed.emit(mover.speed) @@ -255,6 +304,8 @@ func to_dict() -> Dictionary: "travelling": _travelling, "wanted": var_to_str(_wanted), "tide_wait": _tide_wait, + "giving_way": _giving_way, + "post": var_to_str(_post), } @@ -266,11 +317,15 @@ func from_dict(data: Dictionary) -> void: var destination_text: String = data.get("destination", "Vector3(0, 0, 0)") _destination = str_to_var(destination_text) _travelling = data.get("travelling", false) + _giving_way = data.get("giving_way", false) + var post_text: String = data.get("post", "") + _post = str_to_var(post_text) if post_text != "" else Vector3.INF var wanted_text: String = data.get("wanted", "") _wanted = str_to_var(wanted_text) if wanted_text != "" else _destination _tide_wait = data.get("tide_wait", false) _previous_position = mover.position _previous_yaw = mover.yaw + _update_body() func _request_path(target: Vector3) -> bool: @@ -329,14 +384,16 @@ func _check_stuck(dt: float) -> void: _best_corner_distance = distance _stuck_seconds = 0.0 return - _stuck_seconds += dt - if _stuck_seconds < STUCK_SECONDS: - return var final_distance: float = ( Vector2(_destination.x - mover.position.x, _destination.z - mover.position.z).length() ) - if final_distance < radius * 4.0 + 1.0: - # Close enough and blocked (usually by a unit already standing there). + var waiting: bool = _body != null and _body.speed_cap < mover.max_speed + _stuck_seconds += dt * (WAITING_SHARE if waiting else 1.0) + if _stuck_seconds < STUCK_SECONDS: + return + if final_distance <= maxf(radius, 0.5): + # The body covers its destination. Further away, retry the route rather + # than silently accepting a place several vehicle lengths short. _finish() return _repaths += 1 @@ -368,46 +425,81 @@ func _on_ground(point: Vector3) -> Vector3: return point -func _create_agent(def: UnitDef) -> void: - var map: RID = paths.get_avoidance_map() - if not map.is_valid(): +## Do not funnel a whole group through an exact point after the obstacle is clear. +## The walk grid validates each shortcut, so corners across walls stay in the path. +func _skip_visible_corners() -> void: + if _body == null or not _travelling: + return + while ( + mover.has_path() + and not mover.is_on_last_corner() + and mover.distance_to_corner() < SKIP_DISTANCE + and paths.is_segment_walkable(mover.position, mover.path[mover.path_index + 1]) + ): + mover.skip_corner() + + +## Moves by `offset` when that stays on walkable ground (Traffic's push). +func _shift(offset: Vector3) -> void: + if offset == Vector3.ZERO: + return + var shifted: Vector3 = mover.position + offset + if paths.is_walkable(shifted): + mover.position = shifted + + +## While standing with nothing to do: step aside when Traffic asks, and walk back to +## the post once nothing has driven by for a while. +func _tick_give_way(dt: float) -> void: + if _travelling: + return + if _giving_way: + _give_way_seconds += dt + if _give_way_seconds > GIVE_WAY_SECONDS: + mover.clear_path() + _giving_way = false + return + if holds_ground: + _post = Vector3.INF return - _agent = NavigationServer3D.agent_create() - NavigationServer3D.agent_set_use_3d_avoidance(_agent, false) - NavigationServer3D.agent_set_radius(_agent, def.radius + 0.25) - NavigationServer3D.agent_set_max_speed(_agent, mover.max_speed) - NavigationServer3D.agent_set_neighbor_distance(_agent, maxf(8.0, def.radius * 6.0)) - NavigationServer3D.agent_set_max_neighbors(_agent, 8) - NavigationServer3D.agent_set_time_horizon_agents(_agent, 0.8) - NavigationServer3D.agent_set_avoidance_priority(_agent, PRIORITY_IDLE) - NavigationServer3D.agent_set_position(_agent, mover.position) - _agent_priority = PRIORITY_IDLE - _agent_position = mover.position - _agent_velocity = Vector3.ZERO - NavigationServer3D.agent_set_avoidance_callback(_agent, _on_safe_velocity) - NavigationServer3D.agent_set_avoidance_enabled(_agent, true) - NavigationServer3D.agent_set_map(_agent, map) - - -func _update_agent() -> void: - if not _agent.is_valid(): + if _body.give_way_to != Vector3.INF: + if _post == Vector3.INF: + _post = mover.position + _quiet_seconds = 0.0 + _start_give_way(_body.give_way_to) + return + if _post == Vector3.INF: + return + _quiet_seconds = 0.0 if _body.crowded else _quiet_seconds + dt + if _quiet_seconds < RETURN_SECONDS: + return + var post: Vector3 = _post + _post = Vector3.INF + if _flat_distance(post, mover.position) > RETURN_DISTANCE: + _start_give_way(post) + + +func _start_give_way(target: Vector3) -> void: + if not paths.is_walkable(target) or not paths.is_segment_walkable(mover.position, target): + return + mover.set_path(PackedVector3Array([target])) + _giving_way = true + _give_way_seconds = 0.0 + + +## An order replaces a step aside: the unit no longer has a post to walk back to. +func _end_give_way() -> void: + _giving_way = false + _post = Vector3.INF + + +func _update_body() -> void: + if _body == null: return - # Only tell the server what changed: most units stand still most of the time. - if mover.position != _agent_position: - _agent_position = mover.position - NavigationServer3D.agent_set_position(_agent, mover.position) - var moving: bool = mover.has_path() - var priority: float = PRIORITY_MOVING if moving else PRIORITY_IDLE - if priority != _agent_priority: - _agent_priority = priority - NavigationServer3D.agent_set_avoidance_priority(_agent, priority) - if mover.velocity != _agent_velocity: - _agent_velocity = mover.velocity - NavigationServer3D.agent_set_velocity(_agent, mover.velocity) - if not moving: - _has_safe_velocity = false - - -func _on_safe_velocity(safe_velocity: Vector3) -> void: - _safe_velocity = safe_velocity - _has_safe_velocity = true + _body.position = mover.position + _body.velocity = mover.velocity + _body.wish = mover.wish + _body.max_speed = mover.max_speed + _body.moving = mover.has_path() + _body.asks_way = _travelling + _body.gives_way = not _travelling and not _giving_way and not holds_ground diff --git a/game/sim/components/mover.gd b/game/sim/components/mover.gd index 86ef94ba..e9f062cb 100644 --- a/game/sim/components/mover.gd +++ b/game/sim/components/mover.gd @@ -2,7 +2,7 @@ class_name Mover extends RefCounted ## Pure ground-movement maths for one unit: follows a list of path corners on the XZ ## plane, turning at `turn_speed` and accelerating/braking at `acceleration`, and -## stops exactly on the last corner. Knows nothing about nodes, terrain or avoidance; +## stops exactly on the last corner. Knows nothing about nodes, terrain or traffic; ## Locomotion wraps it. Height (`position.y`) is left to the caller. ## ## Each sim tick: `integrate(velocity_to_apply, dt)` then `plan(dt)`. @@ -27,6 +27,9 @@ var position: Vector3 = Vector3.ZERO var yaw: float = 0.0 ## Current ground speed in metres per second. var speed: float = 0.0 +## The velocity it would have without `steer`: straight at the corner. Zero without a +## path. +var wish: Vector3 = Vector3.ZERO ## Velocity this unit wants for the next tick (XZ only). var velocity: Vector3 = Vector3.ZERO var path: PackedVector3Array = PackedVector3Array() @@ -62,6 +65,12 @@ func clear_path() -> void: path_index = 0 +## Steers at the next corner instead (not from the last one). +func skip_corner() -> void: + if has_path() and not is_on_last_corner(): + path_index += 1 + + func has_path() -> bool: return path_index < path.size() @@ -81,20 +90,23 @@ func is_on_last_corner() -> bool: return path_index == path.size() - 1 -## Moves by `applied` (usually `velocity`, or an avoidance-adjusted velocity). +## Moves by `applied` (usually `velocity`). func integrate(applied: Vector3, dt: float) -> void: position.x += applied.x * dt position.z += applied.z * dt ## Updates facing, speed and `velocity` for the next `dt`. Returns true on the tick the -## last corner is reached. -func plan(dt: float) -> bool: +## last corner is reached. `steer` bends the travel direction sideways (it is added to +## the unit direction to the corner) and `speed_cap` limits the speed: how Traffic +## makes a unit pass or wait for another. +func plan(dt: float, steer: Vector3 = Vector3.ZERO, speed_cap: float = INF) -> bool: if not has_path(): speed = move_toward(speed, 0.0, acceleration * dt) if speed < MIN_SPEED: speed = 0.0 velocity = forward_for(yaw) * speed + wish = Vector3.ZERO return false var to_corner: Vector3 = _flat(path[path_index] - position) while not is_on_last_corner() and to_corner.length() < CORNER_RADIUS: @@ -107,13 +119,17 @@ func plan(dt: float) -> bool: clear_path() speed = 0.0 velocity = Vector3.ZERO + wish = Vector3.ZERO return true var direction: Vector3 = to_corner / distance + var straight: Vector3 = direction + if steer != Vector3.ZERO: + direction = _flat(direction + steer).normalized() var wanted_yaw: float = yaw_for(direction) yaw = wrapf(rotate_toward(yaw, wanted_yaw, turn_speed * dt), -PI, PI) # Slow down while facing away from the travel direction; turn in place above ~80°. var alignment: float = clampf((cos(angle_difference(yaw, wanted_yaw)) - 0.2) / 0.8, 0.0, 1.0) - var wanted_speed: float = max_speed * alignment + var wanted_speed: float = minf(max_speed * alignment, speed_cap) if is_on_last_corner(): wanted_speed = minf(wanted_speed, sqrt(2.0 * acceleration * distance)) speed = move_toward(speed, wanted_speed, acceleration * dt) @@ -121,6 +137,7 @@ func plan(dt: float) -> bool: if is_on_last_corner(): step_speed = minf(speed, distance / dt) velocity = direction * step_speed + wish = straight * step_speed return false diff --git a/game/sim/entities/unit.gd b/game/sim/entities/unit.gd index 452d238c..0b3e93ab 100644 --- a/game/sim/entities/unit.gd +++ b/game/sim/entities/unit.gd @@ -253,6 +253,7 @@ func sim_tick(dt: float) -> void: if profiling: mark = world._section(&"unit_orders", mark) if locomotion != null: + locomotion.holds_ground = _holds_ground() locomotion.tick(dt) if profiling: mark = world._section(&"unit_movement", mark) @@ -264,6 +265,14 @@ func sim_tick(dt: float) -> void: world._section(&"unit_weapon", mark) +## True while the unit must not step aside for a friend: it has orders, a target, or +## hides. +func _holds_ground() -> bool: + if orders != null and not orders.is_idle(): + return true + return cloak != null or (weapon != null and weapon.target != null) + + ## Simulation position (leads the drawn node by up to one tick). func sim_position() -> Vector3: return locomotion.mover.position if locomotion != null else global_position diff --git a/game/sim/systems/discovery/discovery.gd b/game/sim/systems/discovery/discovery.gd index 6b98f49a..fa468381 100644 --- a/game/sim/systems/discovery/discovery.gd +++ b/game/sim/systems/discovery/discovery.gd @@ -1,7 +1,7 @@ class_name Discovery extends Node ## Exploration for one mission (PLAN 2.4, ADR 0009): the discovery sites, resolving -## them (Intel, codex entry, payoff, chain), the payoffs that last a while (heal +## them (Intel, log entry, payoff, chain), the payoffs that last a while (heal ## fields), and the Survey Lab's field options. Created by SimWorld and ticked on the ## sim clock; registered on the MissionContext as `SERVICE_KEY`. ## @@ -17,8 +17,8 @@ var player_faction: int = 0 var sites: Array[DiscoverySite] = [] var field_options: FieldOptions = null -## Per faction: resolved DiscoveryDefs in the order found (the codex). -var _codex: Dictionary[int, Array] = {} +## Per faction: resolved DiscoveryDefs in the order found (the Survey Log). +var _survey_log: Dictionary[int, Array] = {} ## Running heal fields: { faction, x, z, radius, amount, until }. var _heal_fields: Array[Dictionary] = [] var _tick: int = 0 @@ -59,10 +59,10 @@ static func is_led_to(defs: Array[DiscoveryDef], id: StringName) -> bool: return false -## The faction's codex: DiscoveryDefs resolved so far, oldest first. -func codex(faction: int) -> Array[DiscoveryDef]: +## The faction's Survey Log: DiscoveryDefs resolved so far, oldest first. +func survey_log(faction: int) -> Array[DiscoveryDef]: var entries: Array[DiscoveryDef] = [] - var stored: Array = _codex.get(faction, []) + var stored: Array = _survey_log.get(faction, []) entries.assign(stored) return entries @@ -78,19 +78,19 @@ func on_scan_started(site: DiscoverySite) -> void: ## `faction` finished scanning `site`: it is resolved, the faction earns its Intel and -## codex entry, the payoff happens and the next site of a chain is charted. +## log entry, the payoff happens and the next site of a chain is charted. func resolve(site: DiscoverySite, faction: int) -> void: if site == null or site.is_resolved or site.def == null: return var def: DiscoveryDef = site.def site.resolve(faction) world.economy.add_intel(faction, def.intel_reward) - if not _codex.has(faction): - _codex[faction] = [] - _codex[faction].append(def) + if not _survey_log.has(faction): + _survey_log[faction] = [] + _survey_log[faction].append(def) Events.discovery_made.emit(site, def, faction) if faction == player_faction: - Events.codex_entry_added.emit(def) + Events.survey_log_entry_added.emit(def) Events.advisor_alert.emit(&"discovery") _apply_payoff(site, faction) if def.leads_to != &"": @@ -193,13 +193,13 @@ static func _is_enemy(faction: int, other: int) -> bool: func to_dict() -> Dictionary: - var codex_ids: Dictionary = {} - for faction: int in _codex: + var log_ids: Dictionary = {} + for faction: int in _survey_log: var paths: Array[String] = [] - for entry: Variant in _codex[faction]: + for entry: Variant in _survey_log[faction]: var def: DiscoveryDef = entry paths.append(def.resource_path) - codex_ids[str(faction)] = paths + log_ids[str(faction)] = paths var fields: Array[Dictionary] = [] for field: Dictionary in _heal_fields: var saved: Dictionary = field.duplicate() @@ -208,26 +208,27 @@ func to_dict() -> Dictionary: fields.append(saved) return { "version": SAVE_VERSION, - "codex": codex_ids, + "codex": log_ids, # the saved name of the Survey Log: keep it "heal_fields": fields, "field_options": field_options.to_dict(), } -## Restores the codex, heal fields and field options (sites are restored by SimWorld). +## Restores the Survey Log, heal fields and field options (sites are restored by SimWorld). func from_dict(data: Dictionary) -> void: var version: int = data.get("version", 0) assert(version == SAVE_VERSION, "Unsupported Discovery save version") - _codex.clear() - var codex_ids: Dictionary = data.get("codex", {}) - for key: Variant in codex_ids: - var paths: Array = codex_ids[key] + _survey_log.clear() + # "codex" is the saved name of the Survey Log (older saves too): keep it. + var log_ids: Dictionary = data.get("codex", {}) + for key: Variant in log_ids: + var paths: Array = log_ids[key] var entries: Array = [] for entry: Variant in paths: var path: String = entry if ResourceLoader.exists(path): entries.append(load(path)) - _codex[int(str(key))] = entries + _survey_log[int(str(key))] = entries _restored = true _heal_fields.clear() var fields: Array = data.get("heal_fields", []) diff --git a/game/sim/systems/navigation/flight_system.gd b/game/sim/systems/navigation/flight_system.gd index 5a9b3de0..7b1b8d68 100644 --- a/game/sim/systems/navigation/flight_system.gd +++ b/game/sim/systems/navigation/flight_system.gd @@ -1,6 +1,6 @@ class_name FlightSystem extends RefCounted -## Keeps flying units apart (ADR 0016). Flying units have no navmesh and no RVO agent +## Keeps flying units apart (ADR 0016). Flying units have no navmesh and stay out of Traffic ## (they never block ground units, and ground units never block them), so after the ## units moved each sim tick, two flyers closer than their bodies plus GAP are pushed ## apart, each by half the overlap times PUSH. Costs nothing without flyers. diff --git a/game/sim/systems/navigation/navmesh_path_service.gd b/game/sim/systems/navigation/navmesh_path_service.gd index 74e6ab5d..763fc136 100644 --- a/game/sim/systems/navigation/navmesh_path_service.gd +++ b/game/sim/systems/navigation/navmesh_path_service.gd @@ -1,12 +1,11 @@ class_name NavmeshPathService extends PathService ## PathService backed by NavigationServer3D navmesh queries on one navigation map. -## Avoidance runs on the same map through server-side RVO agents. +## Units pass each other through Traffic (ADR 0022), not on the navigation server. ## ## Blocked areas (buildings, deposits) are cut out of the region's navmesh with a ## NavmeshCutter, grown by CUT_MARGIN so unit centres keep clear of walls like they -## do of cliffs; the walk grid loses the same cells and each area also becomes a -## static RVO obstacle (ADR 0006). +## do of cliffs; the walk grid loses the same cells (ADR 0006). ## ## On a tidal map (ADR 0014) the region holds one of several navmeshes baked for a few ## sea levels (`set_flood_stages()`): `set_water()` switches to the stage of the sea @@ -21,14 +20,16 @@ const HOVER_MERGE_SCALE: float = 1.0 ## Polygons a path search may visit (the server's default, 4096, cuts long detours ## short on a map of 11 000+ polygons). const PATH_SEARCH_MAX_POLYGONS: int = 65536 +## A unit's lane lies at most this far beside the shared corridor, metres. +const LANE_MAX: float = 9.0 +## Shares of its place in the group a unit tries for each corner, widest first. +const LANE_SHARES: Array[float] = [1.0, 0.5, 0.0] ## How many leading corridor corners a unit may skip when joining. const JOIN_LOOKAHEAD: int = 4 ## Blocked areas are cut out of the navmesh grown by this much (metres): the baked -## agent radius plus room for the widest unit's avoidance radius. +## agent radius plus room for the widest unit to pass another. const CUT_MARGIN: float = NavmeshTools.AGENT_RADIUS + 0.5 -## When false, units get no RVO agents (benchmarks compare both). -var avoidance_enabled: bool = true ## Benchmark and debug counters: shared group corridors built, and group members ## that could not use the corridor and got their own query. var shared_paths_built: int = 0 @@ -48,7 +49,6 @@ var _region: NavigationRegion3D = null ## A region made on the server (the hover map's), used when there is no region node. var _region_rid: RID = RID() var _base_navmesh: NavigationMesh = null -var _obstacles: Dictionary[int, RID] = {} var _apply_scheduled: bool = false ## Per flood stage (one entry without a sea): the baked navmesh, its cutter, the cuts ## it still lacks, whether it must be rebuilt from scratch, its terrain-only cells. @@ -64,10 +64,6 @@ var _stage_clips: PackedFloat32Array = PackedFloat32Array() ## Hovering units' service (lowest stage on its own map), or null without a sea. var _hover_service: NavmeshPathService = null var _hover_map: RID = RID() -## The map RVO agents join (the ground map, also for the hover service). -var _avoidance_map: RID = RID() -## False for the hover service: the ground service owns the RVO obstacles. -var _owns_obstacles: bool = true ## The stage whose (cut) navmesh the region holds. var _shown_stage: int = 0 var _parameters: NavigationPathQueryParameters3D = NavigationPathQueryParameters3D.new() @@ -78,7 +74,6 @@ var _result: NavigationPathQueryResult3D = NavigationPathQueryResult3D.new() ## `region` holds the navmesh that blocked areas are cut out of (optional). func _init(map: RID, walk_grid: WalkGrid = null, region: NavigationRegion3D = null) -> void: _map = map - _avoidance_map = map # The map follows the simulation in step: with the engine's default (updates on # worker threads over several frames) a unit could plan a route over ground the # tide had just closed, when the machine was busy or the sim ran ahead of real time. @@ -143,6 +138,8 @@ func find_group_paths( if path.is_empty(): group_fallback_paths += 1 path = find_path(starts[i], goals[i]) + else: + path = _in_lane(path, starts[i], starts[i] - start_centre) result.append(path) return result @@ -151,6 +148,10 @@ func is_walkable(point: Vector3) -> bool: return _walk_grid == null or _walk_grid.is_walkable(point.x, point.z) +func is_segment_walkable(from: Vector3, to: Vector3) -> bool: + return _walk_grid == null or _walk_grid.is_segment_walkable(from, to) + + ## Makes this a tidal map's service: `navmeshes` are the stages, lowest sea first (the ## first is the region's own), `levels` the sea level each applies from and `clips` ## the height below which its ground was cut away. The walk grid's cells for each @@ -214,9 +215,6 @@ func is_terrain_walkable(point: Vector3) -> bool: func _on_blocked(id: int, area: Rect2) -> void: var cut: Rect2 = area.grow(CUT_MARGIN) _set_cells(cut, false) - var obstacle: RID = _create_obstacle(area) - if obstacle.is_valid(): - _obstacles[id] = obstacle if _hover_service != null: _hover_service.block_area_as(id, area) if _base_navmesh == null: @@ -227,9 +225,6 @@ func _on_blocked(id: int, area: Rect2) -> void: func _on_unblocked(id: int, area: Rect2) -> void: - if _obstacles.has(id): - NavigationServer3D.free_rid(_obstacles[id]) - _obstacles.erase(id) var cut: Rect2 = area.grow(CUT_MARGIN) _restore_cells(cut) if _hover_service != null: @@ -278,13 +273,6 @@ func apply_cuts() -> void: last_cut_msec = (Time.get_ticks_usec() - started) / 1000.0 -## Releases the RVO obstacles (call when the mission ends). -func free_obstacles() -> void: - for rid: RID in _obstacles.values(): - NavigationServer3D.free_rid(rid) - _obstacles.clear() - - ## Builds every other flood stage's cutter now, with the areas blocked so far, so the ## first switch to a stage only applies the cuts made since (instead of half a second ## of cutting in the middle of play). Call once the landing is placed or restored. @@ -300,10 +288,9 @@ func prepare_flood_stages() -> void: _stage_rebuild[stage] = false -## Releases everything this service made on the navigation server (obstacles, the -## hover map and its region). Call when the mission ends. +## Releases everything this service made on the navigation server (the hover map +## and its region). Call when the mission ends. func release() -> void: - free_obstacles() if _hover_service != null: _hover_service.release() _hover_service = null @@ -367,40 +354,10 @@ func _cells_in(area: Rect2) -> Array[Vector2i]: return cells -## A static RVO obstacle over `area`, wound so agents are pushed out. -func _create_obstacle(area: Rect2) -> RID: - if not avoidance_enabled or not _owns_obstacles or not _map.is_valid(): - return RID() - var outline: PackedVector2Array = PackedVector2Array( - [ - area.position, - Vector2(area.end.x, area.position.y), - area.end, - Vector2(area.position.x, area.end.y) - ] - ) - if Geometry2D.is_polygon_clockwise(outline): - outline.reverse() - var points: PackedVector3Array = PackedVector3Array() - for point: Vector2 in outline: - points.append(Vector3(point.x, 0.0, point.y)) - var obstacle: RID = NavigationServer3D.obstacle_create() - NavigationServer3D.obstacle_set_map(obstacle, _map) - NavigationServer3D.obstacle_set_vertices(obstacle, points) - NavigationServer3D.obstacle_set_height(obstacle, 50.0) - NavigationServer3D.obstacle_set_position(obstacle, Vector3(0.0, -10.0, 0.0)) - NavigationServer3D.obstacle_set_avoidance_enabled(obstacle, true) - return obstacle - - func closest_point(point: Vector3) -> Vector3: return NavigationServer3D.map_get_closest_point(_map, point) -func get_avoidance_map() -> RID: - return _avoidance_map if avoidance_enabled else RID() - - func _reset_stages(navmeshes: Array[NavigationMesh]) -> void: _stage_bases = navmeshes _stage_cutters.clear() @@ -413,7 +370,7 @@ func _reset_stages(navmeshes: Array[NavigationMesh]) -> void: ## The hovering units' service: the lowest stage on a navigation map of its own, with -## a walk grid of its own; RVO avoidance stays on the ground map. +## a walk grid of its own. func _make_hover_service(lowest: NavigationMesh, area: Rect2, cell_size: float) -> void: _hover_map = NavigationServer3D.map_create() NavigationServer3D.map_set_cell_size(_hover_map, lowest.cell_size) @@ -439,9 +396,6 @@ func _make_hover_service(lowest: NavigationMesh, area: Rect2, cell_size: float) _hover_service._region_rid = region _hover_service._base_navmesh = lowest _hover_service._reset_stages([lowest] as Array[NavigationMesh]) - _hover_service._avoidance_map = _map - _hover_service._owns_obstacles = false - _hover_service.avoidance_enabled = avoidance_enabled NavigationServer3D.region_set_navigation_mesh(region, lowest) for id: int in _blocked: _hover_service.block_area_as(id, _blocked[id]) @@ -477,6 +431,37 @@ func _join(corridor: PackedVector3Array, start: Vector3, goal: Vector3) -> Packe return PackedVector3Array() +## Moves the shared corners of `path` (all but the last, the unit's own goal) sideways +## by the unit's place in the group (`offset` from the group's centre, at most +## LANE_MAX), so the group travels side by side instead of in single file through +## the same corners (ADR 0022). A corner keeps the largest of the full, half or no +## shift that is walkable and can be reached in a straight line from the corner +## before; if even the plain corner cannot, the path is left as it was. +func _in_lane(path: PackedVector3Array, start: Vector3, offset: Vector3) -> PackedVector3Array: + var shift: Vector3 = Vector3(offset.x, 0.0, offset.z).limit_length(LANE_MAX) + if path.size() < 2 or shift.length_squared() < 0.25: + return path + var lane: PackedVector3Array = PackedVector3Array() + var from: Vector3 = start + for k: int in path.size() - 1: + var corner: Vector3 = path[k] + var placed: bool = false + for share: float in LANE_SHARES: + var moved: Vector3 = corner + shift * share + if _walk_grid.is_segment_walkable(from, moved): + lane.append(moved) + from = moved + placed = true + break + if not placed: + return path + var goal: Vector3 = path[path.size() - 1] + if not _walk_grid.is_segment_walkable(from, goal): + return path + lane.append(goal) + return lane + + static func _centre(points: PackedVector3Array) -> Vector3: var sum: Vector3 = Vector3.ZERO for point: Vector3 in points: diff --git a/game/sim/systems/navigation/path_service.gd b/game/sim/systems/navigation/path_service.gd index 095773eb..96eefa27 100644 --- a/game/sim/systems/navigation/path_service.gd +++ b/game/sim/systems/navigation/path_service.gd @@ -52,6 +52,12 @@ func is_walkable(point: Vector3) -> bool: return not is_blocked(point) and not is_flooded(point) +## True if a unit may walk straight from `from` to `to`. Cheap enough for a few calls +## per unit per tick. The base class has no obstacles to look around. +func is_segment_walkable(_from: Vector3, _to: Vector3) -> bool: + return true + + ## True if the sea closes `point` to ground units now. func is_flooded(point: Vector3) -> bool: return ( @@ -149,9 +155,3 @@ func _on_unblocked(_id: int, _area: Rect2) -> void: ## The nearest walkable point to `point`. Can be expensive; not for per-tick use. func closest_point(point: Vector3) -> Vector3: return point - - -## The navigation map RVO agents should join, or an invalid RID when this backend has -## no server-side avoidance. -func get_avoidance_map() -> RID: - return RID() diff --git a/game/sim/systems/navigation/traffic.gd b/game/sim/systems/navigation/traffic.gd new file mode 100644 index 00000000..b1e38094 --- /dev/null +++ b/game/sim/systems/navigation/traffic.gd @@ -0,0 +1,279 @@ +class_name Traffic +extends RefCounted +## How ground units pass each other (ADR 0022). Once per sim tick, before the units +## move, `solve()` looks at every unit's position and intended velocity and tells it: +## +## - `steer`: a sideways pull, so two units that would touch within HORIZON seconds +## each bend away from where the other will be. Units meeting head-on both keep +## right; the larger unit bends less. +## - `speed_cap`: brake behind a slower unit, or in front of a blocker, instead of +## driving into it. +## - `give_way_to`: a standing friend in the way steps aside (Locomotion walks it +## back afterwards). +## - `push`: a last resort that separates two bodies that overlap anyway. +## +## Deterministic and independent of the frame rate: plain arithmetic over the bodies +## in the order they were added. Flying units do not take part. + +## How far ahead a moving unit looks, seconds. +const HORIZON: float = 2.0 +## ... but never further than this, metres. +const LOOK_MAX: float = 14.0 +## Room kept between two bodies when passing, metres. +const CLEARANCE: float = 0.35 +## Largest sideways pull, as a fraction of the forward direction (1 = 45 degrees). +const MAX_STEER: float = 1.5 +## Strength of the sideways pull. +const STEER_GAIN: float = 2.5 +## A body nearer than this (beyond the radii) is steered around at full strength. +const CLOSE_DISTANCE: float = 2.0 +## Extra pull to the right when meeting oncoming traffic. +const KEEP_RIGHT: float = 0.35 +## A unit ahead moving at least this share of our top speed is followed, not passed. +const FOLLOW_SHARE: float = 0.7 +## Braking for what is ahead uses this share of the unit's braking power, and aims to +## stop this far short (metres): the order to brake arrives a tick late. +const BRAKE_SHARE: float = 0.5 +const BRAKE_MARGIN: float = 0.3 +## Speed never capped below this while steering around something, m/s. +const CREEP_SPEED: float = 0.6 +## A standing friend steps aside when it would be hit within this many seconds. +const GIVE_WAY_TIME: float = 1.2 +## Extra distance a unit stepping aside moves beyond the passing room, metres. +const GIVE_WAY_MARGIN: float = 0.3 +## Share of an overlap removed per tick (all of it: movement adds more each tick). +const PUSH_SHARE: float = 1.0 +## A standing unit counts as crowded with a mover this close (beyond their radii). +const CROWD_DISTANCE: float = 4.0 +## Grid cell for finding neighbours, metres. +const CELL: float = 8.0 +## Largest unit radius the search allows for. +const MAX_RADIUS: float = 2.0 + +## How firmly a body keeps its place when two overlap: it moves, it stands with +## nothing to do, or it holds its ground. +const HOLD_MOVING: int = 0 +const HOLD_LOOSE: int = 1 +const HOLD_FIRM: int = 2 + +var _bodies: Array[TrafficBody] = [] + + +func add(body: TrafficBody) -> void: + _bodies.append(body) + + +func remove(body: TrafficBody) -> void: + _bodies.erase(body) + + +func size() -> int: + return _bodies.size() + + +## Works out every body's steer, speed cap, push and step-aside for this tick. +func solve(dt: float = SimClock.TICK_DELTA) -> void: + var grid: Dictionary[int, Array] = {} + for index: int in _bodies.size(): + var body: TrafficBody = _bodies[index] + body.steer = Vector3.ZERO + body.speed_cap = INF + body.push = Vector3.ZERO + body.give_way_to = Vector3.INF + body.crowded = false + var key: int = _key(floori(body.position.x / CELL), floori(body.position.z / CELL)) + if grid.has(key): + grid[key].append(index) + else: + grid[key] = [index] + # For each standing body: the time until the most urgent mover would hit it. + var give_way_time: PackedFloat32Array = PackedFloat32Array() + give_way_time.resize(_bodies.size()) + give_way_time.fill(INF) + for index: int in _bodies.size(): + _solve_body(index, grid, give_way_time, dt) + + +func _solve_body( + index: int, grid: Dictionary[int, Array], give_way_time: PackedFloat32Array, dt: float +) -> void: + var body: TrafficBody = _bodies[index] + var at: Vector2 = Vector2(body.position.x, body.position.z) + var velocity: Vector2 = Vector2(body.wish.x, body.wish.z) + var speed: float = velocity.length() + var driving: bool = body.moving and speed > 0.01 + var forward: Vector2 = velocity / speed if driving else Vector2.ZERO + var right: Vector2 = Vector2(-forward.y, forward.x) + var reach: float = body.radius + MAX_RADIUS + CLEARANCE + if driving: + reach += minf(speed * HORIZON, LOOK_MAX) + else: + reach += CROWD_DISTANCE + var steer: Vector2 = Vector2.ZERO + var push: Vector2 = Vector2.ZERO + var low_x: int = floori((at.x - reach) / CELL) + var high_x: int = floori((at.x + reach) / CELL) + var low_z: int = floori((at.y - reach) / CELL) + var high_z: int = floori((at.y + reach) / CELL) + for cell_x: int in range(low_x, high_x + 1): + for cell_z: int in range(low_z, high_z + 1): + var cell: Array = grid.get(_key(cell_x, cell_z), []) + for entry: Variant in cell: + var other_index: int = entry + if other_index == index: + continue + var other: TrafficBody = _bodies[other_index] + var offset: Vector2 = Vector2(other.position.x, other.position.z) - at + var distance: float = offset.length() + if distance > reach: + continue + var touching: float = body.radius + other.radius + # Locomotion integrates its already-planned velocity before applying + # this push. Resolve that next position, rather than last tick's contact. + var next_offset: Vector2 = ( + offset + + ( + Vector2( + other.velocity.x - body.velocity.x, other.velocity.z - body.velocity.z + ) + * dt + ) + ) + var next_distance: float = next_offset.length() + if next_distance < touching: + push += _push_apart( + body, other, next_offset, next_distance, index < other_index + ) + if not driving: + if other.moving and distance < touching + CROWD_DISTANCE: + body.crowded = true + continue + var other_velocity: Vector2 = Vector2(other.velocity.x, other.velocity.z) + var relative: Vector2 = velocity - other_velocity + var closing: float = relative.dot(offset) + if closing <= 0.05 * distance: + continue + var time: float = closing / relative.length_squared() + # Slow queues still need local avoidance: a time horizon alone + # otherwise ignores a body already almost touching the bumper. + if time > HORIZON and distance > touching + CLOSE_DISTANCE: + continue + var ahead: float = offset.dot(forward) + if ahead <= 0.0: + continue + # Where the other will be, seen from here, when the two are closest. + var miss: Vector2 = offset - relative * time + var room: float = touching + CLEARANCE + var miss_distance: float = miss.length() + if miss_distance >= room: + continue + var side: float = offset.dot(right) + var other_forward: float = other_velocity.dot(forward) + # A parked neighbour outside the lane needs steering, not braking. + # Moving traffic retains clearance for its next tick's movement. + var brake_room: float = room if other.moving else touching + if ( + absf(side) < brake_room + and _brakes_for(index, other_index, forward, ahead, offset) + ): + var reach_ahead: float = sqrt(brake_room * brake_room - side * side) + var gap: float = maxf(ahead - reach_ahead - BRAKE_MARGIN, 0.0) + var cap: float = ( + maxf(other_forward, 0.0) + sqrt(2.0 * BRAKE_SHARE * body.acceleration * gap) + ) + body.speed_cap = minf(body.speed_cap, cap) + if other.moving and other_forward >= FOLLOW_SHARE * body.max_speed: + # Follow it: the speed cap keeps the distance. + continue + var away: Vector2 = -miss + if other_forward < 0.0: + away += right * KEEP_RIGHT * room + away -= forward * away.dot(forward) + if away.length_squared() < 0.0001: + away = right + # Urgent when it is soon, and when it is close however slowly it comes. + var soon: float = 1.0 - time / HORIZON + var close: float = 1.0 - (distance - touching) / CLOSE_DISTANCE + var urgency: float = maxf(soon, close) * (0.4 + 0.6 * (1.0 - miss_distance / room)) + steer += away.normalized() * urgency * _share(body, other) * STEER_GAIN + if ( + body.asks_way + and other.gives_way + and other.faction == body.faction + and (time < GIVE_WAY_TIME or distance < touching + CLOSE_DISTANCE) + and miss_distance < touching + and time < give_way_time[other_index] + ): + give_way_time[other_index] = time + var to_side: float = 1.0 if side > 0.05 else -1.0 + var step: Vector2 = right * to_side * (room - absf(side) + GIVE_WAY_MARGIN) + other.give_way_to = other.position + Vector3(step.x, 0.0, step.y) + if steer.length_squared() > 0.0: + steer = steer.limit_length(MAX_STEER) + body.steer = Vector3(steer.x, 0.0, steer.y) + body.speed_cap = maxf(body.speed_cap, CREEP_SPEED) + body.push = Vector3(push.x, 0.0, push.y) + + +## True when body `index` is the one to brake for body `other_index`, which is `ahead` +## metres ahead along `forward`. Of two units driving roughly the same way toward the +## same spot, only the one further back brakes; if both did, each would slow to the +## other's speed in turn until both crawled. +func _brakes_for( + index: int, other_index: int, forward: Vector2, ahead: float, offset: Vector2 +) -> bool: + var other: TrafficBody = _bodies[other_index] + var other_wish: Vector2 = Vector2(other.wish.x, other.wish.z) + var other_speed: float = other_wish.length() + if not other.moving or other_speed <= 0.01: + return true + var other_way: Vector2 = other_wish / other_speed + if other_way.dot(forward) <= 0.0: + return true + # How far ahead of the other this body is, seen along the other's way. + var lead: float = -offset.dot(other_way) + if is_equal_approx(lead, ahead): + return index > other_index + return ahead > lead + + +## How much of an encounter `body` answers for: the smaller unit bends more, and all +## of it falls to the mover when the other stands still. +static func _share(body: TrafficBody, other: TrafficBody) -> float: + if not other.moving: + return 1.0 + var own: float = body.radius * body.radius + var theirs: float = other.radius * other.radius + return clampf(2.0 * theirs / (own + theirs), 0.5, 1.5) + + +## The shift that takes `body` out of `other`. Whoever is freer to move makes all the +## room: a moving body for a standing one, a standing body with nothing to do for one +## that holds its ground. Two alike share it, the smaller giving more. A body that +## holds its ground is never shifted. +static func _push_apart( + body: TrafficBody, other: TrafficBody, offset: Vector2, distance: float, first: bool +) -> Vector2: + var own_hold: int = _hold(body) + var other_hold: int = _hold(other) + if own_hold > other_hold or own_hold == HOLD_FIRM: + return Vector2.ZERO + var direction: Vector2 = offset / distance if distance > 0.001 else Vector2.RIGHT + if distance <= 0.001 and not first: + direction = Vector2.LEFT + var share: float = 1.0 + if own_hold == other_hold: + var own: float = body.radius * body.radius + share = other.radius * other.radius / (own + other.radius * other.radius) + return -direction * (body.radius + other.radius - distance) * PUSH_SHARE * share + + +## How firmly `body` keeps its place: HOLD_MOVING, HOLD_LOOSE or HOLD_FIRM. +static func _hold(body: TrafficBody) -> int: + if body.moving: + return HOLD_MOVING + return HOLD_LOOSE if body.gives_way else HOLD_FIRM + + +static func _key(cell_x: int, cell_z: int) -> int: + return (cell_x + 32768) * 65536 + cell_z + 32768 diff --git a/game/sim/systems/navigation/traffic.gd.uid b/game/sim/systems/navigation/traffic.gd.uid new file mode 100644 index 00000000..0e991536 --- /dev/null +++ b/game/sim/systems/navigation/traffic.gd.uid @@ -0,0 +1 @@ +uid://bi708eiicul3q diff --git a/game/sim/systems/navigation/traffic_body.gd b/game/sim/systems/navigation/traffic_body.gd new file mode 100644 index 00000000..b1d2f072 --- /dev/null +++ b/game/sim/systems/navigation/traffic_body.gd @@ -0,0 +1,37 @@ +class_name TrafficBody +extends RefCounted +## One ground unit as Traffic sees it. Locomotion fills in the first block after every +## tick; Traffic fills in the second at the start of the next. + +## Where the unit stands (the height is ignored). +var position: Vector3 = Vector3.ZERO +## The velocity it means to move with this tick; zero while standing. +var velocity: Vector3 = Vector3.ZERO +## The velocity it would move with if nothing were in the way (straight along its +## path); zero while standing. Traffic judges what is in the way by this, so that +## bending away does not make the reason for bending disappear. +var wish: Vector3 = Vector3.ZERO +var radius: float = 0.5 +var max_speed: float = 1.0 +var acceleration: float = 1.0 +var faction: int = 0 +## True while it follows a path (an order's, or a step aside). +var moving: bool = false +## True while it moves on an order: only then do standing friends step aside for it. A +## unit that is itself stepping aside (or walking back) drives around them instead, so +## two units never keep making room for each other. +var asks_way: bool = false +## True when it would step aside for a friend coming through: standing with nothing +## to do. +var gives_way: bool = false + +## Sideways pull on the travel direction, to pass what is ahead (length 0..MAX_STEER). +var steer: Vector3 = Vector3.ZERO +## Top speed for now, so it does not drive into what is ahead; INF = no limit. +var speed_cap: float = INF +## Shift that takes it out of a body it overlaps. +var push: Vector3 = Vector3.ZERO +## Where to step aside to for a friend coming through; INF = stay. +var give_way_to: Vector3 = Vector3.INF +## True while something drives close by: no time to walk back to its post. +var crowded: bool = false diff --git a/game/sim/systems/navigation/traffic_body.gd.uid b/game/sim/systems/navigation/traffic_body.gd.uid new file mode 100644 index 00000000..51ddcf30 --- /dev/null +++ b/game/sim/systems/navigation/traffic_body.gd.uid @@ -0,0 +1 @@ +uid://xbomk3vcooni diff --git a/game/sim/systems/sim_world.gd b/game/sim/systems/sim_world.gd index 8e6bbce5..f0d9a276 100644 --- a/game/sim/systems/sim_world.gd +++ b/game/sim/systems/sim_world.gd @@ -40,6 +40,8 @@ var dry_crossings: PackedVector3Array = PackedVector3Array() var air_paths: PathService = PathService.new() ## Keeps flying units apart (idle without any). var flight: FlightSystem = FlightSystem.new() +## How ground units pass each other (ADR 0022); null = they do not (benchmarks). +var traffic: Traffic = Traffic.new() ## Tree crowns, (centre x, centre z, radius x, radius z) each (the map's ## `canopy_zones`); a CanopyRule hides what stands under them. var canopy_zones: PackedVector4Array = PackedVector4Array() @@ -126,7 +128,7 @@ func spawn_unit(def: UnitDef, faction: int, at: Vector3, yaw: float = 0.0) -> Un var unit_paths: PathService = paths.for_hover() if def.hovers else paths if def.flies: unit_paths = air_paths - unit.locomotion.setup(def, at, yaw, unit_paths, heights) + unit.locomotion.setup(def, at, yaw, unit_paths, heights, traffic, faction) unit.locomotion.set_speed_scale(conditions.speed_factor(def.rides_above_ground())) units.append(unit) unit.tree_exiting.connect(_on_unit_exiting.bind(unit)) @@ -404,6 +406,9 @@ func _on_ticked(tick: int) -> void: if stealth != null: stealth.tick(tick, dt, units) mark = _section(&"stealth", mark) + if traffic != null: + traffic.solve(dt) + mark = _section(&"traffic", mark) for unit: Unit in units: unit.sim_tick(dt) flight.tick(units, dt) diff --git a/game/tests/ai/test_commander.gd b/game/tests/ai/test_commander.gd index 408b6742..04ce5f32 100644 --- a/game/tests/ai/test_commander.gd +++ b/game/tests/ai/test_commander.gd @@ -135,10 +135,6 @@ func test_a_lost_retrieval_squad_makes_the_next_bigger_and_later() -> void: def.blocks_sight = false def.carriable = true _f.world.spawn_prop(def, Vector3(0, 0, 0)) - # Power for the guns, and the guns around the artefact. - _f.building(_f.hub, Vector3(-60, 0, -60), AiFixture.ENEMY) - for at: Vector3 in [Vector3(6, 0, 4), Vector3(-6, 0, 4), Vector3(0, 0, -6)]: - _f.building(_f.combat.sentry, at, AiFixture.ENEMY) _f.world.economy.stockpile(AiFixture.AI).alloy = 0 _f.building(_f.hub, Vector3(60, 0, 60)) _f.soldiers(3, Vector3(50, 0, 50)) @@ -146,8 +142,18 @@ func test_a_lost_retrieval_squad_makes_the_next_bigger_and_later() -> void: _f.profile.retrieve_squad_size = 2 _f.profile.retrieve_after_seconds = 0.0 _start_commander() + _f.tick(20) + assert_not_null(_commander.retrieval, "a retrieval squad formed") + if _commander.retrieval == null: + return + var lost_members: Array[Unit] = _commander.retrieval.members.duplicate() + assert_eq(lost_members.size(), 2) + # Test the response to a loss, without depending on a particular traffic + # trajectory through gunfire (a squad member may legitimately escape). + for unit: Unit in lost_members: + unit.health.take(unit.health.max_health) _f.tick(900) - assert_eq(_commander.retrievals_lost, 1, "the first squad of two fell to the guns") + assert_eq(_commander.retrievals_lost, 1, "the first squad of two was lost") assert_eq(_commander.retrieve_squad_size(), 4, "the next one is twice the size") _f.tick(900) assert_null(_commander.retrieval, "the one soldier left is not sent alone") @@ -158,3 +164,5 @@ func test_a_lost_retrieval_squad_makes_the_next_bigger_and_later() -> void: var saved: Dictionary = _commander.to_dict() var lost: int = saved["retrievals_lost"] assert_eq(lost, 1, "the losses are saved") + var retry_after: int = saved["retrieve_after"] + assert_gt(retry_after, 20, "another attempt is delayed after the loss") diff --git a/game/tests/audio/test_audio_assets.gd b/game/tests/audio/test_audio_assets.gd index 0ad3ce9a..2951ff7b 100644 --- a/game/tests/audio/test_audio_assets.gd +++ b/game/tests/audio/test_audio_assets.gd @@ -275,9 +275,9 @@ func test_discovery_events_exist_with_their_buses() -> void: "signal/scan_loop": &"Discovery", "signal/scan_interrupted": &"Discovery", "sting/mus_swell_antecedent": &"Discovery", - "ui/ui_codex_open": &"UI", - "ui/ui_codex_close": &"UI", - "ui/ui_codex_entry": &"UI", + "ui/ui_survey_log_open": &"UI", + "ui/ui_survey_log_close": &"UI", + "ui/ui_survey_log_entry": &"UI", "ui/ui_intel_tick": &"UI", "ui/ui_option_button": &"UI", "advisor/advisor_discovery": &"Advisor", diff --git a/game/tests/audio/test_discovery_sound_router.gd b/game/tests/audio/test_discovery_sound_router.gd index b5bb2cee..720205f2 100644 --- a/game/tests/audio/test_discovery_sound_router.gd +++ b/game/tests/audio/test_discovery_sound_router.gd @@ -161,10 +161,10 @@ func test_field_options_play_their_effect() -> void: assert_eq(_played.size(), 0, "enemy options are not announced") -func test_codex_entry_and_codex_interface_sounds() -> void: - Events.codex_entry_added.emit(Resource.new()) - assert_eq(_played, [DiscoveryCues.CODEX_ENTRY] as Array[StringName]) - for kind: StringName in [&"codex_open", &"codex_close", &"option_button"]: +func test_survey_log_entry_and_interface_sounds() -> void: + Events.survey_log_entry_added.emit(Resource.new()) + assert_eq(_played, [DiscoveryCues.SURVEY_LOG_ENTRY] as Array[StringName]) + for kind: StringName in [&"survey_log_open", &"survey_log_close", &"option_button"]: var ids: Array[StringName] = AudioCueSelector.feedback_event(kind) assert_true(ResourceLoader.exists(_path_of(ids[0])), "ui_feedback %s" % kind) diff --git a/game/tests/balance/balance_run.gd b/game/tests/balance/balance_run.gd index cbc92106..92c5563e 100644 --- a/game/tests/balance/balance_run.gd +++ b/game/tests/balance/balance_run.gd @@ -3,7 +3,7 @@ extends Node ## with the ReferencePlayer in the player's seat (or nobody, `--player=idle`) until it ## ends or the time cap, then prints a short report and one `BALANCE {json}` line that ## `tools/balance.sh` collects. Deterministic for a seed as far as the sim is (the -## commanders' dice are seeded; avoidance timing can still differ slightly). +## commanders' dice are seeded). ## ## godot --headless --fixed-fps 60 --path game res://tests/balance/balance_run.tscn \ ## -- --mission=conquest --seed=1 --difficulty=normal [--player=idle] diff --git a/game/tests/bench/bench_navigation.gd b/game/tests/bench/bench_navigation.gd index f8275073..ac0373ae 100644 --- a/game/tests/bench/bench_navigation.gd +++ b/game/tests/bench/bench_navigation.gd @@ -1,14 +1,15 @@ extends Node -## Phase 0 navigation spike (not part of check.sh): spawns UNIT_COUNT units on Kessel +## Phase 0 navigation spike (not part of check.sh): spawns _unit_count units on Kessel ## Proving, orders all of them across the map in one MoveCommand and reports the sim ## cost per tick, the path-request burst and frame times until everyone has arrived. ## ## Headless: godot --headless --path game res://tests/bench/bench_navigation.tscn ## Windowed: same without --headless (or play the scene from the editor). -## Add `-- --no-avoidance` to run without RVO agents. +## Add `-- --no-traffic` to run without Traffic (units pass through each other) and +## `-- --units=24` for another group size. const MAP: PackedScene = preload("res://maps/kessel_proving/kessel_proving.tscn") -const UNIT_COUNT: int = 200 +const DEFAULT_UNIT_COUNT: int = 200 const SPAWN_AREA: Rect2 = Rect2(-112.0, 62.0, 100.0, 48.0) const SPAWN_SPACING: float = 4.0 const TARGET: Vector3 = Vector3(55.0, 0.0, -40.0) @@ -25,8 +26,10 @@ const ROSTER: Array[String] = [ var _map: LandingMap var _frame: int = 0 -var _spawned_at_msec: int = -1 +var _spawned_at_tick: int = -1 var _ordered_at_msec: int = -1 +var _ordered_at_tick: int = -1 +var _seconds: float = TIMEOUT_SECONDS var _physics_started_usec: int = 0 var _tick_costs: Array[float] = [] var _world_costs: Array[float] = [] @@ -39,19 +42,27 @@ var _ninety_five_seconds: float = -1.0 var _path_burst_usec: int = 0 var _slot_burst_usec: int = 0 var _command_usec: int = 0 -var _safe_seen: int = 0 var _target_walkable: bool = false var _last_frame_usec: int = 0 -var _avoidance: bool = true +var _traffic: bool = true +var _unit_count: int = DEFAULT_UNIT_COUNT +var _goals: Dictionary[int, Vector3] = {} +var _projected_slots: int = 0 func _ready() -> void: process_physics_priority = -100 - _avoidance = not OS.get_cmdline_user_args().has("--no-avoidance") + _traffic = not OS.get_cmdline_user_args().has("--no-traffic") + for argument: String in OS.get_cmdline_user_args(): + if argument.begins_with("--units="): + _unit_count = int(argument.trim_prefix("--units=")) + elif argument.begins_with("--seconds="): + _seconds = float(argument.trim_prefix("--seconds=")) _map = MAP.instantiate() as LandingMap _map.with_mission = false add_child(_map) - (_map.world.paths as NavmeshPathService).avoidance_enabled = _avoidance + if not _traffic: + _map.world.traffic = null Events.sim_ticked.connect(_on_sim_ticked) @@ -69,14 +80,14 @@ func _process(_delta: float) -> void: _navigation_ms.append(Performance.get_monitor(Performance.TIME_NAVIGATION_PROCESS) * 1000.0) _last_frame_usec = now # Wait for the navigation map to sync before spawning (closest_point needs it), - # then give avoidance agents a moment before ordering. - if _spawned_at_msec < 0: + # then give the units a moment before ordering. + if _spawned_at_tick < 0: var map: RID = get_viewport().world_3d.navigation_map if NavigationServer3D.map_get_closest_point(map, _map.map_def.landing_zone) != Vector3.ZERO: _spawn() - _spawned_at_msec = Time.get_ticks_msec() + _spawned_at_tick = _map.context.sim_clock.get_tick() elif _ordered_at_msec < 0: - if Time.get_ticks_msec() - _spawned_at_msec > 1000: + if _map.context.sim_clock.get_tick() - _spawned_at_tick >= SimClock.TICK_RATE: _order() else: _check_done() @@ -86,9 +97,9 @@ func _spawn() -> void: var paths: PathService = _map.world.paths var count: int = 0 var z: float = SPAWN_AREA.position.y - while z <= SPAWN_AREA.end.y and count < UNIT_COUNT: + while z <= SPAWN_AREA.end.y and count < _unit_count: var x: float = SPAWN_AREA.position.x - while x <= SPAWN_AREA.end.x and count < UNIT_COUNT: + while x <= SPAWN_AREA.end.x and count < _unit_count: var point: Vector3 = Vector3(x, _map.heights.sample(x, z), z) var walkable: Vector3 = paths.closest_point(point) if Vector2(walkable.x - x, walkable.z - z).length() < 0.5: @@ -97,7 +108,7 @@ func _spawn() -> void: count += 1 x += SPAWN_SPACING z += SPAWN_SPACING - print("bench: spawned %d units (avoidance %s)" % [count, "on" if _avoidance else "off"]) + print("bench: spawned %d units (traffic %s)" % [count, "on" if _traffic else "off"]) var map: RID = get_viewport().world_3d.navigation_map print("bench: navigation map %s" % map) @@ -133,44 +144,82 @@ func _order() -> void: started = Time.get_ticks_usec() command.execute() _command_usec = Time.get_ticks_usec() - started + for unit: Unit in _map.world.units: + var wanted: Vector3 = unit.orders.last_destination(unit.sim_position()) + var reachable: Vector3 = unit.locomotion.get_destination() + _goals[unit.entity_id] = reachable + if Vector2(wanted.x - reachable.x, wanted.z - reachable.z).length() > 0.5: + _projected_slots += 1 _ordered_at_msec = Time.get_ticks_msec() + _ordered_at_tick = _map.context.sim_clock.get_tick() func _on_sim_ticked(_tick: int) -> void: if _ordered_at_msec < 0: return var cost: float = (Time.get_ticks_usec() - _physics_started_usec) / 1000.0 - for unit: Unit in _map.world.units: - if unit.locomotion.get(&"_has_safe_velocity"): - _safe_seen += 1 _tick_costs.append(cost) _world_costs.append(_map.world.last_tick_usec / 1000.0) func _check_done() -> void: - var elapsed: float = (Time.get_ticks_msec() - _ordered_at_msec) / 1000.0 + var elapsed: float = ( + (_map.context.sim_clock.get_tick() - _ordered_at_tick) * SimClock.TICK_DELTA + ) var idle: int = 0 + var reached: int = 0 for unit: Unit in _map.world.units: - if unit.orders.is_idle() and unit.locomotion.mover.speed == 0.0: + if _settled(unit): idle += 1 + if _at_goal(unit): + reached += 1 var total: int = _map.world.units.size() - if _ninety_five_seconds < 0.0 and idle >= ceili(total * 0.95): + if _ninety_five_seconds < 0.0 and reached >= ceili(total * 0.95): _ninety_five_seconds = elapsed - if idle == total or elapsed > TIMEOUT_SECONDS: - if idle == total: + if idle == total or elapsed > _seconds: + if reached == total: _all_arrived_seconds = elapsed - _report(idle, total) + _report(reached, idle, total) get_tree().quit() -func _report(idle: int, total: int) -> void: +func _at_goal(unit: Unit, precise: bool = false) -> bool: + var goal: Vector3 = _goals[unit.entity_id] + var offset: Vector3 = unit.sim_position() - goal + var tolerance: float = maxf(unit.def.radius, 0.5) + if not precise: + # A dense physical formation may make room for a neighbour instead of + # sitting exactly on its lattice point. Keep both accuracy counts below. + tolerance = unit.def.radius * 2.0 + Traffic.CLEARANCE + return Vector2(offset.x, offset.z).length() <= tolerance + + +func _settled(unit: Unit) -> bool: + var motion: Locomotion = unit.locomotion + return ( + unit.orders.is_idle() + and motion.mover.speed == 0.0 + and not motion.mover.has_path() + and not motion._giving_way + and motion._post == Vector3.INF + ) + + +func _report(reached: int, idle: int, total: int) -> void: + var centered: int = 0 + for unit: Unit in _map.world.units: + if _settled(unit) and _at_goal(unit, true): + centered += 1 var lines: PackedStringArray = [ "bench: ==== navigation benchmark ====", + "bench: arrival times are simulation seconds (accelerate headless with --fixed-fps 60)", + "bench: renderer %s, traffic %s" % [DisplayServer.get_name(), "on" if _traffic else "off"], + "bench: units %d, arrived %d, settled %d" % [total, reached, idle], + "bench: arrival tolerance one body width + clearance; within one radius %d" % centered, ( - "bench: renderer %s, avoidance %s" - % [DisplayServer.get_name(), "on" if _avoidance else "off"] + "bench: slots projected to reachable terrain %d (arrival checks the path endpoint)" + % _projected_slots ), - "bench: units %d, arrived %d" % [total, idle], ( "bench: 95%% arrived after %.1f s, all after %.1f s" % [_ninety_five_seconds, _all_arrived_seconds] @@ -191,7 +240,6 @@ func _report(idle: int, total: int) -> void: (_map.world.paths as NavmeshPathService).group_fallback_paths, ] ), - "bench: unit-ticks with an avoidance velocity: %d" % _safe_seen, "bench: sim per tick (all) %s" % _stats(_tick_costs), "bench: world per tick %s" % _stats(_world_costs), "bench: frame time %s" % _stats(_frame_ms), @@ -199,6 +247,33 @@ func _report(idle: int, total: int) -> void: "bench: physics time %s" % _stats(_physics_ms), "bench: navigation time %s" % _stats(_navigation_ms), ] + if OS.get_cmdline_user_args().has("--details"): + for unit: Unit in _map.world.units: + if _settled(unit) and _at_goal(unit): + continue + var motion: Locomotion = unit.locomotion + lines.append( + "bench: pending state retries %d post %s" % [motion._repaths, motion._post] + ) + ( + lines + . append( + ( + "bench: pending %d %s at %s goal %s speed %.2f travelling %s yielding %s corner %d/%d" + % [ + unit.entity_id, + unit.def.id, + motion.mover.position, + _goals[unit.entity_id], + motion.mover.speed, + motion.is_travelling(), + motion._giving_way, + motion.mover.path_index, + motion.mover.path.size() + ] + ) + ) + ) var text: String = "\n".join(lines) print(text) # Also saved, since an editor-launched run's output is gone once it quits. diff --git a/game/tests/discovery/discovery_fixture.gd b/game/tests/discovery/discovery_fixture.gd index 56a4f068..a1a77f11 100644 --- a/game/tests/discovery/discovery_fixture.gd +++ b/game/tests/discovery/discovery_fixture.gd @@ -103,8 +103,8 @@ func discovery( def.scan_time = 2.0 def.radius = 2.0 def.blocks_movement = false - def.codex_title = "Entry %s" % id - def.codex_text = "Text of %s." % id + def.log_title = "Entry %s" % id + def.log_text = "Text of %s." % id return def diff --git a/game/tests/discovery/test_scanning.gd b/game/tests/discovery/test_scanning.gd index 26d93ddc..99691a70 100644 --- a/game/tests/discovery/test_scanning.gd +++ b/game/tests/discovery/test_scanning.gd @@ -29,9 +29,9 @@ func test_a_scan_resolves_the_site_and_pays_intel() -> void: assert_eq(site.resolved_by, 0) assert_eq(_f.pile().intel, def.intel_reward) assert_signal_emitted_with_parameters(Events, "discovery_made", [site, def, 0]) - assert_signal_emitted_with_parameters(Events, "codex_entry_added", [def]) + assert_signal_emitted_with_parameters(Events, "survey_log_entry_added", [def]) assert_signal_emitted_with_parameters(Events, "intel_changed", [0, def.intel_reward]) - assert_eq(_f.world.discovery.codex(0), [def] as Array[DiscoveryDef]) + assert_eq(_f.world.discovery.survey_log(0), [def] as Array[DiscoveryDef]) assert_true(scanner.orders.is_idle(), "the scan order ends with the scan") diff --git a/game/tests/missions/test_tutorial_hints.gd b/game/tests/missions/test_tutorial_hints.gd index f34ef287..d01f3d6c 100644 --- a/game/tests/missions/test_tutorial_hints.gd +++ b/game/tests/missions/test_tutorial_hints.gd @@ -150,6 +150,17 @@ func test_a_paused_mission_holds_its_hints() -> void: hints.suspended = true hints._process(TutorialHints.AUTO_HIDE_SECONDS + 1.0) assert_not_null(hints.shown, "the card does not time out under the pause menu") + assert_false(hints._card.visible, "the hint does not overlap the pause menu") + hints.obscured = true + hints.suspended = false + assert_false(hints._card.visible, "resuming does not uncover a hint over the Survey Log") + hints._process(TutorialHints.AUTO_HIDE_SECONDS + 1.0) + assert_not_null(hints.shown, "reading the log preserves the hint") + hints.suspended = true + hints.obscured = false + assert_false(hints._card.visible, "closing the log still respects the pause menu") + hints.suspended = false + assert_true(hints._card.visible, "the same hint returns when the overlays close") hints.end_mission() diff --git a/game/tests/test_traffic.gd b/game/tests/test_traffic.gd new file mode 100644 index 00000000..b09cf278 --- /dev/null +++ b/game/tests/test_traffic.gd @@ -0,0 +1,281 @@ +extends GutTest +## Traffic (ADR 0022): ground units pass each other without driving through one +## another. Vehicle-like units on open ground with the straight-line PathService. + +const DT: float = 0.1 +## Two bodies count as overlapping when they are this much inside each other, metres. +const OVERLAP_TOLERANCE: float = 0.1 + + +class CornerVisibility: + extends PathService + var clear: bool = false + + func is_segment_walkable(_from: Vector3, _to: Vector3) -> bool: + return clear + + +var _def: UnitDef +var _queue: CommandQueue +var _traffic: Traffic +var _units: Array[Unit] +## The deepest overlap of any two units seen while ticking, metres. +var _deepest_overlap: float + + +func before_each() -> void: + _def = _make_def(1.2, 6.0) + _queue = CommandQueue.new() + _traffic = Traffic.new() + _units = [] + _deepest_overlap = 0.0 + + +func _make_def(radius: float, speed: float) -> UnitDef: + var def: UnitDef = UnitDef.new() + def.move_speed = speed + def.acceleration = 8.0 + def.turn_speed = 120.0 + def.radius = radius + return def + + +func _unit(at: Vector3, facing: Vector3, faction: int = 0, def: UnitDef = null) -> Unit: + var unit: Unit = Unit.new() + unit.def = def if def != null else _def + unit.faction = faction + unit.add_child(Locomotion.new()) + unit.add_child(UnitOrders.new()) + add_child_autofree(unit) + var traffic: Traffic = _traffic + unit.locomotion.setup( + unit.def, at, Mover.yaw_for(facing), PathService.new(), null, traffic, faction + ) + _units.append(unit) + return unit + + +func _move(unit: Unit, target: Vector3) -> void: + _queue.push(MoveCommand.new(MoveCommand.KIND_MOVE, unit.faction, [unit], target)) + + +func _tick(ticks: int) -> void: + for i: int in ticks: + _queue.flush() + if _traffic != null: + _traffic.solve() + for unit: Unit in _units: + unit.sim_tick(DT) + _measure_overlap() + + +func _measure_overlap() -> void: + for i: int in _units.size(): + for j: int in range(i + 1, _units.size()): + var gap: float = ( + _flat(_units[i].sim_position()).distance_to(_flat(_units[j].sim_position())) + - _units[i].def.radius + - _units[j].def.radius + ) + _deepest_overlap = maxf(_deepest_overlap, -gap) + + +static func _flat(point: Vector3) -> Vector2: + return Vector2(point.x, point.z) + + +func _assert_at(unit: Unit, target: Vector3, within: float, what: String) -> void: + assert_lt(_flat(unit.sim_position()).distance_to(_flat(target)), within, what) + + +func test_without_traffic_units_drive_through_each_other() -> void: + _traffic = null + var north: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + var south: Unit = _unit(Vector3(0, 0, -20), Vector3.BACK) + _move(north, Vector3(0, 0, -20)) + _move(south, Vector3(0, 0, 20)) + _tick(120) + assert_gt(_deepest_overlap, 1.5, "the case traffic exists for") + + +func test_head_on_units_pass_on_the_right() -> void: + var north: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + var south: Unit = _unit(Vector3(0, 0, -20), Vector3.BACK) + _move(north, Vector3(0, 0, -20)) + _move(south, Vector3(0, 0, 20)) + var passed_on_right: bool = false + for i: int in 140: + _tick(1) + if absf(north.sim_position().z) < 1.0: + # Driving toward -Z, right is +X. + passed_on_right = north.sim_position().x > 0.5 + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + assert_true(passed_on_right, "kept right") + _assert_at(north, Vector3(0, 0, -20), 0.5, "north arrived") + _assert_at(south, Vector3(0, 0, 20), 0.5, "south arrived") + assert_true(north.orders.is_idle() and south.orders.is_idle(), "orders done") + + +func test_two_columns_meeting_head_on_get_through() -> void: + var targets: Array[Vector3] = [] + for i: int in 4: + _unit(Vector3(0, 0, 20 + i * 4.0), Vector3.FORWARD) + targets.append(Vector3(0, 0, -20 - i * 4.0)) + for i: int in 4: + _unit(Vector3(0, 0, -20 - i * 4.0), Vector3.BACK) + targets.append(Vector3(0, 0, 20 + i * 4.0)) + for i: int in _units.size(): + _move(_units[i], targets[i]) + _tick(250) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + for i: int in _units.size(): + _assert_at(_units[i], targets[i], 0.5, "unit %d arrived" % i) + + +func test_crossing_units_do_not_touch() -> void: + var north: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + var west: Unit = _unit(Vector3(-20, 0, 0), Vector3.RIGHT) + _move(north, Vector3(0, 0, -20)) + _move(west, Vector3(20, 0, 0)) + _tick(140) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + _assert_at(north, Vector3(0, 0, -20), 0.5, "north arrived") + _assert_at(west, Vector3(20, 0, 0), 0.5, "west arrived") + + +func test_a_standing_friend_steps_aside_and_walks_back() -> void: + var parked: Unit = _unit(Vector3.ZERO, Vector3.FORWARD) + var driver: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + _move(driver, Vector3(0, 0, -20)) + var moved_away: float = 0.0 + for i: int in 140: + _tick(1) + moved_away = maxf(moved_away, _flat(parked.sim_position()).length()) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + assert_gt(moved_away, 0.5, "the parked unit stepped aside") + _assert_at(driver, Vector3(0, 0, -20), 0.5, "the driver arrived") + _assert_at(parked, Vector3.ZERO, Locomotion.RETURN_DISTANCE + 0.1, "and it walked back") + assert_true(parked.orders.is_idle(), "without ever having an order") + assert_eq(parked.locomotion.mover.speed, 0.0, "standing again") + + +func test_a_slow_queue_still_gets_room_from_an_idle_friend() -> void: + var parked: Unit = _unit(Vector3.ZERO, Vector3.FORWARD) + var driver: Unit = _unit(Vector3(0, 0, 6), Vector3.FORWARD, 0, _make_def(1.2, 0.6)) + _move(driver, Vector3(0, 0, -6)) + var moved_away: float = 0.0 + for i: int in 300: + _tick(1) + moved_away = maxf(moved_away, _flat(parked.sim_position()).length()) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "remain separated while creeping") + assert_gt(moved_away, 0.5, "idle friends make room even for a slow queue") + _assert_at(driver, Vector3(0, 0, -6), 0.5, "slow traffic gets through too") + _assert_at(parked, Vector3.ZERO, Locomotion.RETURN_DISTANCE + 0.1, "idle friend returns") + + +func test_an_idle_friend_does_not_step_across_a_blocked_segment() -> void: + var parked: Unit = _unit(Vector3.ZERO, Vector3.FORWARD) + var visibility: CornerVisibility = CornerVisibility.new() + parked.locomotion.paths = visibility + var driver: Unit = _unit(Vector3(0, 0, 6), Vector3.FORWARD) + _move(driver, Vector3(0, 0, -8)) + var moved_away: float = 0.0 + for i: int in 160: + _tick(1) + moved_away = maxf(moved_away, _flat(parked.sim_position()).length()) + assert_eq(moved_away, 0.0, "valid endpoints do not permit crossing blocked ground") + _assert_at(driver, Vector3(0, 0, -8), 0.5, "the driver routes around the standing friend") + + +func test_a_unit_holding_its_ground_is_driven_around() -> void: + var parked: Unit = _unit(Vector3.ZERO, Vector3.FORWARD) + var driver: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + _move(driver, Vector3(0, 0, -20)) + for i: int in 140: + parked.locomotion.holds_ground = true + _queue.flush() + _traffic.solve() + driver.sim_tick(DT) + parked.locomotion.tick(DT) + _measure_overlap() + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + assert_eq(parked.sim_position(), Vector3.ZERO, "it did not move") + _assert_at(driver, Vector3(0, 0, -20), 0.5, "the driver arrived") + + +func test_an_enemy_in_the_way_does_not_step_aside() -> void: + var enemy: Unit = _unit(Vector3.ZERO, Vector3.FORWARD, 1) + var driver: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD) + _move(driver, Vector3(0, 0, -20)) + _tick(140) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + assert_eq(enemy.sim_position(), Vector3.ZERO, "it did not move") + _assert_at(driver, Vector3(0, 0, -20), 0.5, "the driver arrived") + + +func test_a_fast_unit_does_not_ram_a_slow_one_ahead() -> void: + var slow: Unit = _unit(Vector3(0, 0, 10), Vector3.FORWARD, 0, _make_def(1.6, 2.6)) + var fast: Unit = _unit(Vector3(0, 0, 20), Vector3.FORWARD, 0, _make_def(0.8, 11.0)) + _move(slow, Vector3(0, 0, -40)) + _move(fast, Vector3(0, 0, -60)) + _tick(250) + assert_lt(_deepest_overlap, OVERLAP_TOLERANCE, "never inside each other") + _assert_at(fast, Vector3(0, 0, -60), 0.5, "the fast unit got past and arrived") + _assert_at(slow, Vector3(0, 0, -40), 0.5, "the slow unit arrived") + + +func test_overlapping_units_are_pushed_apart() -> void: + var first: Unit = _unit(Vector3.ZERO, Vector3.FORWARD) + var second: Unit = _unit(Vector3(0.4, 0, 0), Vector3.FORWARD) + _tick(30) + var distance: float = _flat(first.sim_position()).distance_to(_flat(second.sim_position())) + assert_gt(distance, _def.radius * 2.0 - OVERLAP_TOLERANCE, "apart") + + +func test_passing_beside_a_parked_body_does_not_brake() -> void: + var driver: TrafficBody = TrafficBody.new() + driver.radius = 1.2 + driver.max_speed = 6.0 + driver.acceleration = 8.0 + driver.moving = true + driver.velocity = Vector3.FORWARD * 6.0 + driver.wish = driver.velocity + var parked: TrafficBody = TrafficBody.new() + parked.radius = 1.2 + parked.position = Vector3(2.6, 0.0, -1.5) + _traffic.add(driver) + _traffic.add(parked) + _traffic.solve() + assert_eq(driver.speed_cap, INF, "clear of both bodies: retain forward speed") + assert_gt(driver.steer.length(), 0.0, "still make comfortable passing room") + + +func test_route_shortcuts_require_a_clear_next_leg() -> void: + for clear: bool in [false, true]: + var driver: Unit = _unit(Vector3(-2, 0, 0), Vector3.FORWARD) + var visibility: CornerVisibility = CornerVisibility.new() + visibility.clear = clear + driver.locomotion.paths = visibility + driver.locomotion.follow_path(PackedVector3Array([Vector3(0, 0, -4), Vector3(12, 0, -4)])) + driver.locomotion.tick(DT) + assert_eq( + driver.locomotion.mover.path_index, + 1 if clear else 0, + "skip an unnecessary funnel point, but retain a corner behind a wall" + ) + + +func test_traffic_is_repeatable() -> void: + var ends: Array[Vector3] = [] + for run: int in 2: + _traffic = Traffic.new() + _units = [] + var north: Unit = _unit(Vector3(0.3, 0, 20), Vector3.FORWARD) + var south: Unit = _unit(Vector3(0, 0, -20), Vector3.BACK) + var west: Unit = _unit(Vector3(-20, 0, 1), Vector3.RIGHT) + _move(north, Vector3(0, 0, -20)) + _move(south, Vector3(0, 0, 20)) + _move(west, Vector3(20, 0, 0)) + _tick(60) + ends.append(north.sim_position() + south.sim_position() * 3.0 + west.sim_position() * 7.0) + assert_eq(ends[0], ends[1], "same inputs, same outcome") diff --git a/game/tests/test_traffic.gd.uid b/game/tests/test_traffic.gd.uid new file mode 100644 index 00000000..dc2d946a --- /dev/null +++ b/game/tests/test_traffic.gd.uid @@ -0,0 +1 @@ +uid://cwocsqelkhbtb diff --git a/game/tests/ui/test_control_groups.gd b/game/tests/ui/test_control_groups.gd new file mode 100644 index 00000000..45b295d2 --- /dev/null +++ b/game/tests/ui/test_control_groups.gd @@ -0,0 +1,244 @@ +extends GutTest +## Control groups from the keyboard (Ctrl/Cmd or Alt/Option + N stores, Shift + N +## adds, N recalls) and the HUD's GroupBar (one badge per group with units). + +var _f: DiscoveryFixture +var _guard: SettingsGuard = SettingsGuard.new() +var _controller: SelectionController +var _bar: GroupBar + + +func before_each() -> void: + _guard.take() + Settings.sticky_shift = false + _f = DiscoveryFixture.new(self) + _controller = SelectionController.new() + _controller.world = _f.world + add_child_autofree(_controller) + _bar = GroupBar.new() + add_child_autofree(_bar) + _bar.setup(_controller) + + +func after_each() -> void: + _f.dispose() + _guard.restore() + + +func _soldier(x: float) -> Unit: + return _f.spawn(_f.combat.soldier, 0, Vector3(x, 0, 0)) + + +## A press of the number-row key `digit`; `typed` is the character the layout gives +## it (Option on macOS turns "1" into "¡"). +func _key(digit: int, modifiers: Array[StringName] = [], typed: Key = KEY_NONE) -> InputEventKey: + var event := InputEventKey.new() + event.physical_keycode = (KEY_0 + digit) as Key + event.keycode = typed if typed != KEY_NONE else event.physical_keycode + event.pressed = true + event.ctrl_pressed = modifiers.has(&"ctrl") + event.meta_pressed = modifiers.has(&"meta") + event.alt_pressed = modifiers.has(&"alt") + event.shift_pressed = modifiers.has(&"shift") + return event + + +func _press(event: InputEventKey) -> void: + _controller._unhandled_input(event) + + +func _shift_key() -> InputEventKey: + var event := InputEventKey.new() + event.keycode = KEY_SHIFT + event.physical_keycode = KEY_SHIFT + event.pressed = true + return event + + +func test_ctrl_number_stores_and_the_number_recalls() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + _press(_key(1, [&"ctrl"])) + _controller.set_selection([]) + _press(_key(1)) + assert_eq(_controller.selection, [a, b] as Array[Unit]) + + +func test_alt_number_stores_even_when_option_types_another_character() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + # macOS: Option+1 types "¡" (U+00A1); the key in that place still counts. + _press(_key(1, [&"alt"], 0xA1 as Key)) + assert_eq(_controller.control_groups().count(1), 2, "Alt+1 stored the selection") + _controller.set_selection([]) + _press(_key(1)) + assert_eq(_controller.selection, [a, b] as Array[Unit], "1 selects the group again") + + +func test_alt_matches_a_group_bound_by_label() -> void: + InputMap.action_erase_events(&"control_group_4") + var by_label := InputEventKey.new() + by_label.keycode = KEY_4 + InputMap.action_add_event(&"control_group_4", by_label) + assert_eq(KeyBindings.group_of(_key(4, [&"alt"], 0xA2 as Key)), 4) + assert_eq(KeyBindings.group_of(_key(4, [], 0xA2 as Key)), 0, "without Alt: no match") + + +func test_meta_number_stores() -> void: + var a: Unit = _soldier(0) + _controller.set_selection([a]) + _press(_key(5, [&"meta"])) + assert_eq(_controller.control_groups().count(5), 1) + + +func test_shift_number_adds_to_the_group() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + var c: Unit = _soldier(6) + _controller.set_selection([a, b]) + _press(_key(2, [&"alt"])) + _controller.set_selection([b, c]) + _press(_key(2, [&"shift"])) + assert_eq(_controller.selection, [b, c] as Array[Unit], "adding keeps the selection") + _controller.set_selection([]) + _press(_key(2)) + assert_eq(_controller.selection, [a, b, c] as Array[Unit], "each unit once, old ones first") + + +func test_sticky_shift_number_adds_to_the_group() -> void: + Settings.sticky_shift = true + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a]) + _press(_key(3, [&"alt"])) + _press(_shift_key()) + _controller.set_selection([b]) + _press(_key(3)) + _press(_shift_key()) + _controller.set_selection([]) + _press(_key(3)) + assert_eq(_controller.selection, [a, b] as Array[Unit]) + + +func test_shift_with_nothing_selected_leaves_the_group() -> void: + var a: Unit = _soldier(0) + _controller.set_selection([a]) + _press(_key(6, [&"alt"])) + _controller.set_selection([]) + _press(_key(6, [&"shift"])) + assert_eq(_controller.control_groups().count(6), 1) + + +func test_the_bar_is_hidden_until_a_group_exists() -> void: + assert_false(_bar.visible) + for group: int in range(1, ControlGroups.COUNT + 1): + assert_false(_bar.badge(group).visible) + + +func test_badges_show_number_and_count_in_group_order() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + _press(_key(3, [&"alt"])) + _controller.set_selection([a]) + _press(_key(1, [&"alt"])) + assert_true(_bar.visible) + assert_true(_bar.badge(1).visible) + assert_true(_bar.badge(3).visible) + assert_false(_bar.badge(2).visible) + assert_eq(_bar.badge(1).text, "1 · 1") + assert_eq(_bar.badge(3).text, "3 · 2") + assert_lt(_bar.badge(1).get_index(), _bar.badge(3).get_index()) + var c: Unit = _soldier(6) + _controller.set_selection([c]) + _press(_key(3, [&"shift"])) + assert_eq(_bar.badge(3).text, "3 · 3", "adding updates the count") + + +func test_a_badge_flashes_when_its_group_is_stored_or_added_to() -> void: + var a: Unit = _soldier(0) + _controller.set_selection([a]) + _press(_key(2, [&"alt"])) + assert_true(_bar.is_flashing(2)) + assert_false(_bar.is_flashing(1)) + _bar._process(GroupBar.FLASH_SECONDS + 0.1) + assert_false(_bar.is_flashing(2), "the light goes out") + _press(_key(2, [&"shift"])) + assert_true(_bar.is_flashing(2), "adding lights it again") + + +func test_a_badge_goes_when_its_units_die() -> void: + var a: Unit = _soldier(0) + _controller.set_selection([a]) + _press(_key(4, [&"alt"])) + assert_true(_bar.badge(4).visible) + a.health.take(1.0e6) + Events.entity_died.emit(a) + await wait_process_frames(2) + assert_false(_bar.badge(4).visible) + assert_false(_bar.visible, "no group left: the bar hides") + + +func test_clicking_a_badge_recalls_the_group() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + _press(_key(7, [&"alt"])) + _controller.set_selection([]) + _bar.badge(7).pressed.emit() + assert_eq(_controller.selection, [a, b] as Array[Unit]) + + +func test_loading_groups_refreshes_the_bar() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + _press(_key(8, [&"alt"])) + var saved: Dictionary = _controller.control_groups().to_dict() + _controller.control_groups().from_dict({}, func(_id: int) -> Node3D: return null) + assert_false(_bar.visible, "an empty save clears the bar") + _controller.control_groups().from_dict(saved, _f.world.entity) + assert_true(_bar.badge(8).visible) + assert_eq(_bar.badge(8).text, "8 · 2") + + +func test_shift_number_starts_an_empty_group() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a, b]) + _press(_key(9, [&"shift"])) + _controller.set_selection([]) + _press(_key(9)) + assert_eq(_controller.selection, [a, b] as Array[Unit], "Shift+9 made group 9") + + +func _right_click() -> InputEventMouseButton: + var click := InputEventMouseButton.new() + click.button_index = MOUSE_BUTTON_RIGHT + click.pressed = true + return click + + +func test_right_clicking_a_badge_replaces_the_group() -> void: + var a: Unit = _soldier(0) + var b: Unit = _soldier(3) + _controller.set_selection([a]) + _press(_key(2, [&"alt"])) + _controller.set_selection([b]) + _bar.badge(2).gui_input.emit(_right_click()) + assert_eq(_bar.badge(2).text, "2 · 1") + assert_true(_bar.is_flashing(2)) + _controller.set_selection([]) + _press(_key(2)) + assert_eq(_controller.selection, [b] as Array[Unit], "b replaced a") + + +func test_right_clicking_a_badge_with_nothing_selected_keeps_the_group() -> void: + var a: Unit = _soldier(0) + _controller.set_selection([a]) + _press(_key(2, [&"alt"])) + _controller.set_selection([]) + _bar.badge(2).gui_input.emit(_right_click()) + assert_eq(_controller.control_groups().count(2), 1) diff --git a/game/tests/ui/test_control_groups.gd.uid b/game/tests/ui/test_control_groups.gd.uid new file mode 100644 index 00000000..f1f5af41 --- /dev/null +++ b/game/tests/ui/test_control_groups.gd.uid @@ -0,0 +1 @@ +uid://bu2tdssrtopvb diff --git a/game/tests/ui/test_controls_page.gd b/game/tests/ui/test_controls_page.gd new file mode 100644 index 00000000..eed5ce1f --- /dev/null +++ b/game/tests/ui/test_controls_page.gd @@ -0,0 +1,38 @@ +extends GutTest +## The help that explains the controls: the F1 panel and How to play name the group +## keys, and the Controls page lists every control with the keys bound now. + + +func test_every_explanation_names_the_new_keys() -> void: + for scheme: StringName in [Settings.SCHEME_CLASSIC, Settings.SCHEME_MODERN]: + var hud: String = Hud.controls_text(scheme) + assert_string_contains(hud, "Alt/Ctrl+1-9 store") + assert_string_contains(hud, "Shift+1-9 add or start") + var how: String = InfoPanel.how_to_play_text(scheme) + assert_string_contains(how, "Alt (Option on a Mac)") + assert_string_contains(how, "Shift + the key adds") + + +func test_the_controls_page_lists_every_bound_key() -> void: + for scheme: StringName in [Settings.SCHEME_CLASSIC, Settings.SCHEME_MODERN]: + var text: String = InfoPanel.controls_text(scheme) + for heading: String in ["MOUSE", "CAMERA", "ORDERS", "CONTROL GROUPS", "GAME"]: + assert_string_contains(text, heading) + for entry: Array in KeyBindings.ACTIONS: + var action: StringName = entry[0] + if String(action).begins_with("control_group_"): + continue + assert_string_contains(text, KeyBindings.label(action), String(action)) + assert_string_contains(text, "Alt + 1-9") + assert_string_contains(text, "Shift + 1-9") + assert_string_contains(InfoPanel.controls_text(Settings.SCHEME_MODERN), "Right click ground") + assert_string_contains(InfoPanel.controls_text(Settings.SCHEME_CLASSIC), "Left click ground") + + +func test_the_controls_page_opens() -> void: + var info := InfoPanel.new() + add_child_autofree(info) + info.open_controls() + assert_true(info.visible) + assert_eq(info.page, InfoPanel.PAGE_CONTROLS) + assert_string_contains(info.body_text(), "CONTROL GROUPS") diff --git a/game/tests/ui/test_controls_page.gd.uid b/game/tests/ui/test_controls_page.gd.uid new file mode 100644 index 00000000..c32d8d8e --- /dev/null +++ b/game/tests/ui/test_controls_page.gd.uid @@ -0,0 +1 @@ +uid://b5b606lda0ksk diff --git a/game/tests/ui/test_group_bar_layout.gd b/game/tests/ui/test_group_bar_layout.gd new file mode 100644 index 00000000..611f4a23 --- /dev/null +++ b/game/tests/ui/test_group_bar_layout.gd @@ -0,0 +1,87 @@ +extends GutTest +## The control groups bar on a real landing at 1152x648, at 100 % and 130 % interface +## size: with all nine groups shown it stays on screen and clear of the command +## panel, the selection panel, the objectives, the resource bar, the minimap corner +## and the subtitle band, with units selected and with nothing selected. + +const VIEW: Vector2i = Vector2i(1152, 648) +const CATALOG: String = "res://data/missions/catalog.tres" + +var _saved_size: Vector2i +var _saved_scale: float = 1.0 + + +func before_each() -> void: + _saved_size = get_tree().root.size + _saved_scale = get_tree().root.content_scale_factor + + +func after_each() -> void: + get_tree().root.size = _saved_size + get_tree().root.content_scale_factor = _saved_scale + + +func test_the_bar_keeps_clear_at_both_interface_sizes() -> void: + var catalog: MissionCatalog = load(CATALOG) + var mission: MissionDef = catalog.missions[0] + get_tree().root.size = VIEW + for scale: float in [1.0, 1.3]: + get_tree().root.content_scale_factor = scale + var map: LandingMap = mission.map_scene.instantiate() as LandingMap + map.mission = mission + add_child(map) + await wait_physics_frames(30) + var controller: SelectionController = map.selection_controller + var units: Array[Unit] = map.world.units_of(map.world.player_faction) + assert_gt(units.size(), 0, "the landing has player units") + controller.set_selection(units) + for group: int in range(1, ControlGroups.COUNT + 1): + controller.store_group(group) + await wait_process_frames(4) + _assert_clear(map.hud, "%d %% selected" % roundi(scale * 100.0)) + controller.set_selection([]) + await wait_process_frames(4) + _assert_clear(map.hud, "%d %% nothing selected" % roundi(scale * 100.0)) + var builder: Unit = null + for unit: Unit in units: + if not unit.def.builds.is_empty(): + builder = unit + break + assert_not_null(builder) + controller.set_selection([builder] as Array[Unit]) + await wait_process_frames(4) + _assert_clear(map.hud, "%d %% builder selected" % roundi(scale * 100.0)) + var commands: Control = map.hud.get("_command_panel") + var corner: Control = map.hud.get("_corner") + assert_false( + commands.get_global_rect().intersects(corner.get_global_rect()), + "the full build menu stays clear of the minimap" + ) + remove_child(map) + map.free() + await wait_process_frames(2) + + +func _assert_clear(hud: Hud, label: String) -> void: + var bar: GroupBar = hud.group_bar() + assert_true(bar.visible, label + ": the bar shows") + var rect: Rect2 = bar.get_global_rect() + var view: Rect2 = hud.get_viewport().get_visible_rect() + assert_true(view.encloses(rect), "%s: on screen %s in %s" % [label, rect, view]) + var subtitle_bottom: float = view.size.y - SubtitleLine.BOTTOM_GAP + assert_gt(rect.position.y, subtitle_bottom, label + ": under the subtitle band") + for field: String in ["_command_panel", "_selection_panel", "_objectives", "_corner"]: + var value: Variant = hud.get(field) + if not value is Control: + continue + var other: Control = value + if not other.is_visible_in_tree(): + continue + var other_rect: Rect2 = other.get_global_rect() + assert_false( + rect.intersects(other_rect), "%s: clear of %s %s %s" % [label, field, rect, other_rect] + ) + for child: Node in hud.get_children(): + var resources: ResourceBar = child as ResourceBar + if resources != null: + assert_false(rect.intersects(resources.get_global_rect()), label + ": resource bar") diff --git a/game/tests/ui/test_group_bar_layout.gd.uid b/game/tests/ui/test_group_bar_layout.gd.uid new file mode 100644 index 00000000..7ccbf55d --- /dev/null +++ b/game/tests/ui/test_group_bar_layout.gd.uid @@ -0,0 +1 @@ +uid://b1t7tfve1smur diff --git a/game/tests/ui/test_phase9_settings.gd b/game/tests/ui/test_phase9_settings.gd index d04cb702..33b6404b 100644 --- a/game/tests/ui/test_phase9_settings.gd +++ b/game/tests/ui/test_phase9_settings.gd @@ -85,12 +85,13 @@ func test_damaged_values_fall_back() -> void: func test_two_actions_on_one_key_in_a_file_are_undone() -> void: var config: ConfigFile = ConfigFile.new() + # "codex" is the saved action id of the Survey Log key. config.set_value("keys_classic", "codex", "k%d" % KEY_F5) config.save(OLD_FILE) Settings.load_from(OLD_FILE) - var codex: String = Settings.bindings.binding(Settings.SCHEME_CLASSIC, &"codex") + var log_key: String = Settings.bindings.binding(Settings.SCHEME_CLASSIC, &"codex") var quicksave: String = Settings.bindings.binding(Settings.SCHEME_CLASSIC, &"quicksave") - assert_false(KeyBindings.same_key(codex, quicksave)) + assert_false(KeyBindings.same_key(log_key, quicksave)) func test_rebinding_reports_conflicts_swaps_and_resets() -> void: diff --git a/game/tests/web/web_probe.gd b/game/tests/web/web_probe.gd index 7f596180..c8590d44 100644 --- a/game/tests/web/web_probe.gd +++ b/game/tests/web/web_probe.gd @@ -82,6 +82,22 @@ func _process(delta: float) -> void: var map: LandingMap = _main.map as LandingMap if map != null: var camera: Camera3D = map.camera.camera + var commands: CommandPanel = map.hud.get("_command_panel") + var scroller: ScrollContainer = commands.get("_scroll") + var scroll_bar: HScrollBar = scroller.get_h_scroll_bar() + var scroll_rect: Rect2 = scroll_bar.get_global_rect() + data["command_scroll"] = { + "rect": + [ + scroll_rect.position.x * _css_scale(), + scroll_rect.position.y * _css_scale(), + scroll_rect.size.x * _css_scale(), + scroll_rect.size.y * _css_scale() + ], + "value": scroll_bar.value, + "maximum": scroll_bar.max_value, + "page": scroll_bar.page, + } data["placing"] = map.selection_controller.placement.is_active() data["placement_reason"] = map.selection_controller.placement.reason data["tick"] = map.context.sim_clock.get_tick() diff --git a/game/ui/command_panel.gd b/game/ui/command_panel.gd index 9b8e0b55..cdd750bb 100644 --- a/game/ui/command_panel.gd +++ b/game/ui/command_panel.gd @@ -64,6 +64,8 @@ var faction: int = 0 var _title: Label var _buttons: HBoxContainer +var _scroll: ScrollContainer +var _available_width: float = 720.0 var _status: Label var _progress: ProgressBar var _hint: Label @@ -75,28 +77,31 @@ func setup(p_controller: SelectionController, p_world: SimWorld, p_faction: int) controller = p_controller world = p_world faction = p_faction - var style := StyleBoxFlat.new() - style.bg_color = HudStyle.PANEL_COLOR - style.border_color = HudStyle.ACCENT_COLOR - style.border_width_top = 2 - style.set_corner_radius_all(3) - style.set_content_margin_all(10) - add_theme_stylebox_override(&"panel", style) + add_theme_stylebox_override(&"panel", HudStyle.panel_style()) mouse_filter = Control.MOUSE_FILTER_STOP var column := VBoxContainer.new() - column.add_theme_constant_override(&"separation", 6) + column.add_theme_constant_override(&"separation", 4) add_child(column) _title = HudStyle.make_label(11, HudStyle.MUTED_COLOR) column.add_child(_title) + _scroll = ScrollContainer.new() + _scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_AUTO + _scroll.vertical_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + column.add_child(_scroll) _buttons = HBoxContainer.new() _buttons.add_theme_constant_override(&"separation", 8) - column.add_child(_buttons) + _scroll.add_child(_buttons) _status = HudStyle.make_label(12, HudStyle.TEXT_COLOR) + _status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _status.max_lines_visible = 2 column.add_child(_status) _progress = HudStyle.make_progress_bar() _progress.custom_minimum_size = Vector2(260, 6) column.add_child(_progress) _hint = HudStyle.make_label(12, HudStyle.MUTED_COLOR) + _hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _hint.max_lines_visible = 2 + _hint.mouse_filter = Control.MOUSE_FILTER_PASS column.add_child(_hint) visible = false @@ -109,7 +114,21 @@ func _process(_delta: float) -> void: _mode = mode _rebuild() if visible: + fit_width(_available_width) _refresh() + _hint.tooltip_text = _hint.text + + +## Keeps every command available between the selection panel and minimap. +func fit_width(available: float) -> void: + _available_width = available + if _buttons == null: + return + var inner: float = maxf(120.0, available - get_theme_stylebox(&"panel").get_minimum_size().x) + _scroll.custom_minimum_size.x = inner + _progress.custom_minimum_size.x = minf(260.0, inner) + _status.custom_minimum_size.x = inner + _hint.custom_minimum_size.x = inner ## A key that changes whenever the panel needs different buttons. diff --git a/game/ui/group_bar.gd b/game/ui/group_bar.gd new file mode 100644 index 00000000..a5ee24da --- /dev/null +++ b/game/ui/group_bar.gd @@ -0,0 +1,130 @@ +class_name GroupBar +extends HBoxContainer +## The player's control groups on the HUD: one small badge per group that holds +## living units, in group order, reading " · " ("1 · 5"). Clicking a +## badge recalls the group like its key does (twice quickly centres the camera); +## right-clicking it puts the selection in that group instead (a way to replace a +## group that no browser takes, unlike Ctrl or, on Linux, Alt + a number). A +## badge lights up briefly when its group is stored or added to, disappears when its +## last unit dies, and the bar hides while no group exists. + +## How long a badge stays lit after its group was stored or added to, in seconds. +const FLASH_SECONDS: float = 0.6 + +var _controller: SelectionController +var _groups: ControlGroups +## Group number -> its badge (all nine exist; empty groups are hidden). +var _badges: Dictionary[int, Button] = {} +## Group number -> seconds its badge stays lit. +var _flash_left: Dictionary[int, float] = {} + + +func _init() -> void: + name = &"GroupBar" + add_theme_constant_override(&"separation", 4) + mouse_filter = Control.MOUSE_FILTER_IGNORE + for group: int in range(1, ControlGroups.COUNT + 1): + var badge: Button = HudStyle.make_small_button("") + badge.name = StringName("Group%d" % group) + badge.pressed.connect(_on_badge_pressed.bind(group)) + badge.gui_input.connect(_on_badge_input.bind(group)) + badge.visible = false + add_child(badge) + _badges[group] = badge + visible = false + + +func _ready() -> void: + Events.entity_died.connect(_on_entity_died) + Settings.changed.connect(refresh) + + +## Shows the groups of `controller` and recalls them through it. +func setup(controller: SelectionController) -> void: + _controller = controller + _groups = controller.control_groups() if controller != null else null + if _groups != null: + _groups.changed.connect(refresh) + _groups.stored.connect(_on_group_stored) + refresh() + + +## Reads every group's living count again and shows the badges that have units. +func refresh() -> void: + var any: bool = false + for group: int in _badges: + var badge: Button = _badges[group] + var units: int = _groups.count(group) if _groups != null else 0 + badge.visible = units > 0 + any = any or units > 0 + badge.text = "%d · %d" % [group, units] + var key: String = KeyBindings.label(StringName("control_group_%d" % group)) + badge.tooltip_text = ( + ( + "Group %d: %d units. Click (or %s) to select it, twice to centre on it.\n" + + "Right-click, Alt+%s or Ctrl+%s: the selection becomes this group.\n" + + "Shift+%s adds the selection to it." + ) + % [group, units, key, key, key, key] + ) + visible = any + + +## The badge of group `group` (1..9). +func badge(group: int) -> Button: + return _badges.get(group, null) + + +## True while the badge of `group` is lit after a store or add. +func is_flashing(group: int) -> bool: + return _flash_left.has(group) + + +func _process(delta: float) -> void: + if _flash_left.is_empty(): + return + for group: int in _flash_left.keys(): + var left: float = _flash_left[group] - delta + if left > 0.0: + _flash_left[group] = left + else: + _flash_left.erase(group) + _light(group, false) + + +func _on_group_stored(group: int) -> void: + _flash_left[group] = FLASH_SECONDS + _light(group, true) + + +func _light(group: int, lit: bool) -> void: + var lamp: Button = _badges.get(group, null) + if lamp == null: + return + lamp.add_theme_stylebox_override( + &"normal", HudStyle.button_style(&"pressed" if lit else &"normal") + ) + lamp.add_theme_color_override( + &"font_color", HudStyle.ACCENT_COLOR if lit else HudStyle.TEXT_COLOR + ) + + +func _on_badge_pressed(group: int) -> void: + if _controller != null: + _controller.recall_group(group) + + +## Right click on a badge: the selection replaces the group (nothing selected: no +## change, so a stray click cannot empty a group). +func _on_badge_input(event: InputEvent, group: int) -> void: + var click: InputEventMouseButton = event as InputEventMouseButton + if click == null or not click.pressed or click.button_index != MOUSE_BUTTON_RIGHT: + return + accept_event() + if _controller != null and not _controller.selection.is_empty(): + _controller.store_group(group) + + +func _on_entity_died(entity: Node3D) -> void: + if entity is Unit: + refresh.call_deferred() diff --git a/game/ui/group_bar.gd.uid b/game/ui/group_bar.gd.uid new file mode 100644 index 00000000..d6b21377 --- /dev/null +++ b/game/ui/group_bar.gd.uid @@ -0,0 +1 @@ +uid://ciykyo6lk1y4n diff --git a/game/ui/hud.gd b/game/ui/hud.gd index ffb82c0e..0a8b2c2b 100644 --- a/game/ui/hud.gd +++ b/game/ui/hud.gd @@ -2,7 +2,8 @@ class_name Hud extends CanvasLayer ## In-mission HUD: the resource bar (top), the command panel (bottom centre: build ## menu, production, field options, hints), a selection panel with one chip per -## type, the minimap (bottom right) with the controls panel (F1) above it, the codex +## type (bottom left), the control groups bar above it and the command panel, the +## minimap (bottom right) with the controls panel (F1) above it, the Survey Log ## (button or C) and the menu button (top right; the pause menu holds the settings, ## including the mouse scheme), the planet indicator under them (Kessel: the dust ## storm and its countdown), the mission's objectives (top left, with the enemy alert @@ -13,6 +14,8 @@ extends CanvasLayer ## The MENU button was pressed (Main opens the pause menu). signal menu_requested +## The Survey Log opened or closed, including through its Close button. +signal survey_log_toggled(is_open: bool) ## Controls panel text per mouse scheme (Settings.control_scheme); {key_} ## is the key bound to that action now (KeyBindings), filled in by `controls_text()`. @@ -24,10 +27,11 @@ const HINT_CLASSIC: String = ( + " building selected: ground sets the rally point\n" + "RIGHT deselect · while placing or aiming: cancel (or Esc)\n" + "SHIFT add to selection · queue orders · place several · {key_order_stop} stop\n" - + "GROUPS Ctrl+{groups} store · {groups} recall, twice to centre\n" + + "GROUPS Alt/Ctrl+{groups} store · Shift+{groups} add or start\n" + + " {groups} recall, twice to centre · badge: click recall, right click store\n" + "CAMERA {pan} or the edge or MMB pan · wheel zoom · {turn} turn\n" + "MAP left: look there (drag)\n" - + "CODEX {key_codex} or the button top right · COMBAT armed units fire by themselves\n" + + "LOG {key_codex} or the button top right · COMBAT armed units fire by themselves\n" + "SAVE {key_quicksave} quicksave · {key_quickload} quickload\n" + "MENU Esc or {key_pause_menu}: pause, settings, keys, restart, quit" ) @@ -40,10 +44,11 @@ const HINT_MODERN: String = ( + " building selected: rally point · unit button: cancel one\n" + " while placing or aiming: cancel (or Esc)\n" + "SHIFT add to selection · queue orders · place several · {key_order_stop} stop\n" - + "GROUPS Ctrl+{groups} store · {groups} recall, twice to centre\n" + + "GROUPS Alt/Ctrl+{groups} store · Shift+{groups} add or start\n" + + " {groups} recall, twice to centre · badge: click recall, right click store\n" + "CAMERA {pan} or the edge or MMB pan · wheel zoom · {turn} turn\n" + "MAP left: look there (drag) · right: move selected units there\n" - + "CODEX {key_codex} or the button top right · COMBAT armed units fire by themselves\n" + + "LOG {key_codex} or the button top right · COMBAT armed units fire by themselves\n" + "SAVE {key_quicksave} quicksave · {key_quickload} quickload\n" + "MENU Esc or {key_pause_menu}: pause, settings, keys, restart, quit" ) @@ -61,6 +66,7 @@ const MARGIN := HudStyle.MARGIN @export var map_area: Rect2 = Rect2(-120.0, -120.0, 240.0, 240.0) var _selection_panel: PanelContainer +var _group_bar: GroupBar var _selection_title: Label var _chips: HBoxContainer var _hint_panel: PanelContainer @@ -74,8 +80,8 @@ var _corner: VBoxContainer var _minimap: Minimap var _objectives: ObjectivesPanel var _hint: Label -var _codex: CodexPanel -var _codex_button: Button +var _survey_log: SurveyLogPanel +var _log_button: Button var _menu_button: Button var _planet: PlanetIndicator var _shift_note: Label @@ -88,11 +94,14 @@ func _ready() -> void: _build_hint() _build_debug() _build_top_right() - _codex = CodexPanel.new() - add_child(_codex) - _codex.set_anchors_and_offsets_preset(Control.PRESET_CENTER, Control.PRESET_MODE_MINSIZE) - _codex.grow_horizontal = Control.GROW_DIRECTION_BOTH - _codex.grow_vertical = Control.GROW_DIRECTION_BOTH + _survey_log = SurveyLogPanel.new() + add_child(_survey_log) + _survey_log.visibility_changed.connect( + func() -> void: survey_log_toggled.emit(_survey_log.visible) + ) + _survey_log.set_anchors_and_offsets_preset(Control.PRESET_CENTER, Control.PRESET_MODE_MINSIZE) + _survey_log.grow_horizontal = Control.GROW_DIRECTION_BOTH + _survey_log.grow_vertical = Control.GROW_DIRECTION_BOTH Settings.changed.connect(_on_settings_changed) _on_settings_changed() _objectives = ObjectivesPanel.new() @@ -118,11 +127,12 @@ func _unhandled_input(event: InputEvent) -> void: _hint_panel.visible = not _hint_panel.visible _hint_toggle.visible = not _hint_panel.visible get_viewport().set_input_as_handled() + # "codex" is the saved action id of the Survey Log key. elif key.is_action_pressed(&"codex", false, true): - toggle_codex() + toggle_survey_log() get_viewport().set_input_as_handled() - elif key.keycode == KEY_ESCAPE and _codex.visible: - _codex.close_panel() + elif key.keycode == KEY_ESCAPE and _survey_log.visible: + _survey_log.close_panel() get_viewport().set_input_as_handled() @@ -132,20 +142,25 @@ func set_map_colors(low: Color, high: Color) -> void: _minimap.set_ground_colors(low, high) +## The control groups bar (left, above the selection and command panels). +func group_bar() -> GroupBar: + return _group_bar + + ## Shows the alert meter of the enemy `faction` under the objectives. func show_alert_meter(faction: int) -> void: _objectives.show_alert_meter(faction) -## Opens the codex with the player's entries, or closes it. -func toggle_codex() -> void: - if _codex.visible: - _codex.close_panel() +## Opens the Survey Log with the player's entries, or closes it. +func toggle_survey_log() -> void: + if _survey_log.visible: + _survey_log.close_panel() return var entries: Array[DiscoveryDef] = [] if world != null and world.discovery != null: - entries = world.discovery.codex(player_faction) - _codex.open_panel(entries) + entries = world.discovery.survey_log(player_faction) + _survey_log.open_panel(entries) ## Switches between the classic and modern mouse schemes (saved in the settings). @@ -194,6 +209,8 @@ static func controls_text(scheme: StringName) -> String: func _process(_delta: float) -> void: + _place_commands() + _place_group_bar() if _shift_note != null and selection_controller != null: _shift_note.visible = Settings.sticky_shift and selection_controller.shift_held(_no_shift) if not _debug_panel.visible: @@ -216,6 +233,39 @@ func _process(_delta: float) -> void: _debug.text = "\n".join(lines) +## Reserve the gap between the corner panels; narrow windows scroll commands. +func _place_commands() -> void: + var view: Vector2 = get_viewport().get_visible_rect().size + if _selection_panel != null and _selection_panel.visible: + _selection_panel.reset_size() + _selection_panel.position = Vector2(MARGIN, view.y - MARGIN - _selection_panel.size.y) + # Configure the hidden panel too, before a selection makes new commands + # visible. Their first layout must use the final reserved space. + if _command_panel == null: + return + var left: float = MARGIN + if _selection_panel.visible: + left = _selection_panel.get_global_rect().end.x + MARGIN + var right: float = _corner.get_global_rect().position.x - MARGIN + _command_panel.fit_width(right - left) + _command_panel.reset_size() + _command_panel.position = Vector2( + (left + right - _command_panel.size.x) * 0.5, view.y - MARGIN - _command_panel.size.y + ) + + +## Keep group badges above the lower panels, without covering their controls. +func _place_group_bar() -> void: + if _group_bar == null or not _group_bar.visible: + return + var top: float = get_viewport().get_visible_rect().size.y - MARGIN + for panel: Control in [_selection_panel, _command_panel]: + if panel != null and panel.visible: + top = minf(top, panel.get_global_rect().position.y) + _group_bar.reset_size() + _group_bar.position = Vector2(MARGIN, top - 6.0 - _group_bar.size.y) + + ## Summary text for a selection, e.g. "3 selected: 2 Ranger, 1 Bulwark". static func summarize(entities: Array[Node3D]) -> String: if entities.is_empty(): @@ -297,6 +347,9 @@ func _build_selection_panel() -> void: _chips = HBoxContainer.new() _chips.add_theme_constant_override(&"separation", 14) column.add_child(_chips) + _group_bar = GroupBar.new() + add_child(_group_bar) + _group_bar.setup(selection_controller) ## Bottom-right column: the controls panel (F1) or its toggle, above the minimap. @@ -321,7 +374,7 @@ func _build_hint() -> void: _corner.add_child(_shift_note) -## Top right: the codex and menu buttons, the planet indicator below them. +## Top right: the Survey Log and menu buttons, the planet indicator below them. func _build_top_right() -> void: var column := VBoxContainer.new() column.add_theme_constant_override(&"separation", 6) @@ -334,10 +387,10 @@ func _build_top_right() -> void: row.add_theme_constant_override(&"separation", 6) row.alignment = BoxContainer.ALIGNMENT_END column.add_child(row) - _codex_button = HudStyle.make_small_button("CODEX (C)") - _codex_button.tooltip_text = "What the expedition has found on this landing." - _codex_button.pressed.connect(toggle_codex) - row.add_child(_codex_button) + _log_button = HudStyle.make_small_button("LOG (C)") + _log_button.tooltip_text = "What the expedition has found on this landing." + _log_button.pressed.connect(toggle_survey_log) + row.add_child(_log_button) _menu_button = HudStyle.make_small_button("MENU (Esc)") _menu_button.tooltip_text = "Pause: resume, settings (mouse, audio, display), restart, quit." _menu_button.pressed.connect(request_menu) @@ -351,7 +404,7 @@ func _build_top_right() -> void: func _on_settings_changed() -> void: _hint.text = controls_text(Settings.control_scheme) _hint_toggle.text = "%s CONTROLS" % KeyBindings.label(&"controls_help") - _codex_button.text = "CODEX (%s)" % KeyBindings.label(&"codex") + _log_button.text = "LOG (%s)" % KeyBindings.label(&"codex") func _build_debug() -> void: diff --git a/game/ui/hud_style.gd b/game/ui/hud_style.gd index 40321ca7..7b25c1d9 100644 --- a/game/ui/hud_style.gd +++ b/game/ui/hud_style.gd @@ -1,31 +1,52 @@ class_name HudStyle extends RefCounted -## The HUD's shared look: one small set of colours, panels, labels and buttons, so -## every panel reads as the same survey-instrument family. - -const PANEL_COLOR := Color(0.055, 0.07, 0.09, 0.84) -const ACCENT_COLOR := Color(0.93, 0.36, 0.05) -const TEXT_COLOR := Color(0.90, 0.92, 0.94) -const MUTED_COLOR := Color(0.62, 0.68, 0.74) +## The game's shared look: one small set of colours, plates, labels and buttons, so +## every panel reads as the same Concord field kit: steel-blue plates with cut +## corners, thin outlines and cyan instrument lights (PlateStyle draws the plates). +## Orange and red are kept for warnings and the enemy. + +const PANEL_COLOR := Color(0.043, 0.071, 0.098, 0.88) +## Outline of panels and resting buttons. +const LINE_COLOR := Color(0.25, 0.35, 0.43) +## The instrument light: headings, lit lamps, the chosen option. +const ACCENT_COLOR := Color(0.40, 0.87, 0.95) +const TEXT_COLOR := Color(0.90, 0.94, 0.96) +const MUTED_COLOR := Color(0.58, 0.67, 0.74) const WARNING_COLOR := Color(1.0, 0.42, 0.25) const ALLOY_COLOR := Color(0.80, 0.84, 0.90) const FLUX_COLOR := Color(0.45, 0.85, 1.0) const POWER_COLOR := Color(1.0, 0.82, 0.35) const INTEL_COLOR := Color(0.62, 1.0, 0.78) -const BUTTON_COLOR := Color(0.10, 0.125, 0.15, 0.95) -const BUTTON_HOVER_COLOR := Color(0.15, 0.19, 0.23, 0.98) +const BUTTON_COLOR := Color(0.075, 0.115, 0.15, 0.96) +const BUTTON_HOVER_COLOR := Color(0.11, 0.18, 0.23, 0.98) +const BUTTON_PRESSED_COLOR := Color(0.09, 0.25, 0.30, 0.98) ## Campaign screens: route node and tech states. const LOCKED_COLOR := Color(0.36, 0.40, 0.45) -const OPEN_COLOR := Color(0.93, 0.36, 0.05) +const OPEN_COLOR := ACCENT_COLOR const WON_COLOR := Color(0.55, 0.95, 0.65) const CURRENT_COLOR := Color(1.0, 0.92, 0.55) const AVAILABLE_COLOR := Color(0.70, 0.76, 0.82) const LINK_COLOR := Color(0.62, 0.68, 0.74, 0.45) const MARGIN := 14 const ICON_SIZE := 52 +## Corner cut of panels and of buttons, px. +const PANEL_CUT := 10.0 +const BUTTON_CUT := 6.0 +## Labels this large or larger are set in the heading weight. +const HEADING_SIZE := 18 +## The typeface (Chakra Petch, SIL Open Font License) by weight. Loaded on first use, +## not preloaded: a fresh checkout parses this script before the fonts are imported. +const FONT_BODY: String = "res://assets/fonts/ChakraPetch-Regular.ttf" +const FONT_BUTTON: String = "res://assets/fonts/ChakraPetch-Medium.ttf" +const FONT_HEADING: String = "res://assets/fonts/ChakraPetch-SemiBold.ttf" + + +## The font at `path` (FONT_BODY, FONT_BUTTON, FONT_HEADING). +static func font(path: String) -> Font: + return load(path) as Font -## A dark panel with the orange accent along its top edge. +## A dark plate with the instrument light along its top edge. static func make_panel() -> PanelContainer: var panel := PanelContainer.new() panel.add_theme_stylebox_override(&"panel", panel_style()) @@ -33,24 +54,19 @@ static func make_panel() -> PanelContainer: return panel -## The panels' look: dark, the orange accent along the top edge. -static func panel_style() -> StyleBoxFlat: - var style := StyleBoxFlat.new() - style.bg_color = PANEL_COLOR - style.border_color = ACCENT_COLOR - style.border_width_top = 2 - style.set_corner_radius_all(3) - style.set_content_margin_all(10) +## The panels' look; `margin` is the space kept free inside the edge, px. +static func panel_style(margin: int = 10) -> PlateStyle: + var style := PlateStyle.new(PANEL_COLOR, LINE_COLOR, PANEL_CUT) + style.marker = ACCENT_COLOR + style.set_content_margin_all(margin) return style ## The same panel without see-through: for screens that open over other panels. -static func solid_panel_style() -> StyleBoxFlat: - var style: StyleBoxFlat = panel_style() - style.bg_color = Color(PANEL_COLOR, 1.0) - style.set_content_margin_all(16) - style.shadow_color = Color(0, 0, 0, 0.5) - style.shadow_size = 18 +static func solid_panel_style() -> PlateStyle: + var style: PlateStyle = panel_style(18) + style.fill = Color(PANEL_COLOR, 1.0) + style.shadow = 18.0 return style @@ -86,6 +102,8 @@ static func make_label(font_size: int, color: Color, text: String = "") -> Label label.text = text label.add_theme_font_size_override(&"font_size", font_size) label.add_theme_color_override(&"font_color", color) + if font_size >= HEADING_SIZE: + label.add_theme_font_override(&"font", font(FONT_HEADING)) label.mouse_filter = Control.MOUSE_FILTER_IGNORE return label @@ -105,13 +123,12 @@ static func make_button(icon: Texture2D, caption: String) -> Button: button.add_theme_color_override(&"font_hover_color", Color.WHITE) button.add_theme_color_override(&"font_disabled_color", MUTED_COLOR) button.add_theme_constant_override(&"icon_max_width", ICON_SIZE) - for state: StringName in [&"normal", &"pressed", &"disabled", &"focus"]: - button.add_theme_stylebox_override(state, _button_style(BUTTON_COLOR)) - button.add_theme_stylebox_override(&"hover", _button_style(BUTTON_HOVER_COLOR)) + style_button(button) + button.add_theme_stylebox_override(&"disabled", button_style(&"normal")) return button -## A small text button for the HUD's corners (codex, control scheme). +## A small text button for the HUD's corners (menu, control scheme). static func make_small_button(caption: String) -> Button: var button := Button.new() button.text = caption @@ -119,9 +136,7 @@ static func make_small_button(caption: String) -> Button: button.add_theme_font_size_override(&"font_size", 11) button.add_theme_color_override(&"font_color", TEXT_COLOR) button.add_theme_color_override(&"font_hover_color", Color.WHITE) - for state: StringName in [&"normal", &"pressed", &"focus"]: - button.add_theme_stylebox_override(state, _button_style(BUTTON_COLOR)) - button.add_theme_stylebox_override(&"hover", _button_style(BUTTON_HOVER_COLOR)) + style_button(button) return button @@ -206,18 +221,34 @@ static func make_menu_button(caption: String, width: float = 240.0) -> Button: button.custom_minimum_size = Vector2(width, 40) button.add_theme_font_size_override(&"font_size", 14) button.add_theme_color_override(&"font_disabled_color", Color(MUTED_COLOR, 0.5)) - button.add_theme_stylebox_override(&"disabled", _button_style(Color(BUTTON_COLOR, 0.5))) return button -static func _button_style(color: Color) -> StyleBoxFlat: - var style := StyleBoxFlat.new() - style.bg_color = color - # The border is the fill colour lightened, at the fill's own alpha. A see-through - # white border stacks on the fill where the two meet in the rounded corners and - # shows there as bright specks. - style.border_color = color.lightened(0.08) - style.set_border_width_all(1) - style.set_corner_radius_all(3) +## Gives `button` the plate look in every state (resting, hover, pressed, disabled). +static func style_button(button: Button) -> void: + button.add_theme_font_override(&"font", font(FONT_BUTTON)) + for state: StringName in [&"normal", &"hover", &"pressed", &"disabled"]: + button.add_theme_stylebox_override(state, button_style(state)) + button.add_theme_stylebox_override(&"focus", StyleBoxEmpty.new()) + + +## A button's plate in `state`: &"normal", &"hover", &"pressed" or &"disabled". The +## lamp on its left edge lights on hover and while pressed. +static func button_style(state: StringName) -> PlateStyle: + var style := PlateStyle.new(BUTTON_COLOR, LINE_COLOR, BUTTON_CUT) + match state: + &"hover": + style.fill = BUTTON_HOVER_COLOR + style.line = Color(ACCENT_COLOR, 0.75) + style.lamp = ACCENT_COLOR + &"pressed": + style.fill = BUTTON_PRESSED_COLOR + style.line = ACCENT_COLOR + style.lamp = ACCENT_COLOR + &"disabled": + style.fill = Color(BUTTON_COLOR, 0.5) + style.line = Color(LINE_COLOR, 0.5) style.set_content_margin_all(6) + style.content_margin_left = 10 + style.content_margin_right = 10 return style diff --git a/game/ui/hud_theme.gd b/game/ui/hud_theme.gd new file mode 100644 index 00000000..c616c507 --- /dev/null +++ b/game/ui/hud_theme.gd @@ -0,0 +1,130 @@ +class_name HudTheme +extends RefCounted +## The theme every control starts from: the game's typeface and the field-kit look for +## the stock controls that HudStyle's helpers do not build (lists, sliders, switches, +## drop-downs, scroll bars, tooltips). The UiTheme autoload applies it everywhere. + +const TRACK_COLOR := Color(1.0, 1.0, 1.0, 0.10) +const SWITCH_SIZE := Vector2i(38, 18) +const GRABBER_SIZE: int = 14 + + +static func build() -> Theme: + var theme := Theme.new() + theme.default_font = HudStyle.font(HudStyle.FONT_BODY) + theme.set_color(&"font_color", &"Label", HudStyle.TEXT_COLOR) + _buttons(theme, &"Button") + _buttons(theme, &"OptionButton") + _buttons(theme, &"CheckButton") + theme.set_stylebox(&"normal", &"CheckButton", StyleBoxEmpty.new()) + theme.set_stylebox(&"hover", &"CheckButton", StyleBoxEmpty.new()) + theme.set_stylebox(&"pressed", &"CheckButton", StyleBoxEmpty.new()) + theme.set_stylebox(&"hover_pressed", &"CheckButton", StyleBoxEmpty.new()) + theme.set_icon(&"checked", &"CheckButton", switch_icon(true)) + theme.set_icon(&"unchecked", &"CheckButton", switch_icon(false)) + _slider(theme) + _scroll_bar(theme, &"VScrollBar") + _scroll_bar(theme, &"HScrollBar") + _list(theme) + _popup(theme) + var tip: PlateStyle = HudStyle.panel_style(8) + tip.fill = Color(HudStyle.PANEL_COLOR, 0.97) + tip.marker = Color.TRANSPARENT + theme.set_stylebox(&"panel", &"TooltipPanel", tip) + theme.set_color(&"font_color", &"TooltipLabel", HudStyle.TEXT_COLOR) + theme.set_font_size(&"font_size", &"TooltipLabel", 12) + return theme + + +## The on/off switch drawn for a CheckButton: a cut track with a square knob. +static func switch_icon(on: bool) -> ImageTexture: + var image := Image.create(SWITCH_SIZE.x, SWITCH_SIZE.y, false, Image.FORMAT_RGBA8) + var track: Color = Color(HudStyle.ACCENT_COLOR, 0.35) if on else TRACK_COLOR + image.fill_rect(Rect2i(0, 3, SWITCH_SIZE.x, SWITCH_SIZE.y - 6), track) + var knob: Color = HudStyle.ACCENT_COLOR if on else HudStyle.MUTED_COLOR + var left: int = SWITCH_SIZE.x - SWITCH_SIZE.y if on else 0 + image.fill_rect(Rect2i(left + 2, 0, SWITCH_SIZE.y - 4, SWITCH_SIZE.y), knob) + return ImageTexture.create_from_image(image) + + +## The slider's handle: a small diamond. +static func grabber_icon(color: Color) -> ImageTexture: + var image := Image.create(GRABBER_SIZE, GRABBER_SIZE, false, Image.FORMAT_RGBA8) + var half: float = (GRABBER_SIZE - 1) / 2.0 + for y: int in GRABBER_SIZE: + for x: int in GRABBER_SIZE: + if absf(x - half) + absf(y - half) <= half: + image.set_pixel(x, y, color) + return ImageTexture.create_from_image(image) + + +static func _buttons(theme: Theme, type: StringName) -> void: + theme.set_font(&"font", type, HudStyle.font(HudStyle.FONT_BUTTON)) + theme.set_color(&"font_color", type, HudStyle.TEXT_COLOR) + theme.set_color(&"font_hover_color", type, Color.WHITE) + theme.set_color(&"font_pressed_color", type, HudStyle.ACCENT_COLOR) + theme.set_color(&"font_hover_pressed_color", type, HudStyle.ACCENT_COLOR) + theme.set_color(&"font_focus_color", type, HudStyle.TEXT_COLOR) + theme.set_color(&"font_disabled_color", type, Color(HudStyle.MUTED_COLOR, 0.5)) + for state: StringName in [&"normal", &"hover", &"pressed", &"disabled"]: + theme.set_stylebox(state, type, HudStyle.button_style(state)) + theme.set_stylebox(&"focus", type, StyleBoxEmpty.new()) + + +static func _slider(theme: Theme) -> void: + var track := StyleBoxFlat.new() + track.bg_color = TRACK_COLOR + track.content_margin_top = 2 + track.content_margin_bottom = 2 + var filled: StyleBoxFlat = track.duplicate() + filled.bg_color = Color(HudStyle.ACCENT_COLOR, 0.7) + theme.set_stylebox(&"slider", &"HSlider", track) + theme.set_stylebox(&"grabber_area", &"HSlider", filled) + theme.set_stylebox(&"grabber_area_highlight", &"HSlider", filled) + theme.set_icon(&"grabber", &"HSlider", grabber_icon(HudStyle.TEXT_COLOR)) + theme.set_icon(&"grabber_highlight", &"HSlider", grabber_icon(HudStyle.ACCENT_COLOR)) + theme.set_icon(&"grabber_disabled", &"HSlider", grabber_icon(HudStyle.LOCKED_COLOR)) + + +static func _scroll_bar(theme: Theme, type: StringName) -> void: + var track := StyleBoxFlat.new() + track.bg_color = Color(1, 1, 1, 0.04) + track.set_content_margin_all(3) + theme.set_stylebox(&"scroll", type, track) + for state: StringName in [&"grabber", &"grabber_highlight", &"grabber_pressed"]: + var grabber := StyleBoxFlat.new() + grabber.bg_color = HudStyle.LINE_COLOR if state == &"grabber" else HudStyle.ACCENT_COLOR + theme.set_stylebox(state, type, grabber) + + +static func _list(theme: Theme) -> void: + var back := StyleBoxFlat.new() + back.bg_color = Color(0, 0, 0, 0.22) + back.set_content_margin_all(4) + theme.set_stylebox(&"panel", &"ItemList", back) + theme.set_stylebox(&"focus", &"ItemList", StyleBoxEmpty.new()) + var chosen := StyleBoxFlat.new() + chosen.bg_color = Color(HudStyle.ACCENT_COLOR, 0.16) + chosen.border_color = HudStyle.ACCENT_COLOR + chosen.border_width_left = 2 + theme.set_stylebox(&"selected", &"ItemList", chosen) + theme.set_stylebox(&"selected_focus", &"ItemList", chosen) + var hovered := StyleBoxFlat.new() + hovered.bg_color = Color(1, 1, 1, 0.05) + theme.set_stylebox(&"hovered", &"ItemList", hovered) + theme.set_color(&"font_color", &"ItemList", HudStyle.MUTED_COLOR) + theme.set_color(&"font_hovered_color", &"ItemList", HudStyle.TEXT_COLOR) + theme.set_color(&"font_selected_color", &"ItemList", Color.WHITE) + + +static func _popup(theme: Theme) -> void: + var panel: PlateStyle = HudStyle.panel_style(6) + panel.fill = Color(HudStyle.PANEL_COLOR, 0.98) + panel.marker = Color.TRANSPARENT + theme.set_stylebox(&"panel", &"PopupMenu", panel) + var hovered := StyleBoxFlat.new() + hovered.bg_color = Color(HudStyle.ACCENT_COLOR, 0.16) + theme.set_stylebox(&"hover", &"PopupMenu", hovered) + theme.set_color(&"font_color", &"PopupMenu", HudStyle.TEXT_COLOR) + theme.set_color(&"font_hover_color", &"PopupMenu", Color.WHITE) + theme.set_font_size(&"font_size", &"PopupMenu", 12) diff --git a/game/ui/hud_theme.gd.uid b/game/ui/hud_theme.gd.uid new file mode 100644 index 00000000..9ce9b921 --- /dev/null +++ b/game/ui/hud_theme.gd.uid @@ -0,0 +1 @@ +uid://u4kg8c17co4r diff --git a/game/ui/info_panel.gd b/game/ui/info_panel.gd index 87af20fc..34789974 100644 --- a/game/ui/info_panel.gd +++ b/game/ui/info_panel.gd @@ -1,8 +1,9 @@ class_name InfoPanel extends Control -## A page of reading over whatever is behind it: "How to play" (from the title and -## the pause menu; the keys and mouse buttons named are the player's own, for the -## mouse scheme in use) and the credits (from the title and after the ending). Back +## A page of reading over whatever is behind it: "How to play" and "Controls" (every +## mouse button and key the game uses, in one list), both from the title and the +## pause menu (the keys and mouse buttons named are the player's own, for the +## mouse scheme in use), and the credits (from the title and after the ending). Back ## (or Esc) closes it and emits `closed`. signal closed @@ -15,6 +16,7 @@ const HEIGHT: float = 520.0 ## Space kept free above and below the panel, px. const SCREEN_MARGIN: float = 16.0 const PAGE_HOW_TO_PLAY: StringName = &"how_to_play" +const PAGE_CONTROLS: StringName = &"controls" const PAGE_CREDITS: StringName = &"credits" const GAME_NAME: String = "Farlanding" @@ -83,6 +85,12 @@ func open_how_to_play() -> void: Events.ui_feedback.emit(&"click") +## Opens "Controls" for the mouse scheme in use. +func open_controls() -> void: + _open(PAGE_CONTROLS, "Controls", controls_text(Settings.control_scheme)) + Events.ui_feedback.emit(&"click") + + ## Opens the credits. func open_credits() -> void: _open(PAGE_CREDITS, "Credits", credits_text()) @@ -168,12 +176,16 @@ static func how_to_play_text(scheme: StringName) -> String: "KEYS", ( ( - "Ctrl + a group key (%s-%s) stores a control group, the key recalls it (twice to" + "Select units and press Alt (Option on a Mac) or Ctrl + a group key (%s-%s)" % [KeyBindings.label(&"control_group_1"), KeyBindings.label(&"control_group_9")] ) - + " centre on it)." + + " to make them a control group; Shift + the key adds the selection to it (or" + + " starts the group), which works in every browser. The key alone selects the" + + " group again (twice centres on it), and so does a click on its badge above the" + + " selection panel; right-clicking the badge makes the selection that group." + + " Browsers keep Ctrl + a number (and on Linux Alt + a number) for their tabs." + ( - " %s codex · %s all controls · %s quicksave · %s quickload · Esc pause." + " %s Survey Log · %s all controls · %s quicksave · %s quickload · Esc pause." % [ KeyBindings.label(&"codex"), KeyBindings.label(&"controls_help"), @@ -184,7 +196,7 @@ static func how_to_play_text(scheme: StringName) -> String: ), ( "Every key can be changed under Settings > Keys; the mouse scheme under" - + " Settings > General." + + " Settings > General. Controls (title and pause menu) lists them all." ), "", "FIELD NOTES", @@ -196,6 +208,85 @@ static func how_to_play_text(scheme: StringName) -> String: return "\n".join(lines) +## Every control the game has for `scheme` (Settings.SCHEMES): the mouse first, then +## the keys as bound now (KeyBindings), grouped like Settings > Keys. +static func controls_text(scheme: StringName) -> String: + var classic: bool = scheme == Settings.SCHEME_CLASSIC + var command: String = "Left click" if classic else "Right click" + var first: String = KeyBindings.label(&"control_group_1") + var last: String = KeyBindings.label(&"control_group_9") + var groups: String = "%s-%s" % [first, last] + var lines: PackedStringArray = [ + "MOUSE (%s scheme; change it under Settings > General)" % scheme, + "Left click · select a unit or building", + "Left drag · box-select units (Shift adds to the selection)", + "Double click · select every unit of that type on screen", + "Shift + click · add or remove a unit", + "%s ground · move the selected units there" % command, + "%s enemy in sight · attack it" % command, + "%s deposit · harvest (Haulers)" % command, + "%s ? signal · scan (Surveyors)" % command, + "%s own building site · help build (Fabricators)" % command, + "%s ground with a building selected · set its rally point" % command, + ( + "Right click · deselect; cancel placing or aiming" + if classic + else "Left click empty ground · deselect; right click: cancel placing or aiming" + ), + "Shift + order · queue it after the current one; Shift + place: place several", + "Middle drag · pan the camera · Wheel: zoom", + ( + "Minimap: left click or drag looks there" + + ("" if classic else "; right click moves the selected units there") + ), + "", + "CAMERA", + ( + "%s %s %s %s or %s %s %s %s · pan (the screen edge pans too)" + % [ + KeyBindings.label(&"camera_pan_forward_alt"), + KeyBindings.label(&"camera_pan_left_alt"), + KeyBindings.label(&"camera_pan_back_alt"), + KeyBindings.label(&"camera_pan_right_alt"), + KeyBindings.label(&"camera_pan_forward"), + KeyBindings.label(&"camera_pan_left"), + KeyBindings.label(&"camera_pan_back"), + KeyBindings.label(&"camera_pan_right"), + ] + ), + ( + "%s / %s · turn left / right" + % [ + KeyBindings.label(&"camera_rotate_left"), + KeyBindings.label(&"camera_rotate_right"), + ] + ), + "", + "ORDERS", + "%s · stop" % KeyBindings.label(&"order_stop"), + "Esc · cancel placing a building or aiming a field option", + "", + "CONTROL GROUPS", + "Alt + %s (Option on a Mac) · make the selection group 1-9" % groups, + "Ctrl + %s (Cmd on a Mac) · the same (not in a browser: it switches tabs)" % groups, + "Shift + %s · add the selection to that group, or start it (works everywhere)" % groups, + "%s · select the group · press twice to centre the camera on it" % groups, + 'Group badges (bottom left, "1 · 5" = group 1, five units) · click to select', + "Right click a group badge · make the selection that group", + "", + "GAME", + "Esc or %s · pause menu" % KeyBindings.label(&"pause_menu"), + "%s · Survey Log" % KeyBindings.label(&"codex"), + "%s · controls panel in the mission" % KeyBindings.label(&"controls_help"), + "%s · quicksave" % KeyBindings.label(&"quicksave"), + "%s · quickload" % KeyBindings.label(&"quickload"), + "%s · debug overlay" % KeyBindings.label(&"debug_overlay"), + "", + "Every key can be changed under Settings > Keys, per mouse scheme.", + ] + return "\n".join(lines) + + ## The credits: the game, its makers, the tools and the notices their licences ask ## for, and where the sound comes from. static func credits_text() -> String: @@ -217,10 +308,10 @@ static func credits_text() -> String: ), 'GUT, the Godot Unit Test framework, by Tom "Butch" Wesley and contributors, MIT licence.', "gdtoolkit (gdformat, gdlint), by Pawel Lampe and contributors, MIT licence.", - ( - "The interface text uses the font built into Godot Engine (Open Sans), SIL" - + " Open Font Licence 1.1, among the engine's third-party notices." - ), + "Chakra Petch, Copyright 2018 The Chakra Petch Project Authors, SIL Open Font Licence 1.1.", + "", + "CHAKRA PETCH FONT LICENCE", + FileAccess.get_file_as_string("res://assets/fonts/OFL.txt").strip_edges(), "", "GODOT ENGINE LICENCE", Engine.get_license_text().strip_edges(), diff --git a/game/ui/meridian_screen.gd b/game/ui/meridian_screen.gd index caad4e11..89e82633 100644 --- a/game/ui/meridian_screen.gd +++ b/game/ui/meridian_screen.gd @@ -1,7 +1,7 @@ class_name MeridianScreen extends MenuScreen ## Aboard the Meridian (PLAN 1): the ship's overview (banked Intel, landings made, the -## codex, what the next landing will bring, and the campaign's difficulty, which may +## Survey Log, what the next landing will bring, and the campaign's difficulty, which may ## change here between landings), the tech web and the loadout, as tabs. STAR MAP ## goes back. The overview and the loadout scroll when the window is too short for ## them (the tech web scrolls on its own). @@ -131,7 +131,7 @@ func loadout() -> LoadoutView: return _loadout -## The overview: landings, codex, techs, and what the next landing starts with. +## The overview: landings, Survey Log, techs, and what the next landing starts with. func overview_text() -> String: if session == null: return "" @@ -139,7 +139,7 @@ func overview_text() -> String: var lines: PackedStringArray = [] lines.append( ( - "Landings surveyed: %d Techs owned: %d / %d Codex entries: %d" + "Landings surveyed: %d Techs owned: %d / %d Log entries: %d" % [ state.won.size(), state.techs.size(), diff --git a/game/ui/minimap.gd b/game/ui/minimap.gd index dccc995f..49ad4e82 100644 --- a/game/ui/minimap.gd +++ b/game/ui/minimap.gd @@ -309,11 +309,5 @@ func _height(x: float, z: float) -> float: return world.heights.sample(x, z) if world != null and world.heights != null else 0.0 -static func _panel_style() -> StyleBoxFlat: - var style: StyleBoxFlat = StyleBoxFlat.new() - style.bg_color = HudStyle.PANEL_COLOR - style.border_color = HudStyle.ACCENT_COLOR - style.border_width_top = 2 - style.set_corner_radius_all(3) - style.set_content_margin_all(6) - return style +static func _panel_style() -> PlateStyle: + return HudStyle.panel_style(6) diff --git a/game/ui/pause_menu.gd b/game/ui/pause_menu.gd index 897abb4c..c709efef 100644 --- a/game/ui/pause_menu.gd +++ b/game/ui/pause_menu.gd @@ -1,14 +1,15 @@ class_name PauseMenu extends Control ## The in-mission menu (Esc, the pause key or the HUD's MENU button): Resume, Save, -## Load, Settings, How to play, Restart and Quit to missions over a dimmed map. It +## Load, Settings, How to play, Controls, Restart and Quit to missions over a dimmed map. It ## takes every click and key while open (the map behind it cannot be ordered about); ## Main pauses the sim clock and the camera. Esc closes it (or, with the settings, -## the slots or How to play open, those). +## the slots, How to play or Controls open, those). signal resume_pressed signal settings_pressed signal how_to_play_pressed +signal controls_pressed signal save_pressed signal load_pressed signal restart_pressed @@ -59,6 +60,7 @@ func _ready() -> void: column.add_child(_button("LOAD", load_pressed)) column.add_child(_button("SETTINGS", settings_pressed)) column.add_child(_button("HOW TO PLAY", how_to_play_pressed)) + column.add_child(_button("CONTROLS", controls_pressed)) column.add_child(_button("RESTART MISSION", restart_pressed)) _quit = _button("QUIT TO MISSIONS", quit_pressed) column.add_child(_quit) diff --git a/game/ui/plate_style.gd b/game/ui/plate_style.gd new file mode 100644 index 00000000..359f3ba1 --- /dev/null +++ b/game/ui/plate_style.gd @@ -0,0 +1,86 @@ +class_name PlateStyle +extends StyleBox +## The look of every panel and button: a plate of field equipment. A rectangle with +## its top-left and bottom-right corners cut at 45 degrees, a thin outline, and up to +## two small lights: a `marker` bar along the top edge (panels) and a `lamp` strip +## down the left edge (buttons). Drawn by hand because StyleBoxFlat can only round. + +## Fill of the plate. +var fill: Color = Color.BLACK +## Outline, one pixel wide. +var line: Color = Color.WHITE +## Length of the two corner cuts, px. +var cut: float = 8.0 +## Colour of the bar along the top edge; transparent draws none. +var marker: Color = Color.TRANSPARENT +## Length of that bar, px. +var marker_length: float = 36.0 +## Colour of the strip down the left edge; transparent draws none. +var lamp: Color = Color.TRANSPARENT +## Soft shadow around the plate, px; 0 draws none. +var shadow: float = 0.0 + + +func _init(p_fill: Color = Color.BLACK, p_line: Color = Color.WHITE, p_cut: float = 8.0) -> void: + fill = p_fill + line = p_line + cut = p_cut + + +func _draw(to_canvas_item: RID, rect: Rect2) -> void: + var corner: float = minf(cut, minf(rect.size.x, rect.size.y) * 0.5) + if shadow > 0.0: + _draw_shadow(to_canvas_item, rect, corner) + RenderingServer.canvas_item_add_polygon( + to_canvas_item, outline(rect, corner), PackedColorArray([fill]) + ) + if line.a > 0.0: + # Half a pixel in, so the one-pixel line sits on whole pixels. + var edge: PackedVector2Array = outline(rect.grow(-0.5), corner) + edge.append(edge[0]) + RenderingServer.canvas_item_add_polyline( + to_canvas_item, edge, PackedColorArray([line]), 1.0, true + ) + if marker.a > 0.0: + var length: float = minf(marker_length, rect.size.x - corner * 2.0) + RenderingServer.canvas_item_add_rect( + to_canvas_item, + Rect2(rect.position + Vector2(corner + 2.0, 0.0), Vector2(length, 2.0)), + marker + ) + if lamp.a > 0.0: + var top: float = corner + 3.0 + RenderingServer.canvas_item_add_rect( + to_canvas_item, + Rect2(rect.position + Vector2(3.0, top), Vector2(2.0, rect.size.y - top - 4.0)), + lamp + ) + + +## The plate's six corners for `rect`, clockwise from the top-left cut. +static func outline(rect: Rect2, corner: float) -> PackedVector2Array: + var left: float = rect.position.x + var top: float = rect.position.y + var right: float = rect.end.x + var bottom: float = rect.end.y + return PackedVector2Array( + [ + Vector2(left + corner, top), + Vector2(right, top), + Vector2(right, bottom - corner), + Vector2(right - corner, bottom), + Vector2(left, bottom), + Vector2(left, top + corner), + ] + ) + + +func _draw_shadow(to_canvas_item: RID, rect: Rect2, corner: float) -> void: + const STEPS: int = 6 + for step: int in STEPS: + var grow: float = shadow * float(STEPS - step) / float(STEPS) + RenderingServer.canvas_item_add_polygon( + to_canvas_item, + outline(rect.grow(grow), corner + grow * 0.5), + PackedColorArray([Color(0, 0, 0, 0.09)]) + ) diff --git a/game/ui/plate_style.gd.uid b/game/ui/plate_style.gd.uid new file mode 100644 index 00000000..1014fe4e --- /dev/null +++ b/game/ui/plate_style.gd.uid @@ -0,0 +1 @@ +uid://bhkqylerhfxyf diff --git a/game/ui/resource_bar.gd b/game/ui/resource_bar.gd index e746d0a1..5203dd6f 100644 --- a/game/ui/resource_bar.gd +++ b/game/ui/resource_bar.gd @@ -18,11 +18,7 @@ var _low_power: Label ## Builds the bar and shows the faction's current stockpile from `economy` (if any). func setup(p_faction: int, economy: Economy) -> void: faction = p_faction - var style := StyleBoxFlat.new() - style.bg_color = HudStyle.PANEL_COLOR - style.border_color = HudStyle.ACCENT_COLOR - style.border_width_bottom = 2 - style.set_corner_radius_all(3) + var style: PlateStyle = HudStyle.panel_style() style.content_margin_left = 16 style.content_margin_right = 16 style.content_margin_top = 6 diff --git a/game/ui/star_map.gd b/game/ui/star_map.gd index f315d9c0..1fac4824 100644 --- a/game/ui/star_map.gd +++ b/game/ui/star_map.gd @@ -175,7 +175,7 @@ func _signals_text(mission: MissionDef) -> String: known += 1 var text: String = "%d unresolved ? signals" % sites.size() if known > 0: - text += " (%d match codex entries)" % known + text += " (%d match log entries)" % known return text diff --git a/game/ui/subtitle_line.gd b/game/ui/subtitle_line.gd index 244f5ecb..6f891f51 100644 --- a/game/ui/subtitle_line.gd +++ b/game/ui/subtitle_line.gd @@ -34,7 +34,7 @@ func _ready() -> void: _band.mouse_filter = Control.MOUSE_FILTER_IGNORE var style := StyleBoxFlat.new() style.bg_color = BAND - style.set_corner_radius_all(3) + style.set_corner_radius_all(0) style.content_margin_left = 14 style.content_margin_right = 14 style.content_margin_top = 6 diff --git a/game/ui/codex_panel.gd b/game/ui/survey_log_panel.gd similarity index 89% rename from game/ui/codex_panel.gd rename to game/ui/survey_log_panel.gd index 2afbeb0b..912f0e07 100644 --- a/game/ui/codex_panel.gd +++ b/game/ui/survey_log_panel.gd @@ -1,9 +1,9 @@ -class_name CodexPanel +class_name SurveyLogPanel extends PanelContainer -## The codex: every discovery the player has made, newest first, with its codex +## The Survey Log: every discovery the player has made, newest first, with its log ## text. A list of titles on the left, the chosen entry on the right. Opened and ## closed from the HUD (button or C). Fills from the Discovery system when it opens -## and from `Events.codex_entry_added` while the mission runs. +## and from `Events.survey_log_entry_added` while the mission runs. ## Type label and colour per discovery type. const TYPE_NAMES: Dictionary[StringName, String] = { @@ -32,7 +32,7 @@ func _init() -> void: add_child(column) var header := HBoxContainer.new() column.add_child(header) - var heading: Label = HudStyle.make_label(13, HudStyle.ACCENT_COLOR, "CODEX") + var heading: Label = HudStyle.make_label(13, HudStyle.ACCENT_COLOR, "SURVEY LOG") heading.size_flags_horizontal = Control.SIZE_EXPAND_FILL header.add_child(heading) var close: Button = HudStyle.make_small_button("Close (C)") @@ -64,7 +64,7 @@ func _init() -> void: _text.custom_minimum_size = Vector2(360, 0) page.add_child(_text) visible = false - Events.codex_entry_added.connect(_on_entry_added) + Events.survey_log_entry_added.connect(_on_entry_added) ## Shows the panel with `entries` (oldest first, as the Discovery system keeps them). @@ -72,14 +72,14 @@ func open_panel(entries: Array[DiscoveryDef]) -> void: _entries = entries.duplicate() _rebuild() visible = true - Events.ui_feedback.emit(&"codex_open") + Events.ui_feedback.emit(&"survey_log_open") func close_panel() -> void: if not visible: return visible = false - Events.ui_feedback.emit(&"codex_close") + Events.ui_feedback.emit(&"survey_log_close") func entry_count() -> int: @@ -117,8 +117,8 @@ func _show_entry(index: int) -> void: _type.text = "%s · %s" % [TYPE_NAMES.get(def.discovery_type, "UNKNOWN"), def.display_name] _type.add_theme_color_override(&"font_color", def.color) _title.text = _title_of(def) - _text.text = def.codex_text + _text.text = def.log_text static func _title_of(def: DiscoveryDef) -> String: - return def.codex_title if def.codex_title != "" else def.display_name + return def.log_title if def.log_title != "" else def.display_name diff --git a/game/ui/codex_panel.gd.uid b/game/ui/survey_log_panel.gd.uid similarity index 100% rename from game/ui/codex_panel.gd.uid rename to game/ui/survey_log_panel.gd.uid diff --git a/game/ui/tech_web_view.gd b/game/ui/tech_web_view.gd index 152ddb27..0f56f593 100644 --- a/game/ui/tech_web_view.gd +++ b/game/ui/tech_web_view.gd @@ -219,7 +219,7 @@ static func _card_style(color: Color, style_name: StringName) -> StyleBoxFlat: style.border_color = color style.set_border_width_all(1) style.border_width_left = 4 - style.set_corner_radius_all(3) + style.set_corner_radius_all(0) style.set_content_margin_all(8) return style diff --git a/game/ui/title_screen.gd b/game/ui/title_screen.gd index 91d9525c..b0b01d43 100644 --- a/game/ui/title_screen.gd +++ b/game/ui/title_screen.gd @@ -1,7 +1,7 @@ class_name TitleScreen extends MenuScreen ## The first screen: Continue (when an autosave exists), New campaign, Single missions -## (the mission select), How to play, Settings, Credits and Quit. New campaign first +## (the mission select), How to play, Controls, Settings, Credits and Quit. New campaign first ## asks for the difficulty (remembered in the settings for next time); START emits ## `new_campaign_pressed`. On a short window the menu buttons scroll under the name. @@ -11,6 +11,7 @@ signal missions_pressed signal settings_pressed signal quit_pressed signal how_to_play_pressed +signal controls_pressed signal credits_pressed ## Space kept free above and below the column, px. @@ -47,6 +48,7 @@ func _build() -> void: _menu.add_child(start) _add_button(_menu, "SINGLE MISSIONS", missions_pressed) _add_button(_menu, "HOW TO PLAY", how_to_play_pressed) + _add_button(_menu, "CONTROLS", controls_pressed) _add_button(_menu, "SETTINGS", settings_pressed) _add_button(_menu, "CREDITS", credits_pressed) if not OS.has_feature("web"): diff --git a/game/ui/tutorial_hints.gd b/game/ui/tutorial_hints.gd index 7adeecc2..f77cd99e 100644 --- a/game/ui/tutorial_hints.gd +++ b/game/ui/tutorial_hints.gd @@ -15,7 +15,15 @@ var director: HintDirector = HintDirector.new() ## The hint on screen, or null. var shown: HintDef = null ## True while the mission is paused: no hint comes due and the card's time stands still. -var suspended: bool = false +var suspended: bool = false: + set(value): + suspended = value + _refresh_card() +## An in-mission overlay, such as the Survey Log, covers the tutorial card. +var obscured: bool = false: + set(value): + obscured = value + _refresh_card() var _card: PanelContainer var _title: Label @@ -27,8 +35,8 @@ func _ready() -> void: set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) mouse_filter = Control.MOUSE_FILTER_IGNORE _card = HudStyle.make_panel() - var style: StyleBoxFlat = HudStyle.panel_style() - style.border_color = HINT_COLOR + var style: PlateStyle = HudStyle.panel_style() + style.marker = HINT_COLOR _card.add_theme_stylebox_override(&"panel", style) _card.mouse_filter = Control.MOUSE_FILTER_IGNORE add_child(_card) @@ -72,6 +80,7 @@ func setup(catalog: HintCatalog) -> void: func begin_mission(mission: MissionDef) -> void: _hide() suspended = false + obscured = false director.begin(mission.mission_type if mission != null else &"") @@ -82,7 +91,7 @@ func end_mission() -> void: func _process(delta: float) -> void: - if not director.active or suspended: + if not director.active or suspended or obscured: return director.advance(delta) if shown != null: @@ -128,7 +137,7 @@ func _show(hint: HintDef) -> void: _shown_for = 0.0 _title.text = hint.title _text.text = fill(hint.text) - _card.visible = true + _refresh_card() Events.ui_feedback.emit(&"hint_show") @@ -136,3 +145,8 @@ func _hide() -> void: shown = null if _card != null: _card.visible = false + + +func _refresh_card() -> void: + if _card != null: + _card.visible = shown != null and not suspended and not obscured diff --git a/game/ui/ui_theme.gd b/game/ui/ui_theme.gd new file mode 100644 index 00000000..af9a220c --- /dev/null +++ b/game/ui/ui_theme.gd @@ -0,0 +1,14 @@ +extends Node +## Autoload: gives every control, in the game and in the tests, the game's typeface +## and stock-control look (HudTheme) before any screen is built. It merges into the +## engine's default theme, not the root window's: a control under a CanvasLayer or +## other plain node does not inherit the window's theme, and most screens sit under +## one. + + +func _enter_tree() -> void: + var look: Theme = HudTheme.build() + var base: Theme = ThemeDB.get_default_theme() + base.merge_with(look) + base.default_font = look.default_font + ThemeDB.fallback_font = look.default_font diff --git a/game/ui/ui_theme.gd.uid b/game/ui/ui_theme.gd.uid new file mode 100644 index 00000000..cbfd44d9 --- /dev/null +++ b/game/ui/ui_theme.gd.uid @@ -0,0 +1 @@ +uid://d241yv540vbfk diff --git a/tools/web_tests/graphics.spec.cjs b/tools/web_tests/graphics.spec.cjs index 818add91..217e3c75 100644 --- a/tools/web_tests/graphics.spec.cjs +++ b/tools/web_tests/graphics.spec.cjs @@ -30,6 +30,9 @@ async function button(page, text) { async function legacyProfile(page) { await boot(page, 'low'); await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); + // Stop the old engine before editing its persisted fixture, so its sync loop + // cannot replace the legacy record while the next profile is being prepared. + await page.reload(); await page.evaluate(async () => { const db = await new Promise((resolve, reject) => { const request = indexedDB.open('/userfs'); @@ -60,7 +63,6 @@ async function legacyProfile(page) { }); db.close(); }); - await page.reload(); await play(page, 'saved'); await expect.poll(async () => (await state(page))?.graphics_upgrade_available, { timeout: 90000 }).toBe(true); } diff --git a/tools/web_tests/groups.spec.cjs b/tools/web_tests/groups.spec.cjs new file mode 100644 index 00000000..cafed27b --- /dev/null +++ b/tools/web_tests/groups.spec.cjs @@ -0,0 +1,61 @@ +const { play } = require('./launch.cjs'); +const { test, expect } = require('@playwright/test'); + +async function state(page) { return page.evaluate(() => window.farlanding?.diagnostics); } +async function button(page, label) { + await expect.poll(async () => (await state(page))?.buttons.some(b => b.text.startsWith(label))).toBe(true); + const target = (await state(page)).buttons.find(b => b.text.startsWith(label)); + await page.mouse.click(...target.pixel, { delay: 80 }); +} +const sorted = ids => [...ids].sort((a, b) => a - b); + +// Ctrl/Cmd + a number belongs to the browser (tabs); Alt + the number reaches the game. +test('Alt+1 stores a control group and 1 selects it again in the browser build', async ({ page }, info) => { + await page.goto('http://127.0.0.1:8071/?mission=conquest'); + await play(page); + await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); + await expect.poll(async () => (await state(page))?.mission).toBe('conquest'); + await button(page, 'GOT IT'); + const view = page.viewportSize(); + const onScreen = unit => unit.faction === 0 && unit.pixel[0] > 40 && unit.pixel[0] < view.width - 40 + && unit.pixel[1] > 80 && unit.pixel[1] < view.height - 200; + await expect.poll(async () => (await state(page)).units.filter(onScreen).length).toBeGreaterThan(1); + const [first, second] = (await state(page)).units.filter(onScreen); + await page.mouse.click(...first.pixel, { delay: 80 }); + await expect.poll(async () => (await state(page)).selected).toContain(first.id); + await page.keyboard.down('Shift'); + await page.mouse.click(...second.pixel, { delay: 80 }); + await page.keyboard.up('Shift'); + await expect.poll(async () => (await state(page)).selected).toContain(second.id); + let group = sorted((await state(page)).selected); + expect(group.length).toBeGreaterThan(1); + + await page.keyboard.press('Alt+1'); + // The HUD's group bar shows group 1 with its unit count. + await expect.poll(async () => (await state(page)).buttons.some(b => b.text === `1 · ${group.length}`)).toBe(true); + // The Hauler starts mining immediately; a sampled position can be stale on + // software-rendered CI by the time the click arrives. Use the idle Surveyor. + const third = (await state(page)).units.find(unit => onScreen(unit) + && unit.kind === 'concord_surveyor' && !group.includes(unit.id)); + expect(third, 'the visible idle Surveyor can be added').toBeTruthy(); + await page.mouse.click(...third.pixel, { delay: 80 }); + await expect.poll(async () => (await state(page)).selected).toEqual([third.id]); + await page.keyboard.press('Shift+1'); + group = sorted([...group, third.id]); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text === `1 · ${group.length}`)).toBe(true); + await page.screenshot({ path: info.outputPath('stored-group.png') }); + + // Classic scheme: right click deselects. + await page.mouse.click(...(await state(page)).ground[0], { button: 'right', delay: 80 }); + await expect.poll(async () => (await state(page)).selected).toEqual([]); + + await page.keyboard.press('1'); + await expect.poll(async () => sorted((await state(page)).selected)).toEqual(group); + + // Clicking the badge does the same. + await page.mouse.click(...(await state(page)).ground[0], { button: 'right', delay: 80 }); + await expect.poll(async () => (await state(page)).selected).toEqual([]); + await button(page, `1 · ${group.length}`); + await expect.poll(async () => sorted((await state(page)).selected)).toEqual(group); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); +}); diff --git a/tools/web_tests/ui_style.spec.cjs b/tools/web_tests/ui_style.spec.cjs new file mode 100644 index 00000000..e897a7a3 --- /dev/null +++ b/tools/web_tests/ui_style.spec.cjs @@ -0,0 +1,101 @@ +const { test, expect } = require('@playwright/test'); +const { play } = require('./launch.cjs'); +const state = page => page.evaluate(() => window.farlanding?.diagnostics); +async function click(page, text) { + await expect.poll(async () => (await state(page))?.buttons.some(b => b.text.startsWith(text))).toBe(true); + const b = (await state(page)).buttons.find(b => b.text.startsWith(text)); + const view = page.viewportSize(); + expect(b.pixel[0]).toBeGreaterThan(0); expect(b.pixel[0]).toBeLessThan(view.width); + expect(b.pixel[1]).toBeGreaterThan(0); expect(b.pixel[1]).toBeLessThan(view.height); + await page.mouse.click(...b.pixel, { delay: 80 }); +} +async function capture(page, info, name) { + await page.screenshot({ path: info.outputPath(`${name}.png`) }); + await info.attach(name, { body: JSON.stringify(await state(page)), contentType: 'application/json' }); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); +} +if (process.env.WEB_UI_QUALIFY) { + for (const scale of [1, 1.3]) { + test(`field-kit screens at 2000x754 and ${scale * 100}% UI`, async ({ page }, info) => { + test.setTimeout(240000); + await page.setViewportSize({ width: 2000, height: 754 }); + await page.goto('http://127.0.0.1:8071/'); await play(page); + await expect.poll(async () => (await state(page))?.screen, { timeout: 90000 }).toBe('title'); + await click(page, 'SETTINGS'); await click(page, 'ACCESSIBILITY'); + await click(page, '100%'); + await expect.poll(async () => (await state(page)).popups.length).toBeGreaterThan(0); + const popup = (await state(page)).popups.find(p => p.items.some(t => t.startsWith(`${scale * 100}%`))); + const index = popup.items.findIndex(t => t.startsWith(`${scale * 100}%`)); + await page.mouse.click(popup.position[0] + popup.size[0] / 2, + popup.position[1] + popup.size[1] * (index + 0.5) / popup.items.length, { delay: 80 }); + await expect.poll(async () => (await state(page)).ui_scale).toBe(scale); + await capture(page, info, 'accessibility'); await click(page, 'GENERAL'); + await capture(page, info, 'settings'); await click(page, 'BACK'); + await capture(page, info, 'title'); + for (const [label, name] of [['HOW TO PLAY', 'help'], ['CONTROLS', 'controls'], ['CREDITS', 'credits']]) { + await click(page, label); await capture(page, info, name); await click(page, 'BACK'); + } + await click(page, 'SINGLE MISSIONS'); await capture(page, info, 'missions'); + const card = (await state(page)).buttons.find(b => b.text === ''); + expect(card, 'first unlocked mission card').toBeTruthy(); + await page.mouse.click(...card.pixel, { delay: 80 }); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('START LANDING'))).toBe(true); + await capture(page, info, 'briefing'); await click(page, 'BACK'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text === '')).toBe(true); + await click(page, 'BACK'); + await expect.poll(async () => (await state(page)).screen).toBe('title'); + await click(page, 'NEW CAMPAIGN'); await capture(page, info, 'campaign-setup'); await click(page, 'START'); + await expect.poll(async () => (await state(page)).screen).toBe('star_map'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.name === 'kessel_proving')).toBe(true); + const landing = (await state(page)).buttons.find(b => b.name === 'kessel_proving'); + await capture(page, info, 'star-map'); await click(page, 'MERIDIAN'); + await capture(page, info, 'meridian'); await click(page, 'TECH WEB'); await capture(page, info, 'tech-web'); + await click(page, 'LOADOUT'); await capture(page, info, 'loadout'); await click(page, 'STAR MAP'); + await expect.poll(async () => (await state(page)).screen).toBe('star_map'); + expect(landing).toBeTruthy(); await page.mouse.click(...landing.pixel, { delay: 80 }); + await click(page, 'LAUNCH'); await click(page, 'START LANDING'); + await expect.poll(async () => (await state(page)).tick, { timeout: 90000 }).toBeGreaterThan(0); + await click(page, 'GOT IT'); await capture(page, info, 'hud'); + await page.keyboard.press('c'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('Close'))).toBe(true); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text === 'GOT IT')).toBe(false); + await capture(page, info, 'survey-log'); await click(page, 'Close'); + await page.keyboard.press('Escape'); + await expect.poll(async () => (await state(page)).paused).toBe(true); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text === 'GOT IT')).toBe(false); + await capture(page, info, 'pause'); + await click(page, 'CONTROLS'); await capture(page, info, 'pause-controls'); await click(page, 'BACK'); + await click(page, 'RESUME'); + await expect.poll(async () => (await state(page)).paused).toBe(false); + if (scale === 1.3) { + await page.setViewportSize({ width: 1152, height: 648 }); + await page.goto('http://127.0.0.1:8071/?mission=conquest'); await play(page); + await expect.poll(async () => (await state(page))?.tick, { timeout: 90000 }).toBeGreaterThan(0); + expect((await state(page)).ui_scale).toBe(scale); + const worker = (await state(page)).units.find(u => u.faction === 0 && u.kind === 'concord_fabricator'); + await page.mouse.click(...worker.pixel, { delay: 80 }); + await expect.poll(async () => (await state(page)).selected).toContain(worker.id); + for (let digit = 1; digit <= 9; digit++) await page.keyboard.press(`Alt+${digit}`); + await expect.poll(async () => (await state(page)).buttons.filter(b => /^\d · 1$/.test(b.text)).length).toBe(9); + await expect.poll(async () => { + const s = (await state(page)).command_scroll; + return s && s.maximum > s.page && s.rect[3] > 0; + }).toBe(true); + const scroll = (await state(page)).command_scroll; + const [sx, sy, sw, sh] = scroll.rect; + await page.mouse.move(sx + sw * scroll.page / scroll.maximum / 2, sy + sh / 2); + await page.mouse.down(); + await page.mouse.move(sx + sw - 2, sy + sh / 2, { steps: 8 }); + await page.mouse.up(); + await expect.poll(async () => { + const last = (await state(page)).buttons.find(b => b.text.startsWith('Survey Lab')); + return last && last.pixel[0] > 0 && last.pixel[0] < 850; + }).toBe(true); + await capture(page, info, 'narrow-commands'); + await click(page, 'Survey Lab'); + await expect.poll(async () => (await state(page)).placing).toBe(true); + await page.keyboard.press('Escape'); + } + }); + } +}