diff --git a/README.md b/README.md index 757ba6ed..0e688412 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Farlanding is a single-player 3D real-time strategy game about a survey expediti beyond familiar space. Build bases, command a growing force, and uncover a trail of discoveries that changes what your expedition can do. Made with Godot and Blender. -**[Play in your browser](https://farlanding.vercel.app)** · +**[Play in your browser](https://farlanding.app)** · [Player guide](docs/PLAYER_GUIDE.md) · [Development plan](docs/PLAN.md) ![The Meridian in orbit above the expedition's first world](docs/media/browser-orbit.png) diff --git a/docs/ART_STYLE.md b/docs/ART_STYLE.md index bc84c284..0d1a2d93 100644 --- a/docs/ART_STYLE.md +++ b/docs/ART_STYLE.md @@ -29,7 +29,9 @@ diffable and rebuildable. | `art/pipeline/build_all.py` | Rebuilds every model and the palette | | `art/pipeline/build_icons.py` | Renders a HUD icon per model into `game/assets/icons/` | -Rebuild everything: `blender -b -P art/pipeline/build_all.py`. +Rebuild models and palette: `blender -b -P art/pipeline/build_all.py`. +Terrain recipes under `art/terrain/` and HUD icon rendering through +`art/pipeline/build_icons.py` are separate steps; rebuilding models does not rebuild them. ### Texturing: one palette for the whole game @@ -70,3 +72,10 @@ cyan instrument lamps. Orange marks warnings. `HudStyle`, `PlateStyle` and 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. + +## Application icon + +`game/assets/branding/farlanding_icon.svg` is the editable favicon source. Its amber +landing chevron and cyan planet rim use the HUD palette. Rebuild the committed 512px +PNG with `game/assets/branding/render_icon.sh` (requires `rsvg-convert`, from librsvg). +The application icon setting supplies native icons and the Web export's browser icon. diff --git a/docs/CONVENTIONS.md b/docs/CONVENTIONS.md index 8dd0c132..18f9fc16 100644 --- a/docs/CONVENTIONS.md +++ b/docs/CONVENTIONS.md @@ -5,7 +5,8 @@ Short rules for everyone writing code in `game/`. The why lives in `docs/PLAN.md ## Before you push Run `tools/check.sh`. It runs format check, lint, headless import, a script-error check, the -unit tests and a boot of the main scene, and must exit 0. CI runs the same script. +unit tests, every-mission smoke, Python tooling tests and source/asset integrity checks. +It must exit 0. CI runs the same script. Engine and GUT warnings/deprecations fail the gate. - Format: `cd game && uvx --from gdtoolkit==4.5.0 gdformat .` - Tests: `godot --headless --path game -s res://addons/gut/gut_cmdln.gd` @@ -28,9 +29,12 @@ unit tests and a boot of the main scene, and must exit 0. CI runs the same scrip core <- sim <- ai / missions <- presentation / ui / audio -A folder may use anything to its left, never to its right. `sim/` never references a UI node, a -sound or a particle: it emits typed signals on `Events` (or its own nodes) and presentation, -UI and audio listen. +Simulation **scripts** must not depend on UI, audio or presentation scripts; +`tools/project_integrity.py` checks adapter class/path references. Simulation emits typed +signals on `Events` (or its own nodes), and adapters listen. Entity **scenes** may compose +simulation and visual children. `Main` and `LandingMap` are composition roots: they wire +the layers and provide dependencies before children enter the tree. Scene composition +does not imply that simulation code may call its visual children. ## Architecture rules in practice @@ -39,7 +43,9 @@ UI and audio listen. - **Gameplay runs on `SimClock` ticks (10 Hz)**, not in `_process`. Visuals interpolate with `SimClock.get_interpolation_fraction()`. - **Mission-scoped things hang off `MissionContext`**, never an autoload. Autoloads are only - `Events`, `Game`, `Settings` (and later `Audio`, `Save`). + `Events`, `Game`, `Settings`, `Audio` and `UiTheme`; the editor integration also + installs `MCPRuntimeProbe` (disabled by release feature, see the Web runtime ADR). + `SaveSlots` is a static service, not an autoload. - **Definitions are data**: new unit types are new `UnitDef` `.tres` files, not new code. - **Composition over inheritance**: an entity is a thin root plus component nodes. - **Saveable from day one**: any class that holds gameplay state has `to_dict()` / @@ -61,3 +67,17 @@ UI and audio listen. - Commit `*.import` and `*.uid` files; never commit `.godot/`. - Binaries go through Git LFS once it is enabled (see `.gitattributes`). - Record expensive-to-reverse choices as a short ADR in `docs/adr/`. + +## Ownership and cleanup + +- A scene owns its child nodes. Configure dependencies before `add_child()`, which runs `_ready()`. +- A RefCounted fixture does not own nodes it attaches elsewhere: retain the fixture and call + its `dispose()` in `after_each`. Use GUT's autofree helpers only when they actually register ownership. +- A service that creates server RIDs releases them explicitly (`PathService.release()`). + Keep cleanup with the owner, including navigation, traffic registration and shader globals. +- Restore snapshots in dependency order: identities before references, planetary conditions + before path-dependent orders. Preserve the save version unless the serialized shape changes. +- Audio source recipes own generated streams and import sidecars; existing SoundEvents own + hand-tuned mix values. `project_integrity.py` checks hashes/inventory without regenerating audio. + Recipe edits also need the deterministic `audio_src/build.py --check` command documented in + `docs/AUDIO_PROVENANCE.md`; encoder versions can affect output hashes. diff --git a/docs/MAINTAINABILITY_PLAN.md b/docs/MAINTAINABILITY_PLAN.md new file mode 100644 index 00000000..fcf8290a --- /dev/null +++ b/docs/MAINTAINABILITY_PLAN.md @@ -0,0 +1,84 @@ +# Project maintainability improvements + +Baseline: `593b8a5`. The audit covered game code, test ownership, tooling, CI, +asset pipelines and architecture documentation. Preserve gameplay, save formats, +resource paths, rendering quality and the tested-artifact deployment pipeline. + +## Phase 1: make diagnostics trustworthy + +Dispose the Verdance test fixture explicitly, replace deprecated GUT frame waits +with their identical physics-frame successor, and reject GUT warnings and +deprecations alongside engine diagnostics. Share diagnostic classification between +checks and exports. Run Python tooling checks locally as well as in CI. +Proof: diagnostic fixtures, focused Verdance run and complete native checks. + +## Phase 2: fix runtime defects before restructuring + +Reproduce placement over blocking props, then include public map obstacles without +revealing unseen enemy buildings to AI. Validate malformed save containers and +resource types before replacing the running landing. Preserve legacy saves. +Proof: focused failing-before regressions, placement commands and save round trips. + +## Phase 3: clarify responsibilities + +Use the existing LandingMap contract in Main instead of reflective property access. +Split world restoration into named ordered phases without exposing its registries. +Separate one-shot playback pools from mission/music orchestration in Audio while +preserving its public API, randomness, voice budgets and shutdown behavior. +Proof: mission/pause/save tests, planetary round trips and real-mixer audio tests. + +## Phase 4: maintain the boundaries + +Document actual composition roots and scene composition, fixture/node/RID ownership, +and the current autoloads. Add inexpensive asset manifest and simulation dependency +checks. Clarify separate art rebuild pipelines and hand-tuned audio resource ownership. +Keep third-party addons unchanged and avoid bulk asset regeneration. + +## Phase 5: qualify and release + +Run complete native checks, every-mission smoke, browser gameplay/persistence and +real-mixer qualification. Measure any proposed performance optimization against the +same scenario; ship only justified changes with unchanged visual settings. Obtain an +independent Sol review, resolve CI/bot findings, merge normally and verify both staged +and public Vercel deployment of the exact merge commit. + +Menu navigation includes direct title-screen loading with Back/Escape return paths. +The browser launcher retains a deliberate Play gesture for browser audio, uses the +field-equipment palette, and places clearly explained graphics overrides under Launch options. +The README play link is https://farlanding.app; verify that domain after release. + +The favicon is a separate visual addition. Keep its source editable and include a +Godot-compatible raster icon; do not couple it to runtime architecture. + +## Research basis + +Godot recommends focused scenes/classes and parent-provided dependencies: +[Scene organization](https://docs.godotengine.org/en/stable/tutorials/best_practices/scene_organization.html). +Its [project organization guidance](https://docs.godotengine.org/en/stable/tutorials/best_practices/project_organization.html) +supports consistent paths and isolated third-party addons, rather than gratuitous moves. +[Static typing](https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/static_typing.html) +improves diagnostics and enables optimized operations. Ref's primary-source +[GDScript analyzer reference](https://github.com/godotengine/godot/blob/master/modules/gdscript/README.md) +explains the limits of dynamic access and the role of typed interfaces. + +Do not rewrite the command queue, fixed-tick simulation, navigation cutter/traffic, +resource-driven definitions or platform rendering/audio adapters. A broad rewrite +would increase migration risk without an observed defect or measured benefit. + +## Added gameplay slice: selling buildings + +Add a tick-driven sell command and a selected-building action with refund preview +and confirmation. Completed placeable buildings return half their construction +cost; unfinished sites cancel for a full refund. Refund queued production through +the existing cancellation rule. Protect other factions, the Lander and story +machines. Prove single refunds, queue cleanup, immediate snapshot removal and +navigation/power/vent release, then verify the visible browser flow. + +## Added exploration slice: remove advance discovery markers + +Remove floating discovery question marks and unresolved-site minimap icons. Show +site models once their ground is explored, preserve scanning/rewards and chain +availability, and record only completed player surveys on the minimap. Update +onboarding and orbital-preview copy. ADR 0023 records this user-requested decision. +Proof: unknown versus explored visibility, enemy versus player map records, scan +feedback, saved vision, and browser screenshots on the actual maps. diff --git a/docs/PLAYER_GUIDE.md b/docs/PLAYER_GUIDE.md index 79c7caee..50f4bb76 100644 --- a/docs/PLAYER_GUIDE.md +++ b/docs/PLAYER_GUIDE.md @@ -5,7 +5,7 @@ Detailed controls and mission rules follow, including planet-specific mechanics. **New campaign** puts you aboard the *Meridian*, the expedition carrier. The star map 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 +type and survey context), 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 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 @@ -74,3 +74,21 @@ 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. + +From the main menu, **Load game** opens all usable landing saves directly. **Continue** +resumes the latest saved state directly: the landing, or the campaign between missions. In the slot screen, **Back** or +**Esc** returns to the menu you came from; an empty or damaged slot cannot be loaded. + +The browser's **Launch options** override graphics only. **Use saved graphics** keeps +your settings, or starts on High on your first visit. Graphics, sound and controls are +available in the in-game **Settings** menu after launching. + +Discovery locations are not marked in advance. Explore the terrain and look for unusual +structures and formations. Select a Surveyor and command it to scan a site you find. +A completed survey adds a coloured record to the minimap and an entry to the Survey Log. + +Select one of your placeable buildings to **Sell** it. The button previews the Alloy +and Flux returned; click it again to confirm, or choose Cancel. Finished buildings +return 50% of their cost. Cancelling an unfinished site returns its construction cost, +and queued units are refunded using the normal cancellation rule. The Lander and +Antecedent story machines cannot be sold. diff --git a/docs/WEB_DEVELOPMENT.md b/docs/WEB_DEVELOPMENT.md index b1f18bd5..d999fb16 100644 --- a/docs/WEB_DEVELOPMENT.md +++ b/docs/WEB_DEVELOPMENT.md @@ -99,3 +99,10 @@ a push-to-`main` workflow while its tested artifact is retained, or rerun that e to create a fresh artifact. Manual **Run workflow** runs remain test-only. Existing ready deployments can still be promoted or rolled back without downloading the source artifact again. + +## Browser launcher + +The Play gesture follows Godot's [Web audio autoplay guidance](https://docs.godotengine.org/en/stable/tutorials/export/exporting_for_web.html#audio). +Launch options overrides only graphics: the default keeps saved settings, or High on a +fresh profile. Full settings stay inside the game. The custom shell lives in +`game/platform/web_shell.html`; the exported `index.icon.png` comes from the application icon. diff --git a/docs/adr/0002-lint-and-format.md b/docs/adr/0002-lint-and-format.md index 2340b972..aa02953c 100644 --- a/docs/adr/0002-lint-and-format.md +++ b/docs/adr/0002-lint-and-format.md @@ -32,3 +32,13 @@ all of it. If a future GDScript feature is not parsed by gdtoolkit, either avoid it or exclude that file in `gdlintrc`/`gdformatrc` and note it here. + +## Verification note (2026-11-15) + +Only the explicitly stored warning overrides are project policy; engine defaults +supply other settings. The earlier list overstated the committed configuration: +`inference_on_variant` and `directory_rules` are engine defaults rather than explicit +overrides in this checkout. Verified through the running 4.7.2 editor: inference is +level 2 and directory rules are `{ "res://addons": 0 }`, matching the intended policy. +The script/resource load check and actual project settings remain the executable authority. Engine and GUT diagnostic classification is now shared +by local checks and exports; GUT warnings and deprecated APIs also fail checks. diff --git a/docs/adr/0013-save-and-load.md b/docs/adr/0013-save-and-load.md index 286bd5e4..c12314d9 100644 --- a/docs/adr/0013-save-and-load.md +++ b/docs/adr/0013-save-and-load.md @@ -144,3 +144,16 @@ camera looks where it did. versions keep reading their older dictionaries. - Not saved: commands younger than a tick, transient AI timers, and the shooter of a projectile in flight. + +## Continue and explicit Load game (2026-11-15) + +The title now offers Load game for choosing a slot. Continue resumes the newest +readable landing directly when it is the latest saved state. A newer campaign +save between landings continues there. A campaign that already records a landing as won continues +on its star map or ending; old manual landings remain available through Load game. +With no usable landing, Continue falls back to the campaign save. + +Slot payloads may include optional integer `write_order` metadata to break equal +whole-second `saved_at` timestamps by actual write order. Legacy files default to +zero, older builds ignore the extra key, and the save format stays at 2. The displayed +date still uses the original seconds value. No world/component schema changes. diff --git a/docs/adr/0023-discovery-exploration.md b/docs/adr/0023-discovery-exploration.md new file mode 100644 index 00000000..323fe82d --- /dev/null +++ b/docs/adr/0023-discovery-exploration.md @@ -0,0 +1,23 @@ +# 0023 — Find discoveries through exploration + +- Status: accepted +- Date: 2026-11-15 + +Discovery sites previously showed floating question marks and minimap markers even +under unexplored fog. Those location spoilers undermined the expedition's exploration. + +Unresolved sites now read through their physical models after their ground is explored. +There are no floating question marks and no unresolved-site minimap icons. Completed +player surveys leave coloured minimap records; enemy surveys do not reveal locations. +Scan rings, progress beams, resolved glows, Intel and Survey Log rewards remain. +Orbital campaign previews provide context without revealing the unknown site count. +Survey objectives retain their text and progress, but have no location ring or beacon, +including when an older save carries the former area marker. + +`charted` continues to gate discovery chains and simulation scanning availability. +It no longer means the player receives a free location marker. World visibility comes +from the existing persisted VisionGrid, so no new save schema is required. Audio still +uses current sight rather than the explored-ground memory. + +Proof: unknown/explored/remembered site visibility, player versus enemy map records, +restored vision and scan-feedback tests, followed by real-map/browser qualification. diff --git a/game/ai/commander.gd b/game/ai/commander.gd index 0831fb57..547a1d27 100644 --- a/game/ai/commander.gd +++ b/game/ai/commander.gd @@ -729,12 +729,14 @@ func _explored_nodes() -> Array[ResourceNode]: return found -## Placement rules over what the faction may know: terrain, bounds, its own -## buildings, the enemy buildings it remembers seeing, sites refused lately, and the +## Placement rules over what the faction may know: public terrain and prop obstacles, +## bounds, its own buildings, the enemy buildings it remembers seeing, sites refused +## lately, and the ## resource nodes it has explored. Never the live footprints of unseen buildings; the ## real rules still judge the PlaceBuildingCommand when it runs. func known_placement_rules() -> PlacementRules: var rules: PlacementRules = world.placement_rules() + # Only replace building knowledge; public prop obstacles stay in rules.obstacles. rules.footprints = [] for building: Building in world.buildings_of(faction): rules.footprints.append(building.footprint()) diff --git a/game/assets/branding/farlanding_icon.png b/game/assets/branding/farlanding_icon.png new file mode 100644 index 00000000..02164305 Binary files /dev/null and b/game/assets/branding/farlanding_icon.png differ diff --git a/game/assets/branding/farlanding_icon.png.import b/game/assets/branding/farlanding_icon.png.import new file mode 100644 index 00000000..ed4c3073 --- /dev/null +++ b/game/assets/branding/farlanding_icon.png.import @@ -0,0 +1,40 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://dhu3anoxvpjhl" +path="res://.godot/imported/farlanding_icon.png-d2a66f47fe0fceafab76d4096b880989.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://assets/branding/farlanding_icon.png" +dest_files=["res://.godot/imported/farlanding_icon.png-d2a66f47fe0fceafab76d4096b880989.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/uastc_level=0 +compress/rdo_quality_loss=0.0 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/channel_remap/red=0 +process/channel_remap/green=1 +process/channel_remap/blue=2 +process/channel_remap/alpha=3 +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/game/assets/branding/farlanding_icon.svg b/game/assets/branding/farlanding_icon.svg new file mode 100644 index 00000000..8a1067b8 --- /dev/null +++ b/game/assets/branding/farlanding_icon.svg @@ -0,0 +1,57 @@ + + + + Farlanding + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/game/assets/branding/farlanding_icon.svg.import b/game/assets/branding/farlanding_icon.svg.import new file mode 100644 index 00000000..9afcf8fc --- /dev/null +++ b/game/assets/branding/farlanding_icon.svg.import @@ -0,0 +1,43 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://wnjb1i0pvja" +path="res://.godot/imported/farlanding_icon.svg-b28a06b0f262060d47cf34f1c3bce404.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://assets/branding/farlanding_icon.svg" +dest_files=["res://.godot/imported/farlanding_icon.svg-b28a06b0f262060d47cf34f1c3bce404.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/uastc_level=0 +compress/rdo_quality_loss=0.0 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/channel_remap/red=0 +process/channel_remap/green=1 +process/channel_remap/blue=2 +process/channel_remap/alpha=3 +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 +svg/scale=1.0 +editor/scale_with_editor_scale=false +editor/convert_colors_with_editor_theme=false diff --git a/game/assets/branding/render_icon.sh b/game/assets/branding/render_icon.sh new file mode 100755 index 00000000..3dfd418a --- /dev/null +++ b/game/assets/branding/render_icon.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Rebuild farlanding_icon.png (512 px) and preview sizes from the SVG. +# Needs rsvg-convert (brew install librsvg). +set -e +cd "$(dirname "$0")" +rsvg-convert -w 512 -h 512 farlanding_icon.svg -o farlanding_icon.png diff --git a/game/audio/audio_service.gd b/game/audio/audio_service.gd index a5e5a75f..b578b44b 100644 --- a/game/audio/audio_service.gd +++ b/game/audio/audio_service.gd @@ -1,52 +1,9 @@ -## Autoload `Audio`: the only way sound gets played. Gameplay never calls this for -## its own events — `audio/` listens to `Events` and decides what is heard. The -## public surface below is a contract other systems rely on. -## -## Inside: every SoundEvent under `res://data/sounds/` is registered by id at -## startup. Flat (interface, replies, Advisor) and positional sounds each have a -## pool of players behind a VoiceBudget (priority stealing, per-event caps and -## cooldowns). An AudioListener3D sits above the camera's ground focus point; -## zoom moves it up and reshapes bus levels (AudioMix). Child nodes: the -## 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, 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) -## and the MissionSoundRouter (objectives, briefing and debrief beds, launch, -## storm). The combat and stealth moods both ask for music states; a -## MusicArbiter decides which one plays. Phase 6 adds the StormSound (the dust -## storm's beds, gusts, debris, the world muffle and its release), the -## AmbienceDirector (layered, wandering planet beds and positional details), -## the score's urgency layer while the base is under attack, transition hits -## on the beat (ScoreTransitions) and the pause and menu mix overlays. -## Phase 7 adds the CampaignSoundRouter: aboard the Meridian between landings -## (any campaign screen) the ship score plays in that screen's state, the -## AmbienceDirector plays the ship, and the ship mix applies; a landing hands -## back to the planet's score (`switch_score`: one player, never two scores). -## Phase 8a adds the planets as data (PlanetAudio: score and ambience set per -## planet id, `play_planet`; found by itself from the running mission when a -## mission starts), the TideSound (Thalassa's tide: water beds, rush and pull, -## the turning warnings, the score's tide layer) and score-specific transition -## hits and ending stings (`_` before the generic one). -## Phase 8b adds Emberfall: the EruptionSound (child "Eruption": vent -## build-ups, blasts, the score's pressure layer) and the HoldoutSound (child -## "Holdout": the survival timer's holdout layer, one-minute cue, approaching -## engine and arrival). Both are reached by name; the public surface is full. -## Phase 8c adds Verdance: the CanopySound (child "Canopy": the player's units -## rustling under the crowns, and the ambience's high band closing while the -## camera looks under one, applied here with the storm's muffle). -## Phase 8d adds Hollow Meridian: the CoreSound (child "Core": the score's Core -## layers by charge, and the awakening, the campaign's peak, on its own player; -## the victory sting is left out while it rings), the MachineSound (child -## "Machines": the old engines' spin-up, wind-down and the enemy's seizure, and -## the running engines' hum; BaseLoops leaves those machines alone) and screen -## music (ScreenMusic: a campaign screen with a score of its own, the ending). -## Phase 9 adds subtitles for the Advisor (the AudioEventRouter emits -## `Events.subtitle` as a line starts), the Advisor's and the ambience's own -## volume settings (AudioMix), and the MachineClaimSound (child "Claims": the -## player's workers bringing an engine back, heard rising with the work). +## Autoload Audio: registers SoundEvents and routes gameplay, mission and campaign +## events to sound. Its public API is the playback contract for other systems. +## OneShotPlayback owns flat and positional voice pools, budgets and variation. +## Audio owns the listener and mix, and coordinates world loops, planetary weather, +## discovery, Advisor lines, ambience and music through focused child nodes. +## ShutdownGuard stops all descendant players before they leave the tree. extends Node const EVENTS_DIR: String = "res://data/sounds" @@ -55,8 +12,8 @@ const SHIP_SCORE: String = "res://data/sounds/music/meridian.tres" ## Leaving the ship, the planet's score comes in at the briefing bed's level ## and waits there for the briefing (or the mission) to set it. const LANDING_DIP_DB: float = MissionSoundRouter.BRIEFING_DUCK_DB -const FLAT_VOICES: int = 16 -const POSITIONAL_VOICES: int = 32 +const FLAT_VOICES: int = OneShotPlayback.FLAT_VOICES +const POSITIONAL_VOICES: int = OneShotPlayback.POSITIONAL_VOICES ## Zoom changes smaller than this do not touch the bus volumes. const ZOOM_EPSILON: float = 0.01 ## The music layer that surfaces as discovery sites are resolved. @@ -79,15 +36,9 @@ const RIVAL_INTEL_TYPE: StringName = &"rival_intel" const STING_DIP_DB: float = -6.0 var _events: Dictionary[StringName, SoundEvent] = {} -var _last_variation: Dictionary[StringName, int] = {} -var _flat_budget: VoiceBudget = VoiceBudget.new(FLAT_VOICES) -var _positional_budget: VoiceBudget = VoiceBudget.new(POSITIONAL_VOICES) -var _flat_players: Array[AudioStreamPlayer] = [] -var _positional_players: Array[AudioStreamPlayer3D] = [] -var _rng: RandomNumberGenerator = RandomNumberGenerator.new() +var _one_shots: OneShotPlayback var _listener: AudioListener3D var _listener_active: bool = false -var _focus: Vector3 = Vector3.ZERO var _zoom: float = 0.5 var _applied_zoom: float = -1.0 var _router: AudioEventRouter @@ -132,7 +83,9 @@ var _shade: float = 0.0 func _ready() -> void: process_mode = Node.PROCESS_MODE_ALWAYS _register_events(EVENTS_DIR) - _build_pools() + _one_shots = OneShotPlayback.new() + _one_shots.name = &"OneShots" + add_child(_one_shots) _listener = AudioListener3D.new() _listener.name = &"Listener" add_child(_listener) @@ -311,7 +264,6 @@ func play(event_id: StringName, position: Vector3 = Vector3.INF) -> void: ## Called by the camera every frame. `focus` is the ground point the camera looks ## at; `zoom` runs from 0 (closest) to 1 (furthest) and shapes the mix. func set_listener_focus(focus: Vector3, zoom: float) -> void: - _focus = focus _zoom = clampf(zoom, 0.0, 1.0) _listener.global_position = focus + Vector3.UP * AudioMix.listener_height(_zoom) var camera: Camera3D = get_viewport().get_camera_3d() @@ -320,6 +272,8 @@ func set_listener_focus(focus: Vector3, zoom: float) -> void: if not _listener_active: _listener.make_current() _listener_active = true + _one_shots.focus = focus + _one_shots.listener_active = _listener_active _loops.focus = focus _base_loops.focus = focus _router.focus = focus @@ -342,7 +296,7 @@ func set_music_state(state: StringName) -> void: _music.set_state(state) -# --- Additions beyond the original contract ----------------------------------- +# --- Music, ambience and mix -------------------------------------------------- ## Starts a planet's score at once (and the ambience of the planet whose id @@ -532,12 +486,7 @@ func music() -> MusicDirector: ## suspicion loops) at once; the score, the ambience and the storm go on. For ## leaving a mission mid-sound and for tests that measure the mix. func stop_all_voices() -> void: - for i: int in _flat_players.size(): - _flat_players[i].stop() - _flat_budget.release(i) - for i: int in _positional_players.size(): - _positional_players[i].stop() - _positional_budget.release(i) + _one_shots.stop_all() for node: Node in [_loops, _base_loops, _pulses, _tones, _machines, _claims]: ShutdownGuard._stop_all(node) _ducker = BusDucker.new() @@ -547,7 +496,7 @@ func stop_all_voices() -> void: ## Voices in use (flat + positional), for the debug overlay and tests. func active_voices() -> int: - return _flat_budget.active_count() + _positional_budget.active_count() + return _one_shots.active_voices() # --- Internals ---------------------------------------------------------------- @@ -563,55 +512,7 @@ func _process(_delta: float) -> void: func _start(event_id: StringName, position: Vector3, volume_offset_db: float = 0.0) -> bool: - var event: SoundEvent = _events.get(event_id, null) - if event == null or event.streams.is_empty(): - return false - var positional: bool = event.positional and position.is_finite() - if positional and _listener_active and event.max_distance > 0.0: - if Vector2(position.x - _focus.x, position.z - _focus.z).length() > event.max_distance: - return false - var last: int = _last_variation.get(event_id, -1) - var index: int = SoundEvent.pick_index( - event.streams.size(), last, _rng.randf(), event.avoid_repeat - ) - var stream: AudioStream = event.streams[index] - var pitch: float = 1.0 - if event.pitch_variation > 0.0: - pitch = pow(2.0, _rng.randf_range(-event.pitch_variation, event.pitch_variation) / 12.0) - var budget: VoiceBudget = _positional_budget if positional else _flat_budget - var voice: int = ( - budget - . request( - event_id, - event.priority, - event.max_instances, - event.cooldown, - stream.get_length() / pitch, - _now(), - ) - ) - if voice == VoiceBudget.REJECTED: - return false - _last_variation[event_id] = index - if positional: - var player3d: AudioStreamPlayer3D = _positional_players[voice] - player3d.stop() - player3d.stream = stream - player3d.bus = event.bus - player3d.volume_db = event.volume_db + volume_offset_db - player3d.pitch_scale = pitch - player3d.max_distance = event.max_distance - player3d.global_position = position - player3d.play() - else: - var player: AudioStreamPlayer = _flat_players[voice] - player.stop() - player.stream = stream - player.bus = event.bus - player.volume_db = event.volume_db + volume_offset_db - player.pitch_scale = pitch - player.play() - return true + return _one_shots.start(event_id, get_event(event_id), position, volume_offset_db) func _register_events(dir_path: String) -> void: @@ -631,23 +532,6 @@ func _register_events(dir_path: String) -> void: _events[event.id] = event -func _build_pools() -> void: - for i: int in FLAT_VOICES: - var player: AudioStreamPlayer = AudioStreamPlayer.new() - player.name = "Flat%d" % i - player.finished.connect(_flat_budget.release.bind(i)) - add_child(player) - _flat_players.append(player) - for i: int in POSITIONAL_VOICES: - var player3d: AudioStreamPlayer3D = AudioStreamPlayer3D.new() - player3d.name = "Positional%d" % i - player3d.attenuation_model = AudioStreamPlayer3D.ATTENUATION_INVERSE_DISTANCE - player3d.unit_size = 10.0 - player3d.finished.connect(_positional_budget.release.bind(i)) - add_child(player3d) - _positional_players.append(player3d) - - func _apply_volumes() -> void: _applied_zoom = _zoom var zoom: float = AudioMix.SHIP_ZOOM if _ship else _zoom @@ -788,9 +672,7 @@ func _on_launch() -> void: ## Stops the world's one-shots (the positional pool) and loops; interface, ## Advisor and stings (the flat pool) ring on. func _stop_world_voices() -> void: - for i: int in _positional_players.size(): - _positional_players[i].stop() - _positional_budget.release(i) + _one_shots.stop_world() for node: Node in [_loops, _base_loops, _pulses, _tones]: ShutdownGuard._stop_all(node) diff --git a/game/audio/combat_sound_router.gd b/game/audio/combat_sound_router.gd index e1906164..e08b2092 100644 --- a/game/audio/combat_sound_router.gd +++ b/game/audio/combat_sound_router.gd @@ -152,6 +152,8 @@ func handle_entity_damaged(entity: Node3D, amount: float, attacker: Node3D, now: func handle_entity_died(entity: Node3D, now: float) -> void: + if is_instance_valid(entity) and entity is Building and (entity as Building).is_sold: + return if entity == null or not is_instance_valid(entity): return var at: Vector3 = _position_of(entity) diff --git a/game/audio/one_shot_playback.gd b/game/audio/one_shot_playback.gd new file mode 100644 index 00000000..d3ce30d4 --- /dev/null +++ b/game/audio/one_shot_playback.gd @@ -0,0 +1,118 @@ +class_name OneShotPlayback +extends Node +## Owns one-shot players, allocation, variation history and randomness. +## Audio supplies registered events and the listener's ground focus. Players stay +## below Audio so its last-added ShutdownGuard stops them before tree teardown. + +const FLAT_VOICES: int = 16 +const POSITIONAL_VOICES: int = 32 + +## Distance culling starts only once Audio has activated its listener. +var listener_active: bool = false +var focus: Vector3 = Vector3.ZERO +## Sampled at allocation, after variation and pitch draws, like Audio's clock. +var now: Callable = func() -> float: return Time.get_ticks_msec() / 1000.0 + +var _last_variation: Dictionary[StringName, int] = {} +var _flat_budget: VoiceBudget = VoiceBudget.new(FLAT_VOICES) +var _positional_budget: VoiceBudget = VoiceBudget.new(POSITIONAL_VOICES) +var _flat_players: Array[AudioStreamPlayer] = [] +var _positional_players: Array[AudioStreamPlayer3D] = [] +var _rng: RandomNumberGenerator = RandomNumberGenerator.new() + + +func _ready() -> void: + _build_pools() + + +func start( + event_id: StringName, + event: SoundEvent, + position: Vector3, + volume_offset_db: float = 0.0, +) -> bool: + if event == null or event.streams.is_empty(): + return false + var positional: bool = event.positional and position.is_finite() + if positional and listener_active and event.max_distance > 0.0: + if Vector2(position.x - focus.x, position.z - focus.z).length() > event.max_distance: + return false + var last: int = _last_variation.get(event_id, -1) + var index: int = SoundEvent.pick_index( + event.streams.size(), last, _rng.randf(), event.avoid_repeat + ) + var stream: AudioStream = event.streams[index] + var pitch: float = 1.0 + if event.pitch_variation > 0.0: + pitch = pow(2.0, _rng.randf_range(-event.pitch_variation, event.pitch_variation) / 12.0) + var budget: VoiceBudget = _positional_budget if positional else _flat_budget + var allocated_at: float = now.call() + var voice: int = ( + budget + . request( + event_id, + event.priority, + event.max_instances, + event.cooldown, + stream.get_length() / pitch, + allocated_at, + ) + ) + if voice == VoiceBudget.REJECTED: + return false + _last_variation[event_id] = index + if positional: + var player3d: AudioStreamPlayer3D = _positional_players[voice] + player3d.stop() + player3d.stream = stream + player3d.bus = event.bus + player3d.volume_db = event.volume_db + volume_offset_db + player3d.pitch_scale = pitch + player3d.max_distance = event.max_distance + player3d.global_position = position + player3d.play() + else: + var player: AudioStreamPlayer = _flat_players[voice] + player.stop() + player.stream = stream + player.bus = event.bus + player.volume_db = event.volume_db + volume_offset_db + player.pitch_scale = pitch + player.play() + return true + + +## Stops flat voices first, then the world's positional voices. Releasing a +## voice keeps its event's cooldown and variation history intact. +func stop_all() -> void: + for i: int in _flat_players.size(): + _flat_players[i].stop() + _flat_budget.release(i) + stop_world() + + +func stop_world() -> void: + for i: int in _positional_players.size(): + _positional_players[i].stop() + _positional_budget.release(i) + + +func active_voices() -> int: + return _flat_budget.active_count() + _positional_budget.active_count() + + +func _build_pools() -> void: + for i: int in FLAT_VOICES: + var player: AudioStreamPlayer = AudioStreamPlayer.new() + player.name = "Flat%d" % i + player.finished.connect(_flat_budget.release.bind(i)) + add_child(player) + _flat_players.append(player) + for i: int in POSITIONAL_VOICES: + var player3d: AudioStreamPlayer3D = AudioStreamPlayer3D.new() + player3d.name = "Positional%d" % i + player3d.attenuation_model = AudioStreamPlayer3D.ATTENUATION_INVERSE_DISTANCE + player3d.unit_size = 10.0 + player3d.finished.connect(_positional_budget.release.bind(i)) + add_child(player3d) + _positional_players.append(player3d) diff --git a/game/audio/one_shot_playback.gd.uid b/game/audio/one_shot_playback.gd.uid new file mode 100644 index 00000000..23beda00 --- /dev/null +++ b/game/audio/one_shot_playback.gd.uid @@ -0,0 +1 @@ +uid://blq35b7saptu1 diff --git a/game/core/defs/economy_rules.gd b/game/core/defs/economy_rules.gd index 0a6aa209..f4d9245f 100644 --- a/game/core/defs/economy_rules.gd +++ b/game/core/defs/economy_rules.gd @@ -12,6 +12,11 @@ extends Resource @export_group("Production") ## Share of the cost returned when a queued unit is cancelled. @export_range(0.0, 1.0, 0.05) var cancel_refund: float = 1.0 +@export_group("Selling") +## Share of a completed building's Alloy and Flux cost returned on sale. +@export_range(0.0, 1.0, 0.05) var sell_refund: float = 0.5 +## Cancelling construction returns the full building cost. +@export_range(0.0, 1.0, 0.05) var construction_cancel_refund: float = 1.0 @export_group("Placement") ## Free space kept between building footprints, in metres. @export_range(0.0, 10.0, 0.1, "suffix:m") var building_gap: float = 1.0 diff --git a/game/core/game.gd b/game/core/game.gd index 05069a6c..1f78f441 100644 --- a/game/core/game.gd +++ b/game/core/game.gd @@ -1,6 +1,6 @@ extends Node -## Scene flow (autoload `Game`). Stub: the project boots straight into MAIN_SCENE; -## menus, mission loading and the campaign layer hook in here later. +## Autoload entry point for whole-scene navigation. Main owns the menu, campaign +## and landing transitions within MAIN_SCENE. const MAIN_SCENE: String = "res://main.tscn" diff --git a/game/data/hints/catalog.tres b/game/data/hints/catalog.tres index 41d80d8e..a6e1bd87 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 log entry and sometimes more. Scans stop if the Surveyor leaves." +text = "Explore the terrain to find unusual sites. {command} a site 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/main.gd b/game/main.gd index 63f8a60c..0de40cbb 100644 --- a/game/main.gd +++ b/game/main.gd @@ -30,8 +30,8 @@ extends Node ## Saved landings (ADR 0013): the quicksave and quickload keys (F5 and F9 unless ## rebound) work in a mission, the pause ## menu saves into and loads from any slot, a campaign landing is autosaved as it -## starts, and the title's Continue picks the newest of the campaign autosave and the -## saved landings. A save that cannot be loaded is refused before anything in play +## starts, and the title's Continue resumes the most recently saved unfinished landing. +## A save that cannot be loaded is refused before anything in play ## is touched. One mission map exists at a time; it is taken out of the tree ## before the next one loads, so nothing leaks between landings. Behind the menus a ## backdrop scene plays when it exists: the menu backdrop (an orbiting view of the @@ -52,7 +52,7 @@ const CAMPAIGN: String = "res://data/campaign/kessel_trail.tres" @export var campaign_def: CampaignDef ## The mission map in play, or null. -var map: Node = null +var map: LandingMap = null ## The mission being played or briefed. var current: MissionDef = null ## The running mission of `map`, or null. @@ -90,6 +90,7 @@ var _backdrop_path: String = "" var _screen_before_credits: StringName = &"" ## The route node of the campaign landing briefed or played. var _landing_node: StringName = &"" +var _slot_return_focus: Control var _web_storage: BrowserPersistence var _web_focus_callback: JavaScriptObject @@ -118,6 +119,7 @@ func _ready() -> void: _layer.add_child(_title) _title.new_campaign_pressed.connect(new_campaign) _title.continue_pressed.connect(continue_campaign) + _title.load_pressed.connect(_open_slots.bind(false)) _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()) @@ -170,12 +172,13 @@ func _ready() -> void: _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)) - _pause.load_pressed.connect(func() -> void: _slots.open(false)) + _pause.save_pressed.connect(_open_slots.bind(true)) + _pause.load_pressed.connect(_open_slots.bind(false)) _slots = SaveLoadPanel.new() _slots.name = &"SaveLoad" _layer.add_child(_slots) _slots.slot_chosen.connect(_on_slot_chosen) + _slots.closed.connect(_on_slots_closed) _notice = SaveNotice.new() _notice.name = &"SaveNotice" _layer.add_child(_notice) @@ -390,32 +393,35 @@ func show_briefing(mission: MissionDef) -> void: func start_mission( mission: MissionDef, modifiers: LandingModifiers = null, restore: Dictionary = {} ) -> void: + var instance: Node = ( + mission.map_scene.instantiate() if mission != null and mission.map_scene != null else null + ) + var landing_map: LandingMap = instance as LandingMap + if landing_map == null: + if instance != null: + instance.free() + _report("The mission has no landing map.", true) + return _close_map() _free_backdrop() current = mission _show_only(null) _set_screen(&"") - if mission == null or mission.map_scene == null: - push_error("Main: mission has no map scene") - show_select() - return Events.ui_feedback.emit(&"menu_close") - map = mission.map_scene.instantiate() + map = landing_map GraphicsSettings.prepare(map) - map.set(&"mission", mission) + map.mission = mission if modifiers != null: - map.set(&"modifiers", modifiers) + map.modifiers = modifiers if not restore.is_empty(): - map.set(&"restore_state", restore) + map.restore_state = restore add_child(map) # The flow's screens take input before the map's nodes. move_child(_layer, -1) - var found: Variant = map.get(&"runner") - runner = found if found is Mission else null + runner = map.runner if runner != null: runner.finished.connect(_on_mission_finished) - var found_hud: Variant = map.get(&"hud") - var hud: Hud = found_hud if found_hud is Hud else null + var hud: Hud = map.hud if hud != null: hud.menu_requested.connect(open_pause) hud.survey_log_toggled.connect(func(is_open: bool) -> void: _hints.obscured = is_open) @@ -428,16 +434,14 @@ func start_mission( ## landing to save (none, or it is over) or the file cannot be written. func save_game(slot: StringName) -> bool: var problem: String = "" - var snapshot: Variant = null + var snapshot: Dictionary = {} if map == null or runner == null or current == null: problem = "There is no landing to save." elif runner.result != null: problem = "The landing is over." - elif not map.has_method(&"snapshot"): - problem = "This map cannot be saved." else: - snapshot = map.call(&"snapshot") - if problem == "" and snapshot is Dictionary: + snapshot = map.snapshot() + if problem == "": var landing_data: Dictionary = snapshot var game: SaveGame = SaveGame.capture( current, landing_data, runner.elapsed_seconds(), campaign, _single_difficulty() @@ -528,7 +532,7 @@ func resume() -> void: paused = false _hints.suspended = false _settings.visible = false - _slots.visible = false + _slots.close() _info.visible = false _pause.visible = false _set_map_running(true) @@ -566,12 +570,9 @@ func _land(mission: MissionDef, level: StringName = &"") -> void: start_mission(mission, modifiers) # The landing autosave: a lost landing can be retried from its first moment. if runner != null: - var snapshot: Variant = map.call(&"snapshot") if map.has_method(&"snapshot") else null - if snapshot is Dictionary: - var landing_data: Dictionary = snapshot - var game: SaveGame = SaveGame.capture(mission, landing_data, 0.0, campaign) - if SaveSlots.write(SaveSlots.AUTOSAVE, game) == "": - Events.campaign_saved.emit(SaveSlots.AUTOSAVE) + var game: SaveGame = SaveGame.capture(mission, map.snapshot(), 0.0, campaign) + if SaveSlots.write(SaveSlots.AUTOSAVE, game) == "": + Events.campaign_saved.emit(SaveSlots.AUTOSAVE) ## Back from a briefing, the debrief or the pause menu: the star map in a campaign, @@ -598,14 +599,13 @@ func _on_restart() -> void: func _set_map_running(running: bool) -> void: if runner != null and runner.context != null: runner.context.sim_clock.paused = not running - var found: Variant = map.get(&"camera") if map != null else null - var camera: Node = found if found is Node else null + var camera: RtsCamera = map.camera if map != null else null if camera != null: camera.process_mode = Node.PROCESS_MODE_INHERIT if running else Node.PROCESS_MODE_DISABLED func _on_mission_finished(result: MissionResult) -> void: - var played: Node = map + var played: LandingMap = map # A won mission of the catalog opens the next single mission, also when it was # won as a campaign landing (the campaign plays the same missions). if result.won and current != null and catalog != null and catalog.missions.has(current): @@ -628,6 +628,36 @@ func _on_mission_finished(result: MissionResult) -> void: _debrief.visible = true +func _open_slots(saving: bool) -> void: + _slot_return_focus = get_viewport().gui_get_focus_owner() + _slots.open(saving) + # Mouse input stops at the modal; keyboard focus must also stay above the + # title/pause buttons so Enter and Tab cannot activate the menu underneath. + _title.focus_behavior_recursive = Control.FOCUS_BEHAVIOR_DISABLED + _pause.focus_behavior_recursive = Control.FOCUS_BEHAVIOR_DISABLED + var first: Button = null + for node: Node in _slots.find_children("*", "Button", true, false): + var button: Button = node as Button + if button == null: + continue + button.focus_mode = Control.FOCUS_ALL + button.add_theme_stylebox_override(&"focus", HudStyle.button_style(&"hover")) + if first == null and not button.disabled and button.is_visible_in_tree(): + first = button + if first != null: + first.grab_focus() + + +func _on_slots_closed() -> void: + _title.focus_behavior_recursive = Control.FOCUS_BEHAVIOR_INHERITED + _pause.focus_behavior_recursive = Control.FOCUS_BEHAVIOR_INHERITED + if is_instance_valid(_slot_return_focus) and _slot_return_focus.is_visible_in_tree(): + _slot_return_focus.grab_focus() + elif map == null and screen == &"title": + _title._load.grab_focus() + _slot_return_focus = null + + func _on_slot_chosen(slot: StringName, saving: bool) -> void: if saving: if save_game(slot): @@ -766,11 +796,11 @@ func _free_backdrop() -> void: func _close_map() -> void: + _slots.close() if paused: paused = false _pause.visible = false _settings.visible = false - _slots.visible = false _info.visible = false Events.ui_feedback.emit(&"pause_close") _hints.end_mission() diff --git a/game/missions/mission.gd b/game/missions/mission.gd index c0c17da2..0db8b1b9 100644 --- a/game/missions/mission.gd +++ b/game/missions/mission.gd @@ -481,6 +481,8 @@ func _has_goal() -> bool: func _on_entity_died(entity: Node3D) -> void: + if is_instance_valid(entity) and entity is Building and (entity as Building).is_sold: + return if result != null or not is_instance_valid(entity): return var faction: int = Combat.faction_of(entity) diff --git a/game/missions/objectives/scan_sites.gd b/game/missions/objectives/scan_sites.gd index 379ccd58..906803db 100644 --- a/game/missions/objectives/scan_sites.gd +++ b/game/missions/objectives/scan_sites.gd @@ -4,6 +4,18 @@ extends Objective ## `site_ids`), or any `amount` sites when none are listed. +## Survey objectives describe the task, without giving away the site's location. +func configure(p_def: ObjectiveDef) -> void: + super(p_def) + has_area = false + + +func from_dict(data: Dictionary) -> void: + super(data) + # Old saves may carry the former objective ring; exploration still owns the reveal. + has_area = false + + func _evaluate() -> void: var resolved: int = 0 var needed: int = def.site_ids.size() if not def.site_ids.is_empty() else def.amount diff --git a/game/platform/web_shell.html b/game/platform/web_shell.html index dad0a826..0a459e85 100644 --- a/game/platform/web_shell.html +++ b/game/platform/web_shell.html @@ -5,19 +5,51 @@ $GODOT_PROJECT_NAME $GODOT_HEAD_INCLUDE -

Farlanding

A Concord Survey expedition

Keyboard and mouse required. Saves stay in this browser.

+
+
+

THE CONCORD SURVEY

Farlanding

+

Build a foothold. Follow the unknown.

+ +

+
Launch options + + +

Your saved graphics are used by default. On your first visit, the game starts on High. You can adjust graphics, sound and controls in Settings after launching.

+
+

Keyboard and mouse required.
Saves stay in this browser on this site.

+
+
@@ -130,7 +162,7 @@ event.target.disabled = true; const missing = Engine.getMissingFeatures({ threads:$GODOT_THREADS_ENABLED }); if (missing.length) { - message.textContent = 'Cannot start. Required browser features: ' + missing.join(', ') + '. Serve with tools/serve_web.py.'; + message.textContent = 'This browser cannot start the game. Missing support: ' + missing.join(', ') + '. Try an up-to-date desktop browser.'; return; } checkStorage(); diff --git a/game/presentation/site_visual.gd b/game/presentation/site_visual.gd index 3edfa3d7..2fdc2359 100644 --- a/game/presentation/site_visual.gd +++ b/game/presentation/site_visual.gd @@ -1,34 +1,27 @@ class_name SiteVisual extends Node3D -## A discovery site in the world: something the orbital scan could not resolve. -## Unresolved it carries a floating "?"; while a Surveyor scans it a ring sweeps -## the ground and a column of light rises; resolved it keeps a steady glow in -## the colour of its discovery type. Holds no gameplay state. +## A discovery site reads through its model, without floating location markers. +## A Surveyor scanning it raises a ring and light column; a resolved site keeps +## a steady glow in its discovery colour. Holds no gameplay state. const RING_SHADER: Shader = preload("res://presentation/shaders/scan_ring.gdshader") const UNKNOWN_COLOR := Color(0.35, 0.92, 1.0) -const BOB_HEIGHT := 0.25 -const BOB_SPEED := 1.6 @export var model_scene: PackedScene ## Radius of the scan ring in metres. @export var radius: float = 6.0 -## Height of the "?" above the ground. +## Height of the active scan beam. @export var marker_height: float = 7.0 -var _marker: Label3D var _ring: MeshInstance3D var _column: MeshInstance3D var _glow: OmniLight3D -var _time: float = 0.0 var _color: Color = UNKNOWN_COLOR func _ready() -> void: if model_scene != null: add_child(model_scene.instantiate()) - _marker = _build_marker() - add_child(_marker) _ring = _build_ring() add_child(_ring) _column = _build_column() @@ -42,12 +35,6 @@ func _ready() -> void: set_scan_progress(0.0) -func _process(delta: float) -> void: - _time += delta - if _marker.visible: - _marker.position.y = marker_height + sin(_time * BOB_SPEED) * BOB_HEIGHT - - ## Colour of the discovery type; used once the site is resolved and while scanning. func set_discovery_color(color: Color) -> void: _color = color @@ -64,30 +51,14 @@ func set_scan_progress(progress: float) -> void: _column.scale = Vector3(1.0, maxf(amount, 0.02), 1.0) -## A resolved site drops its "?" and keeps a steady glow. +## A resolved site keeps a steady glow. func set_resolved(resolved: bool) -> void: - _marker.visible = not resolved _glow.light_color = _color _glow.light_energy = 2.2 if resolved else 0.0 if resolved: set_scan_progress(0.0) -func _build_marker() -> Label3D: - var marker := Label3D.new() - marker.name = "Marker" - marker.text = "?" - marker.font_size = 220 - marker.pixel_size = 0.012 - marker.billboard = BaseMaterial3D.BILLBOARD_ENABLED - marker.no_depth_test = true - marker.modulate = UNKNOWN_COLOR - marker.outline_size = 40 - marker.outline_modulate = Color(0.02, 0.08, 0.10, 0.9) - marker.position.y = marker_height - return marker - - func _build_ring() -> MeshInstance3D: var quad := PlaneMesh.new() quad.size = Vector2.ONE * radius * 2.0 diff --git a/game/presentation/vfx/combat_vfx.gd b/game/presentation/vfx/combat_vfx.gd index 832156d9..a0f16c00 100644 --- a/game/presentation/vfx/combat_vfx.gd +++ b/game/presentation/vfx/combat_vfx.gd @@ -98,6 +98,8 @@ func _on_projectile_impacted(weapon: Resource, at: Vector3, victim: Node3D) -> v func _on_entity_died(entity: Node3D) -> void: + if is_instance_valid(entity) and entity is Building and (entity as Building).is_sold: + return if not is_instance_valid(entity) or _hidden(entity): return var size: float = 1.6 diff --git a/game/project.godot b/game/project.godot index 24a80f35..7dc309fd 100644 --- a/game/project.godot +++ b/game/project.godot @@ -13,6 +13,7 @@ config_version=5 config/name="Farlanding" run/main_scene="res://main.tscn" config/features=PackedStringArray("4.7", "Forward Plus") +config/icon="res://assets/branding/farlanding_icon.png" [audio] diff --git a/game/save/save_game.gd b/game/save/save_game.gd index 6e91d4d8..14888352 100644 --- a/game/save/save_game.gd +++ b/game/save/save_game.gd @@ -109,30 +109,64 @@ static func from_dict(data: Dictionary) -> SaveGame: ## missing mission, campaign or world, or any resource it names that this build does ## not have (a missing unit, building or weapon definition). static func check(data: Dictionary) -> String: + if not _containers(data, ["plan", "campaign", "landing"]): + return "The save has malformed containers." + for key: String in ["kind", "mission", "mission_id", "title", "campaign_def", "difficulty"]: + if data.has(key) and not (data[key] is String or data[key] is StringName): + return "The save has a malformed %s." % key + for key: String in ["format", "saved_at"]: + if data.has(key) and not data[key] is int: + return "The save has a malformed %s." % key + if data.has("seconds") and not (data.seconds is int or data.seconds is float): + return "The save has malformed seconds." var version: int = data.get("format", 0) if version > FORMAT_VERSION: return "This save is from a newer version of the game (format %d)." % version if version < 1: return "This is not a Farlanding save." var path: String = data.get("mission", "") - if path == "" or not ResourceLoader.exists(path): + if not _resource_is(path, MissionDef): return "The mission of this save is missing (%s)." % path - var kind_text: String = data.get("kind", "") + var kind_text: String = data.get("kind", String(KIND_MISSION)) + if kind_text not in [String(KIND_MISSION), String(KIND_CAMPAIGN)]: + return "The kind of this save cannot be read." + var plan_data: Dictionary = data.get("plan", {}) + if not _campaign_containers(plan_data, false): + return "The landing plan of this save cannot be read." if kind_text == String(KIND_CAMPAIGN): var campaign_path: String = data.get("campaign_def", "") - var plan_data: Dictionary = data.get("plan", {}) - if campaign_path == "" or not ResourceLoader.exists(campaign_path): + if not _resource_is(campaign_path, CampaignDef): return "The campaign of this save is missing (%s)." % campaign_path + var campaign_data: Dictionary = data.get("campaign", {}) + if not _campaign_containers(campaign_data, true): + return "The campaign state of this save cannot be read." if LandingPlan.from_dict(plan_data) == null: return "The landing plan of this save cannot be read." var landing_data: Dictionary = data.get("landing", {}) + if not _containers(landing_data, ["clock", "world", "mission", "groups"]): + return "The landing in this save has malformed containers." + if not _versions(landing_data, {"clock": SimClock.SAVE_VERSION}): + return "The clock in this save cannot be read." + var groups: Dictionary = landing_data.get("groups", {}) + for value: Variant in groups.values(): + if not value is Array: + return "The control groups in this save cannot be read." + if not _positions(landing_data, ["camera"], true): + return "The camera in this save cannot be read." var world_data: Dictionary = landing_data.get("world", {}) + if not world_data.get("version", 0) is int: + return "The world in this save has a malformed version." var world_version: int = world_data.get("version", 0) if world_version < 1 or world_version > SimWorld.SAVE_VERSION: return "The world in this save cannot be read (version %d)." % world_version var missing: String = _missing_resource(data) if missing != "": return "Something this save needs is missing: %s" % missing + if not _world_containers(world_data): + return "The world in this save has malformed data." + var mission_data: Dictionary = landing_data.get("mission", {}) + if not _mission_containers(mission_data): + return "The mission state in this save has malformed containers." return "" @@ -172,3 +206,317 @@ static func _missing_resource(value: Variant) -> String: if found != "": return found return "" + + +## Validate the containers the restore readers consume, keeping their defaults for +## omitted fields (including older world versions). Unknown metadata is ignored. +static func _containers(data: Dictionary, dictionaries: Array, arrays: Array = []) -> bool: + for key: String in dictionaries: + if data.has(key) and not data[key] is Dictionary: + return false + for key: String in arrays: + if data.has(key) and not data[key] is Array: + return false + return true + + +static func _resource_is(path: Variant, expected: GDScript) -> bool: + if not path is String: + return false + var text: String = path + return text != "" and ResourceLoader.exists(text) and is_instance_of(load(text), expected) + + +static func _positions( + data: Dictionary, keys: Array, allow_empty: bool = false, allow_unset: bool = false +) -> bool: + for key: String in keys: + if not data.has(key): + continue + if not data[key] is String: + return false + if allow_empty and data[key] == "": + continue + var serialized: String = data[key] + var text: String = serialized.strip_edges() + if allow_unset and text == var_to_str(Vector3.INF): + continue + # Check the serialized vector without asking str_to_var to parse broken + # syntax (that would itself emit an engine error during preflight). + if not text.begins_with("Vector3(") or not text.ends_with(")"): + return false + var parts: PackedStringArray = text.substr(8, text.length() - 9).split(",") + if parts.size() != 3: + return false + for part: String in parts: + if not part.strip_edges().is_valid_float() or not is_finite(part.to_float()): + return false + return true + + +static func _campaign_containers(data: Dictionary, state: bool) -> bool: + if not _containers( + data, + ["loadout", "results"] if state else ["loadout"], + ["techs", "discoveries", "opened", "won", "closed"] + ): + return false + if data.has("version") and not data.version is int: + return false + for key: String in ["node", "campaign", "current_node", "difficulty"]: + if data.has(key) and not (data[key] is String or data[key] is StringName): + return false + if data.has("intel") and not data.intel is int: + return false + if state: + var results: Dictionary = data.get("results", {}) + for entry: Variant in results.values(): + if not entry is Dictionary: + return false + return true + + +static func _world_containers(world: Dictionary) -> bool: + if not _containers( + world, + ["economy", "discovery", "vision", "stealth", "combat", "planet", "props"], + ["resource_nodes", "sites", "buildings", "units"] + ): + return false + if not _versions( + world, + { + "economy": Economy.SAVE_VERSION, + "discovery": Discovery.SAVE_VERSION, + "vision": VisionSystem.SAVE_VERSION, + "stealth": StealthSystem.SAVE_VERSION, + "combat": Combat.SAVE_VERSION, + "planet": 1, + "props": 1 + } + ): + return false + if not _world_services(world): + return false + var classes: Dictionary = { + "resource_nodes": ResourceNodeDef, + "sites": DiscoveryDef, + "buildings": BuildingDef, + "units": UnitDef, + } + for collection: String in classes: + for entry: Variant in world.get(collection, []): + if not entry is Dictionary: + return false + var entity_data: Dictionary = entry + var expected: GDScript = classes[collection] + if not _entity_data(entity_data, expected): + return false + var props: Dictionary = world.get("props", {}) + if not _containers(props, [], ["props"]): + return false + for entry: Variant in props.get("props", []): + if not entry is Dictionary: + return false + var prop_data: Dictionary = entry + if not _entity_data(prop_data, PropDef): + return false + return true + + +static func _entity_data(data: Dictionary, expected: GDScript) -> bool: + var maximum: int = { + UnitDef: Unit.SAVE_VERSION, + BuildingDef: Building.SAVE_VERSION, + ResourceNodeDef: ResourceNode.SAVE_VERSION, + DiscoveryDef: DiscoverySite.SAVE_VERSION, + PropDef: Prop.SAVE_VERSION + }[expected] + if not _version(data, maximum): + return false + if not _resource_is(data.get("def", ""), expected) or not _positions(data, ["position"]): + return false + if not _containers( + data, + [ + "locomotion", + "orders", + "handlers", + "health", + "weapon", + "dormancy", + "watcher", + "cloak", + "construction", + "producer", + "flux", + "machine" + ] + ): + return false + if not _versions( + data, + { + "locomotion": Locomotion.SAVE_VERSION, + "orders": UnitOrders.SAVE_VERSION, + "health": Health.SAVE_VERSION, + "weapon": Weapon.SAVE_VERSION, + "dormancy": Dormancy.SAVE_VERSION, + "watcher": Watcher.SAVE_VERSION, + "cloak": Cloak.SAVE_VERSION, + "construction": Construction.SAVE_VERSION, + "producer": Producer.SAVE_VERSION, + "flux": FluxExtractor.SAVE_VERSION, + "machine": Machine.SAVE_VERSION + } + ): + return false + var watcher: Dictionary = data.get("watcher", {}) + if not _positions(watcher, ["last_noticed"]): + return false + var handlers: Dictionary = data.get("handlers", {}) + for handler: Variant in handlers.values(): + if not handler is Dictionary: + return false + var locomotion: Dictionary = data.get("locomotion", {}) + if not _containers(locomotion, ["mover"]) or not _positions(locomotion, ["destination"]): + return false + if not _positions(locomotion, ["post", "wanted"], true, true): + return false + if not _versions(locomotion, {"mover": Mover.SAVE_VERSION}): + return false + var mover: Dictionary = locomotion.get("mover", {}) + if not _positions(mover, ["position"]): + return false + if mover.has("path"): + if not mover.path is String: + return false + var path_text: String = mover.path + if not path_text.begins_with("PackedVector3Array(") or not path_text.ends_with(")"): + return false + var coordinates: String = path_text.substr(19, path_text.length() - 20) + if coordinates != "": + var parts: PackedStringArray = coordinates.split(",") + if parts.size() % 3 != 0: + return false + for part: String in parts: + if not part.strip_edges().is_valid_float() or not is_finite(part.to_float()): + return false + var orders: Dictionary = data.get("orders", {}) + if not _containers(orders, ["current"], ["queue"]): + return false + var queued: Array = orders.get("queue", []) + var all: Array = queued.duplicate() + all.append(orders.get("current", {})) + for order: Variant in all: + if not order is Dictionary: + return false + var order_data: Dictionary = order + if not order_data.is_empty() and not _version(order_data, Order.SAVE_VERSION): + return false + if not _positions(order_data, ["target", "offset", "guard"]): + return false + var producer: Dictionary = data.get("producer", {}) + if not _containers(producer, [], ["queue"]) or not _positions(producer, ["rally_point"]): + return false + for path: Variant in producer.get("queue", []): + if not _resource_is(path, UnitDef): + return false + return true + + +static func _mission_containers(data: Dictionary) -> bool: + if not _containers( + data, ["commander", "guards", "script"], ["warned", "objectives", "triggers"] + ): + return false + for key: String in ["objectives", "triggers"]: + for entry: Variant in data.get(key, []): + if not entry is Dictionary: + return false + var objectives: Array = data.get("objectives", []) + for objective: Dictionary in objectives: + if not _version(objective, Objective.SAVE_VERSION) or not _positions(objective, ["area"]): + return false + var commander: Dictionary = data.get("commander", {}) + if not _positions(commander, ["home", "staging"]): + return false + if not _versions(commander, {"memory": CommanderMemory.SAVE_VERSION}): + return false + return _containers( + commander, + [ + "memory", + "knowledge", + "last_ordered", + "attack", + "defence", + "scout", + "survey", + "retrieval", + "machines" + ], + ["wave_sizes", "refused"] + ) + + +## Nonempty state dictionaries are passed to readers that assert their version. +## Keep each reader's historical range; the outer format stays unchanged. +static func _version(data: Dictionary, maximum: int) -> bool: + var value: Variant = data.get("version", 0) + return value is int and value >= 1 and value <= maximum + + +static func _versions(data: Dictionary, maxima: Dictionary[String, int]) -> bool: + for key: String in maxima: + if not data.has(key): + continue + if not data[key] is Dictionary: + return false + var state: Dictionary = data[key] + if not state.is_empty() and not _version(state, maxima[key]): + return false + return true + + +static func _world_services(world: Dictionary) -> bool: + var economy: Dictionary = world.get("economy", {}) + if not _containers(economy, ["stockpiles"]): + return false + var piles: Dictionary = economy.get("stockpiles", {}) + for entry: Variant in piles.values(): + if not entry is Dictionary: + return false + var pile: Dictionary = entry + if not _version(pile, Stockpile.SAVE_VERSION): + return false + var discovery: Dictionary = world.get("discovery", {}) + if not _containers(discovery, ["codex", "field_options"], ["heal_fields"]): + return false + if not _versions(discovery, {"field_options": FieldOptions.SAVE_VERSION}): + return false + var vision: Dictionary = world.get("vision", {}) + if not _containers(vision, ["grid", "area_reveals"], ["factions"]): + return false + if not _versions(vision, {"grid": VisionGrid.SAVE_VERSION}): + return false + var grid: Dictionary = vision.get("grid", {}) + if not _containers(grid, ["explored"]): + return false + var stealth: Dictionary = world.get("stealth", {}) + if not _containers(stealth, ["levels", "noticed", "positions"], ["guard_factions"]): + return false + var combat: Dictionary = world.get("combat", {}) + if not _containers(combat, [], ["projectiles"]): + return false + for entry: Variant in combat.get("projectiles", []): + if not entry is Dictionary: + return false + var shot: Dictionary = entry + if not _version(shot, Projectile.SAVE_VERSION): + return false + if not _resource_is(shot.get("weapon", ""), WeaponDef): + return false + if not _positions(shot, ["start", "goal"]): + return false + return true diff --git a/game/save/save_slots.gd b/game/save/save_slots.gd index cb351aee..2075b42f 100644 --- a/game/save/save_slots.gd +++ b/game/save/save_slots.gd @@ -21,6 +21,8 @@ const MANUAL: Array[StringName] = [&"manual_1", &"manual_2", &"manual_3"] static var default_dir: String = DIR ## Why the last `read()` or `write()` failed ("" after a success). static var last_error: String = "" +## Tie-breaks writes within a second without changing legacy saved_at dates. +static var _last_write_order: int = 0 ## Every slot, in the order the slot list shows them. @@ -62,7 +64,13 @@ static func write(slot: StringName, game: SaveGame) -> String: var made: Error = DirAccess.make_dir_recursive_absolute(default_dir) if made != OK and not DirAccess.dir_exists_absolute(default_dir): return _fail("Cannot create the save folder (%s)." % error_string(made)) - var payload: String = var_to_str(game.to_dict()) + var data: Dictionary = game.to_dict() + _last_write_order = maxi( + int(Time.get_unix_time_from_system() * 1_000_000), _last_write_order + 1 + ) + # Optional slot metadata; older readers ignore it and older files default to 0. + data["write_order"] = _last_write_order + var payload: String = var_to_str(data) var text: String = ( "%s %d\n%s\n%s" % [MAGIC, SaveGame.FORMAT_VERSION, payload.sha256_text(), payload] ) @@ -142,13 +150,21 @@ static func parse(text: String) -> Dictionary: static func newest() -> Array: var best: Array = [] var best_time: int = -1 + var best_order: int = -1 for slot: StringName in slots(): if not exists(slot): continue - var game: SaveGame = read(slot) - if game != null and game.saved_at > best_time: + var data: Dictionary = read_data(slot) + var game: SaveGame = SaveGame.from_dict(data) if not data.is_empty() else null + var order_value: Variant = data.get("write_order", 0) + var order: int = order_value if order_value is int else 0 + if ( + game != null + and (game.saved_at > best_time or (game.saved_at == best_time and order > best_order)) + ): best = [slot, game] best_time = game.saved_at + best_order = order last_error = "" return best diff --git a/game/sim/entities/building.gd b/game/sim/entities/building.gd index c2478764..689dd14b 100644 --- a/game/sim/entities/building.gd +++ b/game/sim/entities/building.gd @@ -48,10 +48,12 @@ var seen_by_player: bool = true var sabotage_progress: float = 0.0 ## True once sabotaged: it no longer works. Read by audio, UI and presentation. var is_sabotaged: bool = false -## True from the moment its health ran out. +## True once sold; distinct from a combat death for mission accounting. +var is_sold: bool = false +## True from the moment it leaves play (health ran out or sold). var is_dead: bool: get: - return health != null and health.is_dead() + return is_sold or (health != null and health.is_dead()) ## True for an Antecedent machine that is not running (dormant or shut down): it gives ## nothing, and nothing targets it. Read by combat, the AI, UI and presentation. @@ -62,7 +64,7 @@ var is_inert: bool: ## Read by audio (base loops) and the HUD. var is_under_construction: bool: get: - return construction != null and not construction.is_complete() + return not is_dead and construction != null and not construction.is_complete() var is_producing: bool: get: return is_operational() and producer != null and producer.is_busy() @@ -131,7 +133,8 @@ func _ready() -> void: func is_operational() -> bool: return ( - construction != null + not is_dead + and construction != null and construction.is_complete() and not is_sabotaged and (machine == null or machine.is_running()) diff --git a/game/sim/entities/discovery_site.gd b/game/sim/entities/discovery_site.gd index f4e0510e..d552b2ac 100644 --- a/game/sim/entities/discovery_site.gd +++ b/game/sim/entities/discovery_site.gd @@ -1,7 +1,6 @@ class_name DiscoverySite extends Node3D -## A discovery site on the map (PLAN 2.4): first an unresolved signal the orbital scan -## charted (a "?" the player sees even under fog), resolved when a Surveyor has +## A discovery site on the map (PLAN 2.4), found by exploring and resolved when a Surveyor has ## scanned it for its DiscoveryDef's scan time. Neutral: it belongs to no faction. ## Sites in a chain start uncharted (hidden, not scannable) until the site leading to ## them is resolved. Spawned by SimWorld; scanning is driven by Scanner components and @@ -41,10 +40,10 @@ var is_being_scanned: bool: var discovery_type: StringName: get: return def.discovery_type if def != null else &"" -## The player knows a signal is here (it was charted), resolved or not. +## The site is available and its ground has been encountered, resolved or not. var is_signal_known_to_player: bool: get: - return charted + return charted and visible ## Units scanning it now. var _scanners: Array[Unit] = [] diff --git a/game/sim/orders/sell_building_command.gd b/game/sim/orders/sell_building_command.gd new file mode 100644 index 00000000..5be1b9bb --- /dev/null +++ b/game/sim/orders/sell_building_command.gd @@ -0,0 +1,61 @@ +class_name SellBuildingCommand +extends Command +## Selling uses the normal removal cleanup, without damage or a Health.died signal. +## SimWorld unregisters immediately before notifications and a same-tick save. + +const KIND: StringName = &"sell_building" + +## True only when this execution sold the receiver. +var sold: bool = false + + +func _init(p_issuer_faction: int = 0, p_building: Node3D = null) -> void: + var receivers: Array[Node3D] = [] + if p_building != null: + receivers.append(p_building) + super(KIND, p_issuer_faction, receivers) + + +func execute() -> void: + sold = false + if entities.is_empty(): + return + var building: Building = entities[0] as Building + if not can_sell(building, issuer_faction): + return + sold = building.world.sell_building(building, issuer_faction) + + +static func can_sell(building: Building, issuer: int) -> bool: + return ( + is_instance_valid(building) + and building.is_inside_tree() + and not building.is_queued_for_deletion() + and not building.is_dead + and building.faction == issuer + and building.world != null + and building.world.buildings.has(building) + and building.def != null + and building.def.placeable + and building.def.id != &"lander" + and not building.def.machine + and building.machine == null + ) + + +## Total refund, including queued units under the existing cancellation policy. +static func refund_for(building: Building) -> Vector2i: + var rules: EconomyRules = building.world.rules + var share: float = ( + rules.construction_cancel_refund if building.is_under_construction else rules.sell_refund + ) + var result := Vector2i( + floori(building.def.cost_alloy * share), floori(building.def.cost_flux * share) + ) + if building.producer != null: + for unit: UnitDef in building.producer.queue: + result += Vector2i( + floori(unit.cost_alloy * rules.cancel_refund), + floori(unit.cost_flux * rules.cancel_refund) + ) + return result diff --git a/game/sim/orders/sell_building_command.gd.uid b/game/sim/orders/sell_building_command.gd.uid new file mode 100644 index 00000000..0a102d58 --- /dev/null +++ b/game/sim/orders/sell_building_command.gd.uid @@ -0,0 +1 @@ +uid://bu555fp02imkk diff --git a/game/sim/systems/discovery/discovery.gd b/game/sim/systems/discovery/discovery.gd index fa468381..a3141f60 100644 --- a/game/sim/systems/discovery/discovery.gd +++ b/game/sim/systems/discovery/discovery.gd @@ -40,6 +40,7 @@ func setup(p_world: SimWorld, p_player_faction: int) -> void: func add_site(site: DiscoverySite) -> void: sites.append(site) + _refresh_site_visibility(site) site.tree_exiting.connect(func() -> void: sites.erase(site)) @@ -97,6 +98,7 @@ func resolve(site: DiscoverySite, faction: int) -> void: var next: DiscoverySite = site_of(def.leads_to) if next != null and not next.charted: next.chart() + _refresh_site_visibility(next) ## One sim tick: heal fields, field option cooldowns, the player's view of the sites. @@ -109,14 +111,27 @@ func tick(tick_number: int, dt: float) -> void: _tick = tick_number field_options.tick(tick_number) _tick_heal_fields(dt) + refresh_visibility() + + +## Apply restored exploration immediately, including when the sim clock is paused. +func refresh_visibility() -> void: for site: DiscoverySite in sites: - if world.vision == null: - site.is_visible_to_player = site.charted - else: - site.is_visible_to_player = ( - site.charted - and world.vision.grid.is_area_visible(player_faction, site.blocked_area()) - ) + _refresh_site_visibility(site) + + +## Models appear only after their ground has been explored; charted controls chain +## availability, not a free orbital reveal. VisionGrid already persists exploration. +func _refresh_site_visibility(site: DiscoverySite) -> void: + if world.vision == null: + site.is_visible_to_player = site.charted + site.visible = site.charted + return + var grid: VisionGrid = world.vision.grid + site.is_visible_to_player = ( + site.charted and grid.is_area_visible(player_faction, site.blocked_area()) + ) + site.visible = site.charted and grid.is_area_explored(player_faction, site.blocked_area()) func _apply_payoff(site: DiscoverySite, faction: int) -> void: diff --git a/game/sim/systems/economy/placement_rules.gd b/game/sim/systems/economy/placement_rules.gd index ee7aa8d5..cacd3599 100644 --- a/game/sim/systems/economy/placement_rules.gd +++ b/game/sim/systems/economy/placement_rules.gd @@ -25,6 +25,9 @@ const VENT_TOLERANCE: float = 0.5 ## Footprints of every building standing or under construction (world X/Z). var footprints: Array[Rect2] = [] +## Public movement-blocking map props, independent of faction-known buildings. +## Exact footprints: building spacing does not apply to terrain obstacles. +var obstacles: Array[Rect2] = [] var nodes: Array[ResourceNode] = [] ## Area buildings may be placed in (world X/Z). var bounds: Rect2 = Rect2(-1.0e6, -1.0e6, 2.0e6, 2.0e6) @@ -87,6 +90,9 @@ func check(def: BuildingDef, at: Vector3) -> StringName: for other: Rect2 in footprints: if spaced.intersects(other): return BLOCKED + for obstacle: Rect2 in obstacles: + if area.intersects(obstacle): + return UNWALKABLE var vent_reason: StringName = _check_nodes(def, at, area) if vent_reason != OK: return vent_reason diff --git a/game/sim/systems/sim_world.gd b/game/sim/systems/sim_world.gd index f0d9a276..ca24be0e 100644 --- a/game/sim/systems/sim_world.gd +++ b/game/sim/systems/sim_world.gd @@ -1,3 +1,4 @@ +# gdlint: disable=max-public-methods class_name SimWorld extends Node3D ## Owns the entities of one mission — units, buildings, resource nodes and discovery @@ -303,6 +304,9 @@ func placement_rules() -> PlacementRules: placement.bounds = build_bounds for building: Building in buildings: placement.footprints.append(building.footprint()) + for prop: Prop in props: + if prop.def != null and prop.def.blocks_movement and not prop.is_dead: + placement.obstacles.append(prop.footprint()) placement.nodes = resource_nodes.duplicate() for site: DiscoverySite in discovery.sites: if site.def.blocks_movement: @@ -569,6 +573,30 @@ func _on_ground(point: Vector3) -> Vector3: return point +## Removes an owned placeable building through the normal unregistration path. +## All authoritative state, including the refund, is committed before events: a +## synchronous listener may save. The shared removal event clears selection and +## loops; casualty consumers distinguish a sale via Building.is_sold. +func sell_building(building: Building, issuer: int) -> bool: + if not SellBuildingCommand.can_sell(building, issuer) or building.world != self: + return false + var refund: Vector2i = SellBuildingCommand.refund_for(building) + building.is_sold = true + if building.producer != null: + while building.producer.is_busy(): + building.producer.cancel_last() + _on_building_exiting(building) + # The exit callback may run again after listeners have already reclaimed a vent. + building.vent = null + var pile: Stockpile = economy.stockpile(issuer) + pile.add(refund.x, refund.y) + economy.update_power(buildings) + Events.resources_changed.emit(issuer, pile.alloy, pile.flux) + Events.entity_died.emit(building) + building.queue_free() + return true + + ## Health ran out: announce the death, take the entity out of play at once (its ## navmesh cut-out is freed now) and free it after the frame. func _on_entity_killed(_attacker: Node3D, entity: Node3D) -> void: @@ -681,9 +709,25 @@ func to_dict() -> Dictionary: func from_dict(data: Dictionary) -> void: var version: int = data.get("version", 0) assert(version >= 1 and version <= SAVE_VERSION, "Unsupported SimWorld save version") + _restore_economy(data) + _restore_resource_nodes(data) + _restore_sites(data) + _restore_buildings(data) + _restore_discovery(data) + _restore_units(data) + var saved_next: int = _restore_systems(data) + _restore_props(data) + _restore_references(saved_next) + discovery.refresh_visibility() + + +func _restore_economy(data: Dictionary) -> void: var economy_data: Dictionary = data.get("economy", {}) if not economy_data.is_empty(): economy.from_dict(economy_data) + + +func _restore_resource_nodes(data: Dictionary) -> void: var saved_nodes: Array = data.get("resource_nodes", []) for entry: Variant in saved_nodes: var node_data: Dictionary = entry @@ -692,6 +736,9 @@ func from_dict(data: Dictionary) -> void: var node: ResourceNode = spawn_resource_node(node_def, _saved_position(node_data)) _restore_id(node, node.entity_id, node_data) node.from_dict(node_data) + + +func _restore_sites(data: Dictionary) -> void: var saved_sites: Array = data.get("sites", []) for entry: Variant in saved_sites: var site_data: Dictionary = entry @@ -703,6 +750,9 @@ func from_dict(data: Dictionary) -> void: var site: DiscoverySite = spawn_site(site_def, _saved_position(site_data)) _restore_id(site, site.entity_id, site_data) site.from_dict(site_data) + + +func _restore_buildings(data: Dictionary) -> void: var saved_buildings: Array = data.get("buildings", []) for entry: Variant in saved_buildings: var building_data: Dictionary = entry @@ -714,10 +764,16 @@ func from_dict(data: Dictionary) -> void: ) _restore_id(building, building.entity_id, building_data) building.from_dict(building_data) + + +func _restore_discovery(data: Dictionary) -> void: # After the buildings: field options look their definitions up on the Survey Lab. var discovery_data: Dictionary = data.get("discovery", {}) if not discovery_data.is_empty(): discovery.from_dict(discovery_data) + + +func _restore_units(data: Dictionary) -> void: var saved_units: Array = data.get("units", []) for entry: Variant in saved_units: var unit_data: Dictionary = entry @@ -727,6 +783,9 @@ func from_dict(data: Dictionary) -> void: var unit: Unit = spawn_unit(unit_def, faction, Vector3.ZERO) _restore_id(unit, unit.entity_id, unit_data) unit.from_dict(unit_data) + + +func _restore_systems(data: Dictionary) -> int: var saved_next: int = data.get("next_id", _next_id) _next_id = maxi(_next_id, saved_next) var vision_data: Dictionary = data.get("vision", {}) @@ -744,9 +803,16 @@ func from_dict(data: Dictionary) -> void: _apply_conditions(true) # The sea closes the same ground it did, before orders ask for paths. flood.sync() + return saved_next + + +func _restore_props(data: Dictionary) -> void: var props_data: Dictionary = data.get("props", {}) if not props_data.is_empty(): _props_from_dict(props_data) + + +func _restore_references(saved_next: int) -> void: # Restoring handed out (and then replaced) fresh ids: continue from the saved count. var highest: int = saved_next - 1 for id: int in _entities: diff --git a/game/tests/ai/test_commander_sites.gd b/game/tests/ai/test_commander_sites.gd index a9e0fe81..d2683e7d 100644 --- a/game/tests/ai/test_commander_sites.gd +++ b/game/tests/ai/test_commander_sites.gd @@ -117,3 +117,25 @@ func test_with_no_room_by_the_anchor_it_builds_by_another_of_its_buildings() -> var spot: Vector3 = _commander.site_anywhere(_f.forge, Vector3.ZERO) assert_ne(spot, Vector3.INF, "a site by its other building") assert_lt(AiGroup.flat_distance(spot, outpost.position), 70.0) + + +func test_public_props_survive_replacing_building_knowledge_without_fog_cheats() -> void: + _start_commander() + _look() + var open_spot: Vector3 = _commander.find_site(_f.forge, FAR) + assert_ne(open_spot, Vector3.INF) + var wall_def: PropDef = PropDef.new() + wall_def.size = Vector3(2, 3, 8) + var wall: Prop = _f.world.spawn_prop(wall_def, open_spot, 1) + var unseen: Vector3 = FAR + Vector3(25, 0, 0) + _f.building(_f.forge, unseen, AiFixture.ENEMY) + _look() + assert_eq(_commander.knowledge.known_buildings().size(), 0) + var placement: PlacementRules = _commander.known_placement_rules() + assert_true(placement.obstacles.has(wall.footprint())) + assert_eq(placement.check(_f.forge, open_spot), PlacementRules.UNWALKABLE) + assert_eq(placement.check(_f.forge, unseen), PlacementRules.OK, "no unseen building footprint") + assert_eq(_f.world.placement_rules().check(_f.forge, unseen), PlacementRules.BLOCKED) + var alternate: Vector3 = _commander.find_site(_f.forge, FAR) + assert_ne(alternate, Vector3.INF) + assert_false(_f.forge.world_footprint(alternate).intersects(wall.footprint())) diff --git a/game/tests/audio/test_core_sound.gd b/game/tests/audio/test_core_sound.gd index 434723d5..4e696614 100644 --- a/game/tests/audio/test_core_sound.gd +++ b/game/tests/audio/test_core_sound.gd @@ -139,7 +139,7 @@ func _victory_sting_playing() -> bool: var event: SoundEvent = Audio.get_event(id) if event != null: streams.append_array(event.streams) - for child: Node in Audio.get_children(): + for child: Node in Audio.get_node(^"OneShots").get_children(): var player: AudioStreamPlayer = child as AudioStreamPlayer if player != null and player.playing and streams.has(player.stream): return true diff --git a/game/tests/audio/test_final_mix.gd b/game/tests/audio/test_final_mix.gd index 89d2eccd..eb9517a1 100644 --- a/game/tests/audio/test_final_mix.gd +++ b/game/tests/audio/test_final_mix.gd @@ -131,8 +131,8 @@ func before_each() -> void: Audio.ambience()._use_set(AmbienceSet.new()) await wait_process_frames(1) seed(1729) - Audio._rng.seed = 1729 - Audio._last_variation.clear() + (Audio.get_node(^"OneShots") as OneShotPlayback)._rng.seed = 1729 + (Audio.get_node(^"OneShots") as OneShotPlayback)._last_variation.clear() Audio.ambience()._rng.seed = 1729 Audio.music()._rng.seed = 1729 Audio.play_score(load(KESSEL_SCORE) as MusicScore) diff --git a/game/tests/audio/test_one_shot_playback.gd b/game/tests/audio/test_one_shot_playback.gd new file mode 100644 index 00000000..7d0c4644 --- /dev/null +++ b/game/tests/audio/test_one_shot_playback.gd @@ -0,0 +1,118 @@ +extends GutTest +## Playback-boundary checks; the integrated real-mixer suite covers audible output. + +var _playback: OneShotPlayback +var _time: float = 10.0 + + +func before_each() -> void: + _time = 10.0 + _playback = OneShotPlayback.new() + _playback.now = func() -> float: return _time + add_child_autofree(_playback) + + +func after_each() -> void: + _playback.stop_all() + + +func _event(positional: bool = false) -> SoundEvent: + var event: SoundEvent = SoundEvent.new() + event.id = &"fixture" + event.positional = positional + event.volume_db = -8.0 + for i: int in 3: + var stream: AudioStreamWAV = AudioStreamWAV.new() + stream.mix_rate = 44100 + var data: PackedByteArray = PackedByteArray() + data.resize(44100) + stream.data = data + event.streams.append(stream) + return event + + +func test_budget_rejection_consumes_draws_but_keeps_last_successful_variation() -> void: + var event: SoundEvent = _event() + event.pitch_variation = 2.0 + event.cooldown = 0.5 + _playback._rng.seed = 1729 + var expected: RandomNumberGenerator = RandomNumberGenerator.new() + expected.seed = 1729 + var last: int = -1 + for attempt: int in 3: + var index: int = SoundEvent.pick_index(3, last, expected.randf(), true) + var pitch: float = pow(2.0, expected.randf_range(-2.0, 2.0) / 12.0) + var state_at_allocation: int = expected.state + _playback.now = func() -> float: + assert_eq(_playback._rng.state, state_at_allocation, "draws precede clock sampling") + return _time + var started: bool = _playback.start(event.id, event, Vector3.INF, -3.0) + assert_eq(started, attempt != 1, "cooldown rejects only the middle attempt") + assert_eq(_playback._rng.state, expected.state, "rejection consumes both draws") + if started: + last = index + var voice: int = 0 if attempt == 0 else 1 + var player: AudioStreamPlayer = _playback._flat_players[voice] + assert_eq(player.stream, event.streams[index]) + assert_almost_eq(player.pitch_scale, pitch, 0.00001) + assert_eq(player.volume_db, -11.0) + assert_eq(_playback._last_variation[event.id], last) + _time += 0.25 + + +func test_distance_uses_ground_focus_and_culls_before_randomness() -> void: + var event: SoundEvent = _event(true) + event.max_distance = 5.0 + _playback.focus = Vector3(10.0, 100.0, 20.0) + assert_true(_playback.start(event.id, event, Vector3(100.0, 0.0, 100.0))) + _playback.stop_all() + _playback.listener_active = true + var state: int = _playback._rng.state + assert_false(_playback.start(event.id, event, Vector3(16.0, 100.0, 20.0))) + assert_eq(_playback._rng.state, state, "distance rejection takes no random draws") + var position: Vector3 = Vector3(13.0, -100.0, 24.0) + assert_true(_playback.start(event.id, event, position, -2.0), "inclusive horizontal cutoff") + var player: AudioStreamPlayer3D = _playback._positional_players[0] + assert_eq(player.global_position, position) + assert_eq(player.max_distance, 5.0) + assert_eq(player.volume_db, -10.0) + assert_eq(player.attenuation_model, AudioStreamPlayer3D.ATTENUATION_INVERSE_DISTANCE) + assert_eq(player.unit_size, 10.0) + + +func test_flat_fallback_finished_release_and_stop_scopes() -> void: + var event: SoundEvent = _event(true) + assert_eq(_playback._flat_players.size(), 16) + assert_eq(_playback._positional_players.size(), 32) + assert_true(_playback.start(event.id, event, Vector3.INF)) + assert_true(_playback.start(event.id, event, Vector3.ZERO)) + assert_eq(_playback.active_voices(), 2) + _playback.stop_world() + assert_eq(_playback.active_voices(), 1, "world stop leaves flat fallback alone") + assert_true(_playback._flat_players[0].playing) + assert_false(_playback._positional_players[0].playing) + _playback._flat_players[0].finished.emit() + assert_eq(_playback.active_voices(), 0, "flat finished releases allocation") + assert_true(_playback.start(event.id, event, Vector3.ZERO)) + _playback._positional_players[0].finished.emit() + assert_eq(_playback.active_voices(), 0, "positional finished releases allocation") + assert_true(_playback.start(event.id, event, Vector3.INF)) + assert_true(_playback.start(event.id, event, Vector3.ZERO)) + _playback.stop_all() + assert_eq(_playback.active_voices(), 0) + assert_false(_playback._flat_players[0].playing) + assert_false(_playback._positional_players[0].playing) + + +func test_stop_preserves_cooldown_and_invalid_events_take_no_draws() -> void: + var state: int = _playback._rng.state + assert_false(_playback.start(&"missing", null, Vector3.INF)) + assert_false(_playback.start(&"empty", SoundEvent.new(), Vector3.INF)) + assert_eq(_playback._rng.state, state) + var event: SoundEvent = _event() + event.cooldown = 1.0 + assert_true(_playback.start(event.id, event, Vector3.INF)) + _playback.stop_all() + assert_false(_playback.start(event.id, event, Vector3.INF), "stop preserves cooldown") + _time += 1.0 + assert_true(_playback.start(event.id, event, Vector3.INF), "cooldown ends at its boundary") diff --git a/game/tests/audio/test_one_shot_playback.gd.uid b/game/tests/audio/test_one_shot_playback.gd.uid new file mode 100644 index 00000000..927e8d90 --- /dev/null +++ b/game/tests/audio/test_one_shot_playback.gd.uid @@ -0,0 +1 @@ +uid://d3fu1q1mfi60t diff --git a/game/tests/campaign/test_campaign_completion.gd b/game/tests/campaign/test_campaign_completion.gd index 25cd6b8d..be468a32 100644 --- a/game/tests/campaign/test_campaign_completion.gd +++ b/game/tests/campaign/test_campaign_completion.gd @@ -41,7 +41,7 @@ func after_each() -> void: if _main != null: _main.queue_free() _main = null - await wait_frames(2) + await wait_physics_frames(2) for slot: StringName in SaveSlots.slots(): SaveSlots.remove(slot) DirAccess.remove_absolute(ProjectSettings.globalize_path(SAVES)) @@ -166,7 +166,7 @@ func test_the_debrief_leads_to_the_ending_and_back_to_the_title() -> void: main.launch(&"hollow_finale") assert_true(main._briefing.visible, "the finale is briefed") main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(main.runner, "landed on the deck") assert_true(main.runner.script_instance is CoreScript) main.runner.finish(true) diff --git a/game/tests/campaign/test_campaign_flow.gd b/game/tests/campaign/test_campaign_flow.gd index ac2b183e..dcd50042 100644 --- a/game/tests/campaign/test_campaign_flow.gd +++ b/game/tests/campaign/test_campaign_flow.gd @@ -50,7 +50,7 @@ func before_each() -> void: func after_each() -> void: _main.queue_free() - await wait_frames(2) + await wait_physics_frames(2) for slot: StringName in SaveSlots.slots(): SaveSlots.remove(slot) DirAccess.remove_absolute(ProjectSettings.globalize_path(SAVES)) @@ -98,7 +98,7 @@ func _land(node_id: StringName) -> void: _main.launch(node_id) assert_true(_main._briefing.visible, "briefed") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.runner, "landed") diff --git a/game/tests/economy/economy_fixture.gd b/game/tests/economy/economy_fixture.gd index 7411e247..7b97bd66 100644 --- a/game/tests/economy/economy_fixture.gd +++ b/game/tests/economy/economy_fixture.gd @@ -21,7 +21,7 @@ var deposit: ResourceNodeDef var vent: ResourceNodeDef -## Builds the fixture under `parent` (a GutTest, which frees it with autofree). +## Builds nodes under `parent`; the caller must call `dispose()` in teardown. func _init(parent: Node) -> void: rules = EconomyRules.new() rules.start_alloy = 1000 diff --git a/game/tests/economy/test_construction.gd b/game/tests/economy/test_construction.gd index e8ef6fdd..de7bf894 100644 --- a/game/tests/economy/test_construction.gd +++ b/game/tests/economy/test_construction.gd @@ -181,3 +181,60 @@ func test_a_builder_standing_on_its_own_site_steps_out_and_still_builds() -> voi var site: Building = _place(_f.reactor, Vector3.ZERO, [builder]) assert_ne(_ticks_to_finish(site), -1, "the site gets built") assert_false(_inside(site, builder), "from outside the footprint") + + +func test_blocking_props_refuse_construction_without_spending_in_both_rotations() -> void: + var wall_def: PropDef = PropDef.new() + wall_def.size = Vector3(2, 3, 8) + _f.reactor.cost_flux = 7 + for turns: int in [0, 1]: + var wall: Prop = _f.world.spawn_prop(wall_def, Vector3.ZERO, turns) + var blocked: Vector3 = Vector3(0, 0, 6) if turns == 0 else Vector3(6, 0, 0) + var nearby: Vector3 = Vector3(6, 0, 0) if turns == 0 else Vector3(0, 0, 6) + assert_true(_f.world.paths.is_terrain_walkable(Vector3.ZERO), "terrain ignores cuts") + assert_false(_f.world.paths.is_walkable(Vector3.ZERO), "the prop cuts movement") + var builders: Array[Node3D] = _builders(1) + var alloy: int = _f.pile().alloy + var flux: int = _f.pile().flux + var count: int = _f.world.buildings.size() + var command: PlaceBuildingCommand = PlaceBuildingCommand.new( + 0, builders, _f.reactor, blocked + ) + _f.push(command) + _f.tick() + assert_eq(command.refused, PlacementRules.UNWALKABLE) + assert_null(command.placed) + assert_eq(_f.world.buildings.size(), count) + assert_eq(_f.pile().alloy, alloy) + assert_eq(_f.pile().flux, flux) + var site: Building = _place(_f.reactor, nearby, builders) + assert_not_null(site, "a nearby site clear of the turned wall is valid") + assert_eq(_f.pile().alloy, alloy - _f.reactor.cost_alloy) + assert_eq(_f.pile().flux, flux - _f.reactor.cost_flux) + if site != null: + site.free() + wall.free() + + +func test_nonblocking_props_allow_construction() -> void: + var decoration: PropDef = PropDef.new() + decoration.blocks_movement = false + _f.world.spawn_prop(decoration, Vector3.ZERO) + assert_not_null(_place(_f.reactor, Vector3.ZERO, _builders(1))) + + +func test_real_kessel_map_props_refuse_construction() -> void: + var fixture: SaveFixture = SaveFixture.new(self) + var map: LandingMap = await fixture.land(SaveFixture.mission(&"conquest")) + var placement: PlacementRules = map.world.placement_rules() + # A small footprint isolates each boulder's obstacle from neighbouring buildings. + var foundation: BuildingDef = BuildingDef.new() + foundation.footprint = Rect2(-0.1, -0.1, 0.2, 0.2) + var checked: int = 0 + for prop: Prop in map.world.props: + if prop.def.blocks_movement: + assert_true(placement.obstacles.has(prop.footprint())) + assert_eq(placement.check(foundation, prop.position), PlacementRules.UNWALKABLE) + checked += 1 + assert_eq(checked, 8, "the real map's eight boulders") + fixture.dispose(map) diff --git a/game/tests/economy/test_placement_rules.gd b/game/tests/economy/test_placement_rules.gd index 36d4f9e1..3796a755 100644 --- a/game/tests/economy/test_placement_rules.gd +++ b/game/tests/economy/test_placement_rules.gd @@ -101,3 +101,17 @@ func test_every_refusal_has_a_player_facing_reason() -> void: PlacementRules.TOO_STEEP, ]: assert_ne(PlacementRules.describe(reason), "", String(reason)) + + +func test_public_obstacles_use_exact_overlap_even_between_ground_samples() -> void: + # This sliver falls between the 1.5 m ground samples of the reactor. + _rules.obstacles.append(Rect2(-2.4, -0.1, 0.1, 0.2)) + assert_eq(_rules.check(_reactor, Vector3.ZERO), PlacementRules.UNWALKABLE) + _rules.footprints = [] + assert_eq(_rules.check(_reactor, Vector3.ZERO), PlacementRules.UNWALKABLE) + assert_eq(_rules.check(_reactor, Vector3(1, 0, 0)), PlacementRules.OK) + + +func test_public_obstacles_do_not_require_the_building_gap() -> void: + _rules.obstacles.append(Rect2(3.25, -1, 2, 2)) + assert_eq(_rules.check(_reactor, Vector3.ZERO), PlacementRules.OK, "0.25 m is clear") diff --git a/game/tests/economy/test_sell_building.gd b/game/tests/economy/test_sell_building.gd new file mode 100644 index 00000000..82d1f60d --- /dev/null +++ b/game/tests/economy/test_sell_building.gd @@ -0,0 +1,170 @@ +extends GutTest +## All sales enter through the real command queue; no frames are awaited so the +## snapshot checks cover the gap before queue_free is processed. + +var _f: EconomyFixture + + +func before_each() -> void: + _f = EconomyFixture.new(self) + + +func after_each() -> void: + _f.dispose() + + +func _sell(building: Building, issuer: int = 0) -> SellBuildingCommand: + var command := SellBuildingCommand.new(issuer, building) + _f.push(command) + _f.tick() + return command + + +func test_completed_refund_rounds_down_both_resources_and_never_damages() -> void: + _f.reactor.cost_alloy = 151 + _f.reactor.cost_flux = 31 + var building: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + _f.world.economy.pay(0, _f.reactor) + watch_signals(building.health) + watch_signals(Events) + assert_eq(SellBuildingCommand.refund_for(building), Vector2i(75, 15)) + assert_true(_sell(building).sold) + assert_eq(_f.pile().alloy, 924) + assert_eq(_f.pile().flux, 84) + assert_signal_not_emitted(building.health, "died") + assert_signal_not_emitted(Events, "entity_damaged") + assert_true(building.is_sold) + assert_false(building.is_operational()) + + +func test_duplicate_commands_and_reexecution_refund_only_once() -> void: + var building: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + var first := SellBuildingCommand.new(0, building) + var duplicate := SellBuildingCommand.new(0, building) + _f.push(first) + _f.push(duplicate) + assert_eq(_f.pile().alloy, 1000, "pushing does not sell before the tick") + _f.tick() + assert_true(first.sold) + assert_false(duplicate.sold) + first.execute() + assert_eq(_f.pile().alloy, 1075) + assert_false(SellBuildingCommand.can_sell(building, 0)) + + +func test_foreign_lander_nonplaceable_and_machine_buildings_are_protected() -> void: + var foreign: Building = _f.world.spawn_building(_f.reactor, 1, Vector3.ZERO, true) + assert_false(_sell(foreign).sold) + var lander: Building = _f.world.spawn_building(_f.lander, 0, Vector3(20, 0, 0), true) + assert_false(_sell(lander).sold, "even an accidentally placeable Lander is protected") + _f.refinery.placeable = false + var story: Building = _f.world.spawn_building(_f.refinery, 0, Vector3(40, 0, 0), true) + assert_false(_sell(story).sold) + _f.barracks.machine = true + var engine: Building = _f.world.spawn_building(_f.barracks, 0, Vector3(60, 0, 0), true) + assert_false(_sell(engine).sold) + assert_eq(_f.pile().alloy, 1000) + assert_eq(_f.world.buildings.size(), 4) + + +func test_dead_building_cannot_be_sold() -> void: + var building: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + building.health.take(100000) + assert_false(_sell(building).sold) + assert_eq(_f.pile().alloy, 1000) + + +func test_queued_units_are_cancelled_using_existing_refund_policy() -> void: + _f.rules.cancel_refund = 0.5 + _f.ranger.cost_flux = 7 + var building: Building = _f.world.spawn_building(_f.barracks, 0, Vector3.ZERO, true) + _f.push(ProduceCommand.new(0, building, _f.ranger)) + _f.push(ProduceCommand.new(0, building, _f.ranger)) + _f.tick() + assert_eq(SellBuildingCommand.refund_for(building), Vector2i(174, 6)) + _f.push(SellBuildingCommand.new(0, building)) + _f.push(ProduceCommand.new(0, building, _f.ranger)) + _f.tick() + assert_eq(_f.pile().alloy, 1024, "850 + 100 building + twice floor(75 / 2)") + assert_eq(_f.pile().flux, 92) + assert_true(building.producer.queue.is_empty()) + assert_true(_f.world.units.is_empty()) + + +func test_sale_releases_vent_navigation_power_and_snapshot_before_removal_event() -> void: + var vent: ResourceNode = _f.world.spawn_resource_node(_f.vent, Vector3.ZERO) + var building: Building = _f.world.spawn_building(_f.tap, 0, Vector3.ZERO, true) + _f.tick() + assert_eq(vent.tap, building) + assert_true(_f.world.paths.is_blocked(Vector3.ZERO)) + assert_eq(_f.pile().power_used, 3) + var snapshots: Array[Dictionary] = [] + var listener: Callable = func(entity: Node3D) -> void: + if entity == building: + snapshots.append(_f.world.to_dict()) + Events.entity_died.connect(listener) + _sell(building) + Events.entity_died.disconnect(listener) + assert_null(vent.tap) + assert_false(_f.world.paths.is_blocked(Vector3.ZERO)) + assert_eq(_f.pile().power_used, 0) + assert_null(_f.world.entity(building.entity_id)) + assert_false(_f.world.buildings.has(building)) + assert_eq(snapshots.size(), 1) + var during_removal: Array = snapshots[0]["buildings"] + var after_removal: Array = _f.world.to_dict()["buildings"] + assert_true(during_removal.is_empty()) + assert_true(after_removal.is_empty()) + var replacement: Building = _f.world.spawn_building(_f.tap, 0, Vector3.ZERO, true) + assert_eq(vent.tap, replacement, "the vent can be reclaimed immediately") + + +func test_construction_cancellation_returns_full_cost_and_releases_builders() -> void: + _f.reactor.cost_flux = 21 + var builder: Unit = _f.world.spawn_unit(_f.fabricator, 0, Vector3(0, 0, 8)) + var place := PlaceBuildingCommand.new(0, [builder] as Array[Node3D], _f.reactor, Vector3.ZERO) + _f.push(place) + _f.tick() + var site: Building = place.placed + assert_not_null(site) + assert_eq(_f.pile().alloy, 850) + assert_eq(_f.pile().flux, 79) + assert_true(site.is_under_construction) + assert_eq(SellBuildingCommand.refund_for(site), Vector2i(150, 21)) + _sell(site) + assert_eq(_f.pile().alloy, 1000) + assert_eq(_f.pile().flux, 100) + assert_false(_f.world.paths.is_blocked(Vector3.ZERO)) + assert_true(builder.orders.is_idle()) + + +func test_selling_power_source_updates_power_immediately() -> void: + var reactor: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + _f.tick() + assert_eq(_f.pile().power_produced, 15) + _sell(reactor) + assert_eq(_f.pile().power_produced, 0) + + +func test_refund_and_unregistration_precede_resource_and_power_notifications() -> void: + var building: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + _f.tick() + var snapshots: Array[Dictionary] = [] + var listener: Callable = func(_faction: int, _a: int, _b: int) -> void: + snapshots.append(_f.world.to_dict()) + Events.resources_changed.connect(listener) + Events.power_changed.connect(listener) + _sell(building) + Events.resources_changed.disconnect(listener) + Events.power_changed.disconnect(listener) + assert_eq(snapshots.size(), 2) + for snapshot: Dictionary in snapshots: + var buildings: Array = snapshot["buildings"] + var economy: Dictionary = snapshot["economy"] + var stockpiles: Dictionary = economy["stockpiles"] + var pile: Dictionary = stockpiles["0"] + assert_true(buildings.is_empty()) + var alloy: int = pile["alloy"] + var power: int = pile["power_produced"] + assert_eq(alloy, 1075) + assert_eq(power, 0) diff --git a/game/tests/economy/test_sell_building.gd.uid b/game/tests/economy/test_sell_building.gd.uid new file mode 100644 index 00000000..107b7537 --- /dev/null +++ b/game/tests/economy/test_sell_building.gd.uid @@ -0,0 +1 @@ +uid://du73w78qsy1as diff --git a/game/tests/economy/test_sell_building_consumers.gd b/game/tests/economy/test_sell_building_consumers.gd new file mode 100644 index 00000000..2fac0ad4 --- /dev/null +++ b/game/tests/economy/test_sell_building_consumers.gd @@ -0,0 +1,39 @@ +extends GutTest +## The shared removal notification must not turn a sale into a combat casualty. + + +class VfxSpy: + extends CombatVfx + var explosions: int = 0 + + func explosion(_at: Vector3, _radius: float) -> void: + explosions += 1 + + +func test_sold_buildings_do_not_change_mission_casualties_or_objectives() -> void: + var mission := Mission.new() + autofree(mission) + var building := Building.new() + autofree(building) + building.is_sold = true + building.faction = 0 + mission._on_entity_died(building) + building.faction = 1 + mission._on_entity_died(building) + assert_eq(mission.buildings_lost, 0) + assert_eq(mission.enemies_destroyed, 0) + + +func test_sold_buildings_do_not_explode_or_enter_combat_audio() -> void: + var building := Building.new() + autofree(building) + building.is_sold = true + var vfx := VfxSpy.new() + autofree(vfx) + vfx._on_entity_died(building) + assert_eq(vfx.explosions, 0) + # The router has no callbacks configured: any combat handling would fail. + var router := CombatSoundRouter.new() + autofree(router) + router.handle_entity_died(building, 0.0) + assert_eq(router.mood.state, MusicMood.EXPLORE) diff --git a/game/tests/economy/test_sell_building_consumers.gd.uid b/game/tests/economy/test_sell_building_consumers.gd.uid new file mode 100644 index 00000000..aab62938 --- /dev/null +++ b/game/tests/economy/test_sell_building_consumers.gd.uid @@ -0,0 +1 @@ +uid://c307i31xtvt2h diff --git a/game/tests/maps/test_verdance_map.gd b/game/tests/maps/test_verdance_map.gd index a12faf04..02a58ad8 100644 --- a/game/tests/maps/test_verdance_map.gd +++ b/game/tests/maps/test_verdance_map.gd @@ -54,6 +54,7 @@ const STREAM: PackedVector3Array = [ Vector3(-92, 0, -66), Vector3(-52, 0, -58), Vector3(30, 0, 38), Vector3(92, 0, 66) ] +var _canopy_fixture: EconomyFixture var _f: SaveFixture var _maps: Array[LandingMap] = [] @@ -64,6 +65,9 @@ func before_each() -> void: func after_each() -> void: + if _canopy_fixture != null: + _canopy_fixture.dispose() + _canopy_fixture = null for map: LandingMap in _maps: _f.dispose(map) @@ -142,11 +146,11 @@ func test_flyers_ignore_the_navmesh() -> void: func _canopy_for(map_def: MapDef) -> CanopySystem: - var fixture: EconomyFixture = EconomyFixture.new(self) - fixture.world.canopy_zones = map_def.canopy_zones + _canopy_fixture = EconomyFixture.new(self) + _canopy_fixture.world.canopy_zones = map_def.canopy_zones var rule: CanopyRule = CanopyRule.new() rule.system = CanopySystem - var canopy: CanopySystem = PlanetRuleSystem.start(fixture.world, rule) as CanopySystem + var canopy: CanopySystem = PlanetRuleSystem.start(_canopy_fixture.world, rule) as CanopySystem return canopy diff --git a/game/tests/missions/test_pause_flow.gd b/game/tests/missions/test_pause_flow.gd index 63545cdf..f356a4c3 100644 --- a/game/tests/missions/test_pause_flow.gd +++ b/game/tests/missions/test_pause_flow.gd @@ -28,7 +28,7 @@ func before_each() -> void: func after_each() -> void: _main.queue_free() - await wait_frames(2) + await wait_physics_frames(2) for slot: StringName in SaveSlots.slots(): SaveSlots.remove(slot) DirAccess.remove_absolute(ProjectSettings.globalize_path(SAVES)) @@ -49,7 +49,7 @@ func _escape() -> void: func test_pause_stops_the_sim_and_resume_lets_it_run() -> void: var catalog: MissionCatalog = _main.catalog _main.start_mission(catalog.missions[2]) - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.runner) _escape() assert_true(_main.paused, "Esc pauses") @@ -72,11 +72,11 @@ func test_pause_stops_the_sim_and_resume_lets_it_run() -> void: func test_restart_and_quit() -> void: var catalog: MissionCatalog = _main.catalog _main.start_mission(catalog.missions[2]) - await wait_frames(2) + await wait_physics_frames(2) var first: Node = _main.map _main.open_pause() _main._on_restart() - await wait_frames(2) + await wait_physics_frames(2) assert_ne(_main.map, first, "a fresh landing") assert_false(_main.paused) _main.open_pause() @@ -96,7 +96,7 @@ func test_settings_from_the_mission_select() -> void: func test_the_hud_menu_button_opens_the_pause_menu() -> void: var catalog: MissionCatalog = _main.catalog _main.start_mission(catalog.missions[0]) - await wait_frames(2) + await wait_physics_frames(2) var hud: Hud = _main.map.get(&"hud") hud.request_menu() assert_true(_main.paused) @@ -105,7 +105,7 @@ func test_the_hud_menu_button_opens_the_pause_menu() -> void: func test_pause_cannot_reopen_a_completed_mission_under_the_debrief() -> void: _main.start_mission(_main.catalog.missions[2]) - await wait_frames(3) + await wait_physics_frames(3) _main.runner.finish(false) await wait_seconds(Main.DEBRIEF_DELAY + 0.1) assert_true(_main._debrief.visible) diff --git a/game/tests/save/test_save_flow.gd b/game/tests/save/test_save_flow.gd index 31959571..ef4d0d1c 100644 --- a/game/tests/save/test_save_flow.gd +++ b/game/tests/save/test_save_flow.gd @@ -2,8 +2,8 @@ extends GutTest ## Saving and loading through the game's flow (ADR 0013): F5 quicksaves and F9 ## quickloads a mission, the pause menu's Save and Load use the slot screen, a ## campaign landing autosaves as it starts and loads back into its campaign, and -## Continue on the title picks the newest of the campaign autosave and the saved -## landings. A missing, damaged, newer or incomplete save is refused with a message +## Continue on the title resumes the most recently saved unfinished landing. +## A missing, damaged, newer or incomplete save is refused with a message ## and leaves the game in play as it was. const SAVES: String = "user://test_save_flow_saves/" @@ -43,7 +43,7 @@ func before_each() -> void: func after_each() -> void: _main.queue_free() - await wait_frames(2) + await wait_physics_frames(2) Events.ui_feedback.disconnect(_on_feedback) Events.campaign_saved.disconnect(_on_saved) Events.campaign_loaded.disconnect(_on_loaded) @@ -85,7 +85,7 @@ func _key(code: Key) -> void: func _start(id: StringName) -> void: _main.start_mission(SaveFixture.mission(id)) - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.runner, "landed") @@ -125,7 +125,7 @@ func test_only_successful_browser_saves_emit_durable_confirmation() -> void: func test_f5_quicksaves_and_f9_quickloads() -> void: await _start(&"conquest") - await wait_frames(20) + await wait_physics_frames(20) var hauler: Unit = SaveFixture.unit_of(_world(), 0, &"concord_hauler") var hauler_id: int = hauler.entity_id var saved_at: Vector3 = hauler.sim_position() @@ -138,9 +138,9 @@ func test_f5_quicksaves_and_f9_quickloads() -> void: assert_eq(_saved_slots, [SaveSlots.QUICKSAVE] as Array[StringName]) var first_map: Node = _main.map _world().economy.add(0, 500, 0) - await wait_frames(20) + await wait_physics_frames(20) _key(KEY_F9) - await wait_frames(3) + await wait_physics_frames(3) assert_ne(_main.map, first_map, "a fresh map") assert_true(_feedback.has(&"load_done")) assert_eq(_loaded_slots, [SaveSlots.QUICKSAVE] as Array[StringName]) @@ -171,7 +171,7 @@ func test_the_pause_menu_saves_and_loads_through_the_slot_screen() -> void: assert_true(_main._slots._buttons[SaveSlots.QUICKSAVE].disabled, "nothing to load there") var first_map: Node = _main.map _main._slots._buttons[SaveSlots.MANUAL[1]].pressed.emit() - await wait_frames(3) + await wait_physics_frames(3) assert_ne(_main.map, first_map, "loaded") assert_false(_main.paused, "and running") assert_false(_main._slots.visible) @@ -183,7 +183,7 @@ func test_a_campaign_landing_autosaves_and_loads_into_its_campaign() -> void: _main.campaign.state.intel = 77 _main.launch(&"kessel_proving") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) assert_true(SaveSlots.exists(SaveSlots.AUTOSAVE), "the landing autosaved") var game: SaveGame = SaveSlots.read(SaveSlots.AUTOSAVE) assert_eq(game.kind, SaveGame.KIND_CAMPAIGN) @@ -192,7 +192,7 @@ func test_a_campaign_landing_autosaves_and_loads_into_its_campaign() -> void: _main.show_title() assert_null(_main.campaign) assert_true(_main.load_game(SaveSlots.AUTOSAVE)) - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.campaign, "back in the campaign") assert_eq(_main.campaign.state.intel, 77, "as it was when the landing began") assert_not_null(_main.campaign.landing, "with the landing in play") @@ -205,13 +205,13 @@ func test_loading_a_landing_puts_the_campaign_file_back_too() -> void: _main.campaign.state.intel = 77 _main.launch(&"kessel_proving") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) assert_true(_main.save_game(SaveSlots.MANUAL[0])) # Later in the same campaign: more Intel, written to the campaign file. _main.campaign.state.intel = 300 _main.campaign.save() assert_true(_main.load_game(SaveSlots.MANUAL[0])) - await wait_frames(3) + await wait_physics_frames(3) var on_disk: CampaignSession = CampaignSession.new(_main.campaign_def) assert_true(on_disk.load_quietly()) assert_eq(on_disk.state.intel, 77, "memory and the campaign file are one timeline") @@ -222,7 +222,7 @@ func test_a_resolved_landing_drops_its_quicksave_and_autosave() -> void: _main.new_campaign() _main.launch(&"kessel_proving") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) assert_true(_main.save_game(SaveSlots.QUICKSAVE)) assert_true(_main.save_game(SaveSlots.MANUAL[0])) _main.runner.finish(true) @@ -232,7 +232,7 @@ func test_a_resolved_landing_drops_its_quicksave_and_autosave() -> void: # The manual save is from the same second as the result: Continue takes the result. _main.show_title() _main._title.continue_pressed.emit() - await wait_frames(2) + await wait_physics_frames(2) assert_null(_main.map, "the star map, not the landing already won") assert_eq(_main.campaign.state.won, [&"kessel_proving"] as Array[StringName]) @@ -254,11 +254,11 @@ func test_continue_picks_the_newest_of_campaign_and_landing() -> void: _main.new_campaign() _main.launch(&"kessel_proving") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) _main.show_title() assert_true(_main._title._continue.visible) _main._title.continue_pressed.emit() - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.map, "the landing autosave is newer: back into the mission") assert_not_null(_main.campaign) _main.show_title() @@ -267,7 +267,7 @@ func test_continue_picks_the_newest_of_campaign_and_landing() -> void: data["saved_at"] = 1000 _write_raw(SaveSlots.AUTOSAVE, var_to_str(data)) _main._title.continue_pressed.emit() - await wait_frames(2) + await wait_physics_frames(2) assert_null(_main.map, "the star map, not the old landing") assert_true(_main._star_map.visible) @@ -276,14 +276,14 @@ func test_continue_falls_back_to_the_campaign_when_the_landing_cannot_load() -> _main.new_campaign() _main.launch(&"kessel_proving") _main._briefing._on_start() - await wait_frames(3) + await wait_physics_frames(3) _main.show_title() # The newest save names a campaign this build cannot read. var data: Dictionary = SaveSlots.read_data(SaveSlots.AUTOSAVE) data["campaign"] = {"version": 9999} _write_raw(SaveSlots.AUTOSAVE, var_to_str(data)) _main._title.continue_pressed.emit() - await wait_frames(2) + await wait_physics_frames(2) assert_null(_main.map, "no landing") assert_not_null(_main.campaign, "the campaign itself still continues") assert_true(_main._star_map.visible) @@ -295,7 +295,7 @@ func test_single_missions_continue_too() -> void: _main.show_title() assert_true(_main._title._continue.visible, "a saved landing can be continued") _main._title.continue_pressed.emit() - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(_main.map) assert_null(_main.campaign, "a single mission") @@ -370,6 +370,46 @@ func test_a_save_naming_a_missing_definition_is_refused() -> void: assert_string_contains(SaveGame.check(data), "mission") +func test_malformed_loads_preserve_the_existing_map_runner_and_pause_state() -> void: + await _start(&"conquest") + assert_true(_main.save_game(SaveSlots.MANUAL[0])) + var original: Dictionary = SaveSlots.read_data(SaveSlots.MANUAL[0]) + var map: LandingMap = _main.map + var runner: Mission = _main.runner + _main.open_pause() + var cases: Array = [ + [["landing", "world", "units"], {}], + [["landing", "world", "units"], [null]], + [["landing", "world", "units", 0, "def"], original.mission], + [["landing", "world", "units", 0, "locomotion"], []], + [["landing", "world", "units", 0, "locomotion", "mover"], []], + [["landing", "world", "units", 0, "locomotion", "mover", "position"], "42"], + [["landing", "world", "units", 0, "orders", "queue"], [null]], + [["landing", "world", "units", 0, "health", "version"], Health.SAVE_VERSION + 1], + [["landing", "world", "buildings", 0, "def"], original.mission], + [["landing", "mission", "objectives"], [null]], + [["landing", "world", "units", 0, "watcher"], {"version": 1, "last_noticed": "42"}], + [["landing", "mission", "commander", "home"], "42"], + [["landing", "mission", "commander", "staging"], "42"], + ] + for broken: Array in cases: + var data: Dictionary = original.duplicate(true) + var keys: Array = broken[0] + var container: Variant = data + for i: int in keys.size() - 1: + container = container[keys[i]] + container[keys.back()] = broken[1] + _write_raw(SaveSlots.MANUAL[0], var_to_str(data)) + assert_false(_main.load_game(SaveSlots.MANUAL[0]), str(keys)) + _expect_untouched(map) + assert_eq(_main.runner, runner, "the same running mission survives") + assert_true(map.is_inside_tree()) + assert_false(map.is_queued_for_deletion()) + assert_true(_main.paused, "the pause menu stays open") + assert_true(runner.context.sim_clock.paused) + assert_true(_loaded_slots.is_empty(), "no successful load event is emitted") + + ## Writes `payload` into `slot` with a valid header (to test what is inside). func _write_raw(slot: StringName, payload: String) -> void: DirAccess.make_dir_recursive_absolute(SAVES) diff --git a/game/tests/save/test_save_menu_flow.gd b/game/tests/save/test_save_menu_flow.gd new file mode 100644 index 00000000..3ce203ca --- /dev/null +++ b/game/tests/save/test_save_menu_flow.gd @@ -0,0 +1,184 @@ +extends GutTest +## The title's explicit Load game route shares the existing pause slot modal. + +const SAVES: String = "user://test_save_menu_flow/" +const SETTINGS: String = "user://test_save_menu_flow_settings.cfg" + +var _main: Main +var _saved_dir: String +var _saved_settings: String +var _saved_seen: PackedStringArray + + +func before_each() -> void: + _saved_dir = SaveSlots.default_dir + _saved_settings = Settings.path + _saved_seen = Settings.hints_seen + SaveSlots.default_dir = SAVES + Settings.path = SETTINGS + _main = (load("res://main.tscn") as PackedScene).instantiate() as Main + add_child(_main) + + +func after_each() -> void: + _main.queue_free() + await wait_physics_frames(2) + for slot: StringName in SaveSlots.slots(): + SaveSlots.remove(slot) + DirAccess.remove_absolute(ProjectSettings.globalize_path(SAVES)) + DirAccess.remove_absolute(ProjectSettings.globalize_path(SETTINGS)) + SaveSlots.default_dir = _saved_dir + Settings.path = _saved_settings + Settings.hints_seen = _saved_seen + + +func test_load_game_is_available_on_the_initial_title_without_any_saves() -> void: + assert_true(_main._title._load.is_visible_in_tree()) + assert_false(_main._title._load.disabled) + assert_eq(_main._title._load.text, "LOAD GAME") + _main._title._load.pressed.emit() + assert_true(_main._slots.visible) + assert_false(_main._slots.saving) + assert_eq(_main._slots._heading.text, "Load") + assert_null(_main.map) + assert_eq(_main.screen, &"title") + assert_true(_main._title.visible) + for button: Button in _main._slots._buttons.values(): + assert_true(button.disabled, "empty slots cannot be loaded") + + +func test_slot_modal_keeps_keyboard_focus_above_the_title_and_back_returns_it() -> void: + _main._title._load.grab_focus() + _main._title._load.pressed.emit() + assert_eq(_main._title.focus_behavior_recursive, Control.FOCUS_BEHAVIOR_DISABLED) + var focused: Control = _main.get_viewport().gui_get_focus_owner() + assert_not_null(focused) + assert_true(_main._slots.is_ancestor_of(focused)) + assert_true(_main._slots.is_ancestor_of(focused.find_next_valid_focus())) + var back: Button = focused as Button + assert_string_contains(back.text, "BACK") + back.pressed.emit() + assert_false(_main._slots.visible) + assert_eq(_main._title.focus_behavior_recursive, Control.FOCUS_BEHAVIOR_INHERITED) + assert_eq(_main.get_viewport().gui_get_focus_owner(), _main._title._load) + assert_null(_main.map) + assert_null(_main.runner) + assert_eq(_main.screen, &"title") + + +func test_escape_from_title_load_returns_to_title_without_starting_a_mission() -> void: + _main._title._load.pressed.emit() + var key: InputEventKey = InputEventKey.new() + key.keycode = KEY_ESCAPE + key.pressed = true + _main._slots._unhandled_input(key) + assert_false(_main._slots.visible) + assert_true(_main._title.is_visible_in_tree()) + assert_null(_main.map) + assert_null(_main.runner) + + +func test_title_load_enters_the_restored_mission_and_hides_the_menu() -> void: + _main.start_mission(SaveFixture.mission(&"conquest")) + await wait_physics_frames(3) + _main.runner.world.economy.add(0, 123, 0) + var alloy: int = _main.runner.world.economy.stockpile(0).alloy + assert_true(_main.save_game(SaveSlots.MANUAL[0])) + _main.show_title() + assert_null(_main.map) + _main._title._load.pressed.emit() + var slot: Button = _main._slots._buttons[SaveSlots.MANUAL[0]] + assert_false(slot.disabled) + slot.pressed.emit() + assert_not_null(_main.map) + assert_not_null(_main.runner) + assert_eq(_main.runner.world.economy.stockpile(0).alloy, alloy) + assert_false(_main._title.visible) + assert_false(_main._slots.visible) + assert_eq(_main.screen, &"") + assert_false(_main.paused) + assert_true(_main.map.is_inside_tree()) + + +func test_pause_save_load_keeps_the_modal_and_restores_the_pause_menu() -> void: + _main.start_mission(SaveFixture.mission(&"conquest")) + await wait_physics_frames(3) + _main.open_pause() + _main._pause.save_pressed.emit() + assert_true(_main._slots.visible) + assert_true(_main._slots.saving) + assert_true(_main.paused) + assert_eq(_main._pause.focus_behavior_recursive, Control.FOCUS_BEHAVIOR_DISABLED) + _main._slots.close() + assert_true(_main._pause.visible) + assert_true(_main.paused) + assert_eq(_main._pause.focus_behavior_recursive, Control.FOCUS_BEHAVIOR_INHERITED) + _main._pause.load_pressed.emit() + assert_true(_main._slots.visible) + assert_false(_main._slots.saving) + + +func test_starting_a_scene_without_a_landing_map_preserves_the_existing_map() -> void: + _main.start_mission(SaveFixture.mission(&"conquest")) + await wait_physics_frames(3) + var map: LandingMap = _main.map + var runner: Mission = _main.runner + var root: Node = Node.new() + var scene: PackedScene = PackedScene.new() + assert_eq(scene.pack(root), OK) + root.free() + var mission: MissionDef = MissionDef.new() + mission.map_scene = scene + _main.start_mission(mission) + assert_eq(_main.map, map) + assert_eq(_main.runner, runner) + assert_false(map.is_queued_for_deletion()) + assert_true(_main._message_failed) + + +func test_keyboard_activation_opens_load_and_escape_closes_only_the_modal() -> void: + _main._title._load.grab_focus() + var accept: InputEventAction = InputEventAction.new() + accept.action = &"ui_accept" + accept.pressed = true + Input.parse_input_event(accept) + await wait_physics_frames(2) + accept.pressed = false + Input.parse_input_event(accept) + await wait_physics_frames(2) + assert_true(_main._slots.visible) + assert_null(_main.map) + var escape: InputEventKey = InputEventKey.new() + escape.keycode = KEY_ESCAPE + escape.pressed = true + Input.parse_input_event(escape) + await wait_physics_frames(2) + escape.pressed = false + Input.parse_input_event(escape) + assert_false(_main._slots.visible) + assert_true(_main._title.visible) + assert_null(_main.map) + assert_eq(_main.screen, &"title") + + +func test_latest_written_slot_wins_within_the_same_second() -> void: + _main.start_mission(SaveFixture.mission(&"conquest")) + await wait_physics_frames(3) + var game: SaveGame = SaveGame.capture(_main.current, _main.map.snapshot(), 0.0, null) + assert_eq(SaveSlots.write(SaveSlots.QUICKSAVE, game), "") + assert_eq(SaveSlots.write(SaveSlots.MANUAL[0], game), "") + var newest: StringName = SaveSlots.newest()[0] + assert_eq(newest, SaveSlots.MANUAL[0]) + assert_eq(SaveSlots.write(SaveSlots.MANUAL[2], game), "") + assert_eq(SaveSlots.write(SaveSlots.MANUAL[0], game), "") + newest = SaveSlots.newest()[0] + assert_eq(newest, SaveSlots.MANUAL[0]) + + +func test_load_game_sits_directly_below_single_missions() -> void: + var buttons: Array[Node] = _main._title._menu.get_children() + var index: int = buttons.find(_main._title._load) + assert_gt(index, 0) + var previous: Button = buttons[index - 1] as Button + assert_not_null(previous) + assert_eq(previous.text, "SINGLE MISSIONS") diff --git a/game/tests/save/test_save_menu_flow.gd.uid b/game/tests/save/test_save_menu_flow.gd.uid new file mode 100644 index 00000000..fca7f4e0 --- /dev/null +++ b/game/tests/save/test_save_menu_flow.gd.uid @@ -0,0 +1 @@ +uid://dgmjqqdbrcry2 diff --git a/game/tests/save/test_save_validation.gd b/game/tests/save/test_save_validation.gd new file mode 100644 index 00000000..716d7db1 --- /dev/null +++ b/game/tests/save/test_save_validation.gd @@ -0,0 +1,146 @@ +extends GutTest +## Preflight reads untrusted slot data before Main replaces the current landing. + +const MISSION: String = "res://data/missions/conquest.tres" +const UNIT: String = "res://data/units/concord_hauler.tres" + + +func _save() -> Dictionary: + return { + "format": 2, + "kind": "mission", + "mission": MISSION, + "landing": {"world": {"version": SimWorld.SAVE_VERSION}} + } + + +func test_format_two_keeps_every_supported_legacy_world_version() -> void: + for version: int in range(1, SimWorld.SAVE_VERSION + 1): + var data: Dictionary = _save() + data.landing.world.version = version + assert_eq(SaveGame.check(data), "", "world version %d" % version) + assert_not_null(SaveGame.from_dict(data)) + + +func test_nested_containers_are_refused_without_typed_assignment_errors() -> void: + for key: String in ["landing", "plan", "campaign"]: + var data: Dictionary = _save() + data[key] = [] + assert_ne(SaveGame.check(data), "", key) + assert_null(SaveGame.from_dict(data), key) + for key: String in ["world", "clock", "mission", "groups"]: + var data: Dictionary = _save() + data.landing[key] = [] + assert_ne(SaveGame.check(data), "", key) + for key: String in ["units", "buildings", "resource_nodes", "sites"]: + var data: Dictionary = _save() + data.landing.world[key] = [null] + assert_ne(SaveGame.check(data), "", key) + + +func test_existing_resources_must_have_the_consumed_definition_class() -> void: + var data: Dictionary = _save() + data.mission = UNIT + assert_ne(SaveGame.check(data), "", "a unit is not a mission") + for key: String in ["units", "buildings", "resource_nodes", "sites"]: + data = _save() + data.landing.world[key] = [{"version": 1, "def": MISSION, "position": "Vector3(0, 0, 0)"}] + assert_ne(SaveGame.check(data), "", key) + data = _save() + data.landing.world.props = {"version": 1, "props": [{"version": 1, "def": MISSION}]} + assert_ne(SaveGame.check(data), "", "a mission is not a prop") + data = _save() + data.kind = "campaign" + data.campaign_def = MISSION + assert_ne(SaveGame.check(data), "", "a mission is not a campaign") + + +func test_positions_must_parse_to_the_vector_the_restore_reader_consumes() -> void: + for position: Variant in [42, "42", "Vector2(1, 2)", "Vector3(inf, 0, 0)", "Vector3(broken"]: + var data: Dictionary = _save() + data.landing.world.units = [ + { + "version": Unit.SAVE_VERSION, + "def": UNIT, + "locomotion": + { + "version": Locomotion.SAVE_VERSION, + "mover": {"version": Mover.SAVE_VERSION, "position": position} + } + } + ] + assert_ne(SaveGame.check(data), "", str(position)) + var data: Dictionary = _save() + data.landing.world.units = [ + { + "version": Unit.SAVE_VERSION, + "def": UNIT, + "locomotion": + { + "version": Locomotion.SAVE_VERSION, + "mover": {"version": Mover.SAVE_VERSION}, + "post": var_to_str(Vector3.INF), + "wanted": var_to_str(Vector3.INF) + } + } + ] + assert_eq(SaveGame.check(data), "", "idle locomotion uses INF as an unset destination") + + +func test_campaign_plan_arrays_and_result_records_are_checked_before_parsing() -> void: + var data: Dictionary = _save() + data.kind = "campaign" + data.campaign_def = SaveFixture.CAMPAIGN + data.plan = {"version": 1, "node": "kessel_proving", "techs": {}} + assert_ne(SaveGame.check(data), "") + data.plan.techs = [] + data.campaign = {"results": {"kessel_proving": []}} + assert_ne(SaveGame.check(data), "") + + +func test_consumed_component_versions_are_refused_without_changing_the_format() -> void: + for version: Variant in [0, Health.SAVE_VERSION + 1, "1"]: + var data: Dictionary = _save() + data.landing.world.units = [ + {"version": Unit.SAVE_VERSION, "def": UNIT, "health": {"version": version}} + ] + assert_ne(SaveGame.check(data), "", str(version)) + var data: Dictionary = _save() + data.landing.world.economy = { + "version": Economy.SAVE_VERSION, + "stockpiles": {"0": {"version": Stockpile.SAVE_VERSION + 1}} + } + assert_ne(SaveGame.check(data), "", "nested stockpile version") + + +func test_malformed_movement_paths_are_refused_without_parser_errors() -> void: + for path: Variant in [[], "42", "PackedVector3Array(broken", "PackedVector3Array(1, 2)"]: + var data: Dictionary = _save() + data.landing.world.units = [ + { + "version": Unit.SAVE_VERSION, + "def": UNIT, + "locomotion": + { + "version": Locomotion.SAVE_VERSION, + "mover": {"version": Mover.SAVE_VERSION, "path": path} + } + } + ] + assert_ne(SaveGame.check(data), "", str(path)) + + +func test_watcher_and_commander_vectors_are_checked_before_restore() -> void: + var data: Dictionary = _save() + data.landing.world.units = [ + { + "version": Unit.SAVE_VERSION, + "def": UNIT, + "watcher": {"version": Watcher.SAVE_VERSION, "last_noticed": "42"} + } + ] + assert_ne(SaveGame.check(data), "", "watcher last-noticed point") + for key: String in ["home", "staging"]: + data = _save() + data.landing.mission = {"commander": {key: "42"}} + assert_ne(SaveGame.check(data), "", key) diff --git a/game/tests/save/test_save_validation.gd.uid b/game/tests/save/test_save_validation.gd.uid new file mode 100644 index 00000000..fd8bcf42 --- /dev/null +++ b/game/tests/save/test_save_validation.gd.uid @@ -0,0 +1 @@ +uid://dxsjbb7x5jfi1 diff --git a/game/tests/save/test_stealth_landing_round_trip.gd b/game/tests/save/test_stealth_landing_round_trip.gd index 2fc60f7f..ca10e2e9 100644 --- a/game/tests/save/test_stealth_landing_round_trip.gd +++ b/game/tests/save/test_stealth_landing_round_trip.gd @@ -22,7 +22,7 @@ func after_each() -> void: _f.dispose(map) _maps.clear() # Let the renderer release what the freed visuals used (sabotage sparks). - await wait_frames(3) + await wait_physics_frames(3) func test_quiet_uplink_round_trip_carries_on() -> void: diff --git a/game/tests/ui/test_discovery_presentation.gd b/game/tests/ui/test_discovery_presentation.gd new file mode 100644 index 00000000..6c6f9d95 --- /dev/null +++ b/game/tests/ui/test_discovery_presentation.gd @@ -0,0 +1,95 @@ +extends GutTest +## Exploration reveals physical sites; map records belong to completed player surveys. + +var _f: DiscoveryFixture +var _minimap: Minimap + + +func before_each() -> void: + _f = DiscoveryFixture.new(self, true) + _minimap = Minimap.new() + _minimap.world = _f.world + _minimap.faction = 0 + autofree(_minimap) + + +func after_each() -> void: + _f.dispose() + + +func _reveal(at: Vector3) -> void: + var grid: VisionGrid = _f.world.vision.grid + grid.begin_update(0) + grid.reveal(0, at, 10.0) + grid.end_update(0) + _f.world.discovery.tick(1, SimClock.TICK_DELTA) + + +func test_unknown_sites_are_hidden_until_their_ground_is_explored() -> void: + var site: DiscoverySite = _f.site(_f.discovery(&"unknown"), Vector3(50, 0, 50)) + assert_false(site.visible, "charted is not a free reveal") + assert_false(site.is_signal_known_to_player) + _reveal(site.position) + assert_true(site.visible) + assert_true(site.is_visible_to_player) + assert_true(site.is_signal_known_to_player) + assert_true(_minimap.recorded_sites().is_empty(), "unscanned sites have no map marker") + _reveal(Vector3(-50, 0, -50)) + assert_true(site.visible, "physical site remains in explored ground") + assert_false(site.is_visible_to_player, "audio still respects current sight") + + +func test_only_completed_player_surveys_become_map_records() -> void: + var site: DiscoverySite = _f.site(_f.discovery(&"player_site"), Vector3.ZERO) + var enemy: DiscoverySite = _f.site(_f.discovery(&"enemy_site"), Vector3(2, 0, 0)) + _reveal(Vector3.ZERO) + enemy.resolve(1) + assert_true(_minimap.recorded_sites().is_empty(), "enemy discoveries do not reveal locations") + site.resolve(0) + assert_eq(_minimap.recorded_sites(), [site] as Array[DiscoverySite]) + var saved: Dictionary = _f.world.vision.to_dict() + _f.world.vision.from_dict(saved) + _f.world.discovery.tick(2, SimClock.TICK_DELTA) + assert_eq( + _minimap.recorded_sites(), [site] as Array[DiscoverySite], "exploration survives saves" + ) + + +func test_sites_use_their_model_and_scan_feedback_without_floating_labels() -> void: + var visual: SiteVisual = SiteVisual.new() + add_child_autofree(visual) + assert_eq(visual.find_children("*", "Label3D", true, false).size(), 0) + assert_false(visual._ring.visible) + visual.set_scan_progress(0.5) + assert_true(visual._ring.visible) + assert_true(visual._column.visible) + visual.set_resolved(true) + assert_false(visual._ring.visible) + assert_gt(visual._glow.light_energy, 0.0) + + +func test_restoration_applies_exploration_before_any_tick_or_render() -> void: + var def: DiscoveryDef = load("res://data/discoveries/kessel_trail_beacon.tres") + _f.site(def, Vector3(50, 0, 50)) + var restored: EconomyFixture = EconomyFixture.new(self) + restored.world.enable_vision(DiscoveryFixture.AREA, 2.0) + restored.world.from_dict(_f.world.to_dict()) + assert_true(restored.context.sim_clock.paused, "no tick has run") + var site: DiscoverySite = restored.world.discovery.site_of(def.id) + assert_not_null(site) + assert_false(site.visible, "restoring charted state cannot reveal unexplored ground") + assert_false(site.is_signal_known_to_player) + restored.dispose() + + +func test_survey_objectives_do_not_reveal_site_locations_even_in_older_saves() -> void: + var def: ObjectiveDef = ObjectiveDef.new() + def.area_center = Vector3(70, 0, 70) + def.area_radius = 8.0 + var objective: ScanSitesObjective = ScanSitesObjective.new() + objective.configure(def) + assert_false(objective.has_area) + var saved: Dictionary = objective.to_dict() + saved["has_area"] = true + objective.from_dict(saved) + assert_false(objective.has_area, "legacy objective rings must not reveal the site") diff --git a/game/tests/ui/test_discovery_presentation.gd.uid b/game/tests/ui/test_discovery_presentation.gd.uid new file mode 100644 index 00000000..c1176bfc --- /dev/null +++ b/game/tests/ui/test_discovery_presentation.gd.uid @@ -0,0 +1 @@ +uid://c2babgmnnrtr0 diff --git a/game/tests/ui/test_mission_unlock.gd b/game/tests/ui/test_mission_unlock.gd index b87eaf53..f7c24662 100644 --- a/game/tests/ui/test_mission_unlock.gd +++ b/game/tests/ui/test_mission_unlock.gd @@ -146,17 +146,17 @@ func test_a_mission_won_through_main_is_recorded() -> void: add_child(main) var first: MissionDef = main.catalog.missions[0] main.start_mission(first) - await wait_frames(3) + await wait_physics_frames(3) assert_not_null(main.runner) main.runner.finish(false) assert_false(Settings.has_won_mission(first.id), "a lost mission opens nothing") main.start_mission(first) - await wait_frames(3) + await wait_physics_frames(3) main.runner.finish(true) assert_true(Settings.has_won_mission(first.id)) assert_true(main.catalog.is_open(main.catalog.missions[1], Settings.missions_won)) main.queue_free() - await wait_frames(2) + await wait_physics_frames(2) for slot: StringName in SaveSlots.slots(): SaveSlots.remove(slot) DirAccess.remove_absolute(ProjectSettings.globalize_path(SAVES)) diff --git a/game/tests/ui/test_sell_building_panel.gd b/game/tests/ui/test_sell_building_panel.gd new file mode 100644 index 00000000..28ff4258 --- /dev/null +++ b/game/tests/ui/test_sell_building_panel.gd @@ -0,0 +1,125 @@ +extends GutTest + +var _f: EconomyFixture +var _controller: SelectionController +var _panel: CommandPanel + + +func before_each() -> void: + _f = EconomyFixture.new(self) + _controller = SelectionController.new() + _controller.world = _f.world + add_child(_controller) + _panel = CommandPanel.new() + add_child(_panel) + _panel.setup(_controller, _f.world, 0) + + +func after_each() -> void: + _panel.free() + _controller.free() + _f.dispose() + + +func _select(building: Building) -> void: + _controller.select_building(building) + _panel._process(0.0) + + +func _sale() -> Dictionary: + for entry: Dictionary in _panel._entries: + if entry.has("sell"): + return entry + return {} + + +func test_sell_requires_inline_confirmation_and_cancel_does_not_issue_order() -> void: + var building: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, true) + _select(building) + var entry: Dictionary = _sale() + assert_false(entry.is_empty()) + var button: Button = entry["button"] + var cancel: Button = entry["cancel"] + assert_true(button.text.begins_with("SELL")) + assert_string_contains(button.text, "+75 Alloy") + assert_false(cancel.visible) + button.pressed.emit() + assert_true(button.text.begins_with("Confirm sell")) + assert_true(cancel.visible) + assert_eq(_f.context.command_queue.pending_count(), 0) + cancel.pressed.emit() + assert_true(button.text.begins_with("SELL")) + assert_false(cancel.visible) + assert_eq(_f.context.command_queue.pending_count(), 0) + button.pressed.emit() + button.pressed.emit() + button.pressed.emit() + assert_eq(_f.context.command_queue.pending_count(), 1) + assert_true(button.disabled) + assert_true(_f.world.buildings.has(building)) + _f.tick() + assert_null(_controller.selected_building) + assert_eq(_f.pile().alloy, 1075) + + +func test_construction_has_full_refund_and_confirmation_resets_with_selection() -> void: + var site: Building = _f.world.spawn_building(_f.reactor, 0, Vector3.ZERO, false) + var other: Building = _f.world.spawn_building(_f.barracks, 0, Vector3(30, 0, 0), true) + _select(site) + var button: Button = _sale()["button"] + assert_string_contains(button.text, "+150 Alloy") + button.pressed.emit() + _select(other) + var other_button: Button = _sale()["button"] + assert_true(other_button.text.begins_with("SELL")) + other_button.pressed.emit() + assert_eq(_f.context.command_queue.pending_count(), 0) + _select(site) + var reset_button: Button = _sale()["button"] + assert_true(reset_button.text.begins_with("SELL")) + + +func test_production_commands_remain_and_refund_preview_tracks_queue() -> void: + var building: Building = _f.world.spawn_building(_f.barracks, 0, Vector3.ZERO, true) + _select(building) + assert_eq(_panel._entries.size(), 2, "unit production and SELL both available") + _panel.fit_width(220.0) + assert_eq(_panel._scroll.horizontal_scroll_mode, ScrollContainer.SCROLL_MODE_AUTO) + assert_lte(_panel._scroll.custom_minimum_size.x, 220.0) + var sale: Button = _sale()["button"] + sale.pressed.emit() + _f.push(ProduceCommand.new(0, building, _f.ranger)) + _f.tick() + _panel._process(0.0) + assert_string_contains(sale.text, "+175 Alloy") + sale.pressed.emit() + _f.tick() + assert_eq(_f.pile().alloy, 1100) + + +func test_protected_building_has_no_sell_action() -> void: + var lander: Building = _f.world.spawn_building(_f.lander, 0, Vector3.ZERO, true) + _select(lander) + assert_true(_sale().is_empty()) + assert_eq(_panel._entries.size(), 2, "Lander keeps its production commands") + + +func test_field_and_vent_commands_coexist_with_sell() -> void: + var option := FieldOptionDef.new() + option.id = &"test_scan" + option.display_name = "Scan" + _f.barracks.field_options = [option] + var lab: Building = _f.world.spawn_building(_f.barracks, 0, Vector3(30, 0, 0), true) + _select(lab) + assert_eq(_panel._entries.size(), 3, "production, field option and SELL") + _f.vent.erupts = true + _f.world.spawn_resource_node(_f.vent, Vector3.ZERO) + var tap: Building = _f.world.spawn_building(_f.tap, 0, Vector3.ZERO, true) + var rule := EruptionRule.new() + rule.system = EruptionSystem + PlanetRuleSystem.start(_f.world, rule) + _select(tap) + assert_eq(_panel._entries.size(), 2, "VENT and SELL") + var vent_entry: Dictionary = _panel._entries[0] + assert_true(vent_entry.has("vent")) + assert_false(_sale().is_empty()) diff --git a/game/tests/ui/test_sell_building_panel.gd.uid b/game/tests/ui/test_sell_building_panel.gd.uid new file mode 100644 index 00000000..c61f7992 --- /dev/null +++ b/game/tests/ui/test_sell_building_panel.gd.uid @@ -0,0 +1 @@ +uid://nrjw4yl5pi1p diff --git a/game/ui/command_panel.gd b/game/ui/command_panel.gd index cdd750bb..7c1c716e 100644 --- a/game/ui/command_panel.gd +++ b/game/ui/command_panel.gd @@ -32,7 +32,7 @@ const AIM_HINT: String = "Left-click the map: use it there · right-click or E ## %s = the command button ("Left-click" or "Right-click"). const BUILD_HINT: String = "Pick a building, then left-click the ground · %s a site to help build" const HAUL_HINT: String = "%s an Alloy deposit to harvest it · new Haulers start on their own" -const SCAN_HINT: String = "%s a ? on the map to scan it for Intel · moving away stops the scan" +const SCAN_HINT: String = "%s a discovered site to scan it for Intel · moving away stops the scan" const PRODUCE_HINT: String = ( "Left-click: queue · right-click a button: cancel · " + "%s ground: rally point" ) @@ -71,6 +71,8 @@ var _progress: ProgressBar var _hint: Label var _mode: String = "" var _entries: Array[Dictionary] = [] # { def, button, caption, badge, bar } +var _sell_confirming: bool = false +var _sell_pending: bool = false func setup(p_controller: SelectionController, p_world: SimWorld, p_faction: int) -> void: @@ -161,6 +163,8 @@ func _unit_mode() -> String: func _rebuild() -> void: + _sell_confirming = false + _sell_pending = false for child: Node in _buttons.get_children(): child.queue_free() _entries.clear() @@ -187,6 +191,8 @@ func _rebuild() -> void: _add_option_button(option, building) if building.is_operational() and _eruptions_on(building) != null: _add_vent_button(building) + if SellBuildingCommand.can_sell(building, faction): + _add_sell_buttons(building) elif _mode.begins_with("aim:"): _title.text = controller.targeting_option.display_name.to_upper() elif _mode == "stealth": @@ -227,6 +233,9 @@ func _refresh() -> void: elif _mode.begins_with("building:"): _refresh_building(controller.selected_building) for entry: Dictionary in _entries: + if entry.has("sell"): + _refresh_sell(entry) + continue if entry.has("stealth"): continue if entry.has("vent"): @@ -341,6 +350,60 @@ func _refresh_entry(entry: Dictionary, pile: Stockpile) -> void: bar.value = producer.progress() +## Inline confirmation stays in the horizontally scrollable command row. +func _add_sell_buttons(building: Building) -> void: + var holder := VBoxContainer.new() + var button: Button = HudStyle.make_button(null, "SELL") + button.pressed.connect(_on_sell_pressed.bind(building)) + holder.add_child(button) + var cancel: Button = Button.new() + cancel.text = "Cancel" + cancel.pressed.connect(_on_sell_cancelled) + holder.add_child(cancel) + _buttons.add_child(holder) + _entries.append({"sell": true, "button": button, "cancel": cancel, "building": building}) + + +func _refresh_sell(entry: Dictionary) -> void: + var building: Building = entry["building"] + var button: Button = entry["button"] + var cancel: Button = entry["cancel"] + var eligible: bool = SellBuildingCommand.can_sell(building, faction) + button.disabled = not eligible or _sell_pending + cancel.visible = _sell_confirming and not _sell_pending and eligible + if not eligible: + return + var refund: Vector2i = SellBuildingCommand.refund_for(building) + var action: String = "Confirm sell" if _sell_confirming else "SELL" + if _sell_pending: + action = "Selling…" + button.text = "%s\n+%d Alloy · +%d Flux" % [action, refund.x, refund.y] + button.tooltip_text = ( + "Remove %s. Refund includes cancelled queued units.\nReturns %d Alloy and %d Flux." + % [building.def.display_name, refund.x, refund.y] + ) + + +func _on_sell_pressed(building: Building) -> void: + if ( + _sell_pending + or controller.selected_building != building + or not SellBuildingCommand.can_sell(building, faction) + ): + return + if _sell_confirming: + _sell_pending = true + world.context.command_queue.push(SellBuildingCommand.new(faction, building)) + else: + _sell_confirming = true + _refresh() + + +func _on_sell_cancelled() -> void: + _sell_confirming = false + _refresh() + + func _add_build_button(def: BuildingDef) -> void: var button: Button = HudStyle.make_button(def.icon, def.display_name) button.tooltip_text = ( diff --git a/game/ui/hud.gd b/game/ui/hud.gd index 0a8b2c2b..ba5e610c 100644 --- a/game/ui/hud.gd +++ b/game/ui/hud.gd @@ -22,7 +22,7 @@ signal survey_log_toggled(is_open: bool) const HINT_CLASSIC: String = ( "MOUSE classic (Command & Conquer): left click does it all\n" + "LEFT own unit or building: select · drag: box · double-click: all of type\n" - + " units selected: ground move · enemy in sight attack · ? scan\n" + + " units selected: ground move · enemy in sight attack · discovery: scan\n" + " deposit harvest (Haulers) · own site help build (Fabricators)\n" + " building selected: ground sets the rally point\n" + "RIGHT deselect · while placing or aiming: cancel (or Esc)\n" @@ -39,7 +39,7 @@ const HINT_MODERN: String = ( "MOUSE modern: left selects, right commands\n" + "LEFT select: click, drag, double-click type · building: click it\n" + " enemy in sight: attack · buttons: build, queue units\n" - + "RIGHT move · enemy in sight: attack · ? site: scan (Surveyors)\n" + + "RIGHT move · enemy in sight: attack · discovery: scan (Surveyors)\n" + " deposit: harvest (Haulers) · site: help build (Fabricators)\n" + " building selected: rally point · unit button: cancel one\n" + " while placing or aiming: cancel (or Esc)\n" diff --git a/game/ui/info_panel.gd b/game/ui/info_panel.gd index fd5071e3..6e92f374 100644 --- a/game/ui/info_panel.gd +++ b/game/ui/info_panel.gd @@ -225,7 +225,7 @@ static func controls_text(scheme: StringName) -> String: "%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 discovered site · scan (Surveyors)" % command, "%s own building site · help build (Fabricators)" % command, "%s ground with a building selected · set its rally point" % command, ( diff --git a/game/ui/minimap.gd b/game/ui/minimap.gd index 49ad4e82..0a798cdc 100644 --- a/game/ui/minimap.gd +++ b/game/ui/minimap.gd @@ -4,8 +4,7 @@ extends PanelContainer ## dark) under the fog of war, resource nodes the player has explored, the player's ## units and buildings in team colour, enemies the player sees in the enemy's team ## colour (TeamColors: red by default; enemy buildings seen before but not in sight -## now stay, dimmed, where they were last seen), discovery signals the orbital scan -## charted (a "?" even under fog; a dot in the discovery's colour once resolved), and +## now stay, dimmed, where they were last seen), discoveries the player has scanned, and ## the camera's view. Left click or drag moves the camera there. In the modern mouse ## scheme a right click orders the selected units to move there (Shift queues); in ## the classic scheme, where right click only deselects and cancels, it does nothing @@ -20,7 +19,6 @@ const REMEMBERED_ALPHA: float = 0.75 const NODE_COLOR: Color = Color(0.72, 0.84, 0.95) const VENT_COLOR: Color = Color(0.45, 0.85, 1.0) const VIEW_COLOR: Color = Color(1.0, 1.0, 1.0, 0.85) -const SIGNAL_COLOR: Color = Color(0.35, 0.92, 1.0) const FOG_SHADER: String = """ shader_type canvas_item; @@ -223,22 +221,22 @@ func track_objective(objective: RefCounted) -> void: _objectives.erase(changed) -## Charted sites: an unresolved signal is a "?" in a ring, a resolved one a dot. -func _draw_sites(scale: float) -> void: - if world.discovery == null: - return - var font: Font = get_theme_default_font() +## Only the player's completed surveys become map records. Unknown locations have +## no icon, even if an orbital definition or an enemy already knows about them. +func recorded_sites() -> Array[DiscoverySite]: + var result: Array[DiscoverySite] = [] + if world == null or world.discovery == null: + return result for site: DiscoverySite in world.discovery.sites: - if not site.is_signal_known_to_player or site.def == null: - continue - var at: Vector2 = to_map(site.position) - if site.is_resolved: - _overlay.draw_circle(at, maxf(site.def.radius * scale, 2.5), site.def.color) - continue - _overlay.draw_circle(at, 6.0, Color(0, 0, 0, 0.55)) - _overlay.draw_arc(at, 6.0, 0.0, TAU, 16, SIGNAL_COLOR, 1.5) - _overlay.draw_string( - font, at + Vector2(-3.0, 4.0), "?", HORIZONTAL_ALIGNMENT_LEFT, -1, 11, SIGNAL_COLOR + if site.def != null and site.is_resolved and site.resolved_by == faction and site.visible: + result.append(site) + return result + + +func _draw_sites(scale: float) -> void: + for site: DiscoverySite in recorded_sites(): + _overlay.draw_circle( + to_map(site.position), maxf(site.def.radius * scale, 2.5), site.def.color ) diff --git a/game/ui/star_map.gd b/game/ui/star_map.gd index 1fac4824..1718f199 100644 --- a/game/ui/star_map.gd +++ b/game/ui/star_map.gd @@ -2,7 +2,7 @@ class_name StarMap extends MenuScreen ## Aboard the Meridian: the star map (PLAN 1). The route of landings with their ## states; hovering a node shows its orbital scan (planet, its rule, mission type, -## the `?` signals the scan charted), clicking an open node picks it and LAUNCH goes +## surface survey context), clicking an open node picks it and LAUNCH goes ## to its briefing. MERIDIAN opens the tech web and loadout. ## LAUNCH on the picked node. @@ -173,10 +173,7 @@ func _signals_text(mission: MissionDef) -> String: for site: DiscoveryDef in sites: if session.state.discoveries.has(site.id): known += 1 - var text: String = "%d unresolved ? signals" % sites.size() - if known > 0: - text += " (%d match log entries)" % known - return text + return "%d discoveries recorded" % known if known > 0 else "Surface survey required" static func _rule_text(planet: PlanetDef) -> String: diff --git a/game/ui/survey_log_panel.gd b/game/ui/survey_log_panel.gd index 912f0e07..b21126a0 100644 --- a/game/ui/survey_log_panel.gd +++ b/game/ui/survey_log_panel.gd @@ -13,7 +13,7 @@ const TYPE_NAMES: Dictionary[StringName, String] = { DiscoveryDef.ENEMY: "ENEMY", } const EMPTY_TEXT: String = ( - "No entries yet.\n\n" + "Select a Surveyor and click a ? on the map to scan it." + "No entries yet.\n\n" + "Explore with a Surveyor, then scan an unusual site you encounter." ) var _entries: Array[DiscoveryDef] = [] diff --git a/game/ui/title_screen.gd b/game/ui/title_screen.gd index b0b01d43..614018ab 100644 --- a/game/ui/title_screen.gd +++ b/game/ui/title_screen.gd @@ -1,11 +1,12 @@ class_name TitleScreen extends MenuScreen -## The first screen: Continue (when an autosave exists), New campaign, Single missions +## The first screen: Continue (when an autosave exists), New campaign, Single missions, Load game ## (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. signal new_campaign_pressed +signal load_pressed signal continue_pressed signal missions_pressed signal settings_pressed @@ -17,6 +18,7 @@ signal credits_pressed ## Space kept free above and below the column, px. const SCREEN_MARGIN: int = 24 +var _load: Button var _continue: Button var _menu: VBoxContainer var _menu_scroll: ScrollContainer @@ -44,9 +46,12 @@ func _build() -> void: _menu_scroll = column.add_scroll(_menu) _continue = _add_button(_menu, "CONTINUE", continue_pressed) var start: Button = HudStyle.make_menu_button("NEW CAMPAIGN", 280.0) + _keyboard_button(start) start.pressed.connect(show_new_campaign) _menu.add_child(start) _add_button(_menu, "SINGLE MISSIONS", missions_pressed) + _load = _add_button(_menu, "LOAD GAME", load_pressed) + _load.name = &"LoadGame" _add_button(_menu, "HOW TO PLAY", how_to_play_pressed) _add_button(_menu, "CONTROLS", controls_pressed) _add_button(_menu, "SETTINGS", settings_pressed) @@ -72,6 +77,7 @@ func _build() -> void: buttons.add_theme_constant_override(&"separation", 10) _new_campaign.add_child(buttons) var back: Button = HudStyle.make_menu_button("BACK", 135.0) + _keyboard_button(back) back.pressed.connect(_show_menu) buttons.add_child(back) _add_button(buttons, "START", new_campaign_pressed).custom_minimum_size = Vector2(135, 40) @@ -106,6 +112,7 @@ func _show_menu() -> void: func _add_button(column: BoxContainer, caption: String, pressed: Signal) -> Button: var button: Button = HudStyle.make_menu_button(caption, 280.0) + _keyboard_button(button) button.pressed.connect( func() -> void: Events.ui_feedback.emit(&"click") @@ -113,3 +120,8 @@ func _add_button(column: BoxContainer, caption: String, pressed: Signal) -> Butt ) column.add_child(button) return button + + +func _keyboard_button(button: Button) -> void: + button.focus_mode = Control.FOCUS_ALL + button.add_theme_stylebox_override(&"focus", HudStyle.button_style(&"hover")) diff --git a/tools/check.sh b/tools/check.sh index cd5f6ed3..ffa39557 100755 --- a/tools/check.sh +++ b/tools/check.sh @@ -36,25 +36,24 @@ run_godot() { local log="$LOG_DIR/$name.log" local status=0 with_timeout "$GODOT" --headless --path "$GAME" "$@" >"$log" 2>&1 || status=$? - # Strip ANSI colours so the output and the grep are plain text. - sed -e $'s/\x1b\\[[0-9;]*m//g' "$log" >"$log.txt" - cat "$log.txt" - if [ "$status" -ne 0 ]; then - fail "$name: godot exited with status $status" - fi - # Not ours: the GUT editor plugin asks GitHub for its latest version on a fresh - # machine, and a shared CI runner address is often over GitHub's anonymous limit. - local noise='^ERROR: \[GUT\] Could not get version info' - if grep -E '^(SCRIPT ERROR|ERROR|WARNING|USER ERROR|USER WARNING):' "$log.txt" \ - | grep -Ev "$noise" >/dev/null; then - fail "$name: engine reported errors or warnings (see above)" + local diagnostic_status=0 + if [ "$name" = import ]; then + python3 "$ROOT/tools/godot_diagnostics.py" "$log" --allow-import-noise || diagnostic_status=$? + else + python3 "$ROOT/tools/godot_diagnostics.py" "$log" || diagnostic_status=$? fi + [ "$status" -eq 0 ] || fail "$name: godot exited with status $status" + [ "$diagnostic_status" -eq 0 ] || fail "$name: engine or GUT reported diagnostics (see above)" } command -v "$GODOT" >/dev/null || fail "Godot binary '$GODOT' not found (set GODOT=...)" command -v uvx >/dev/null || fail "uvx not found (install uv: https://docs.astral.sh/uv/)" command -v perl >/dev/null || fail "perl not found" +step "Python tooling tests and project integrity" +python3 -m unittest discover -s "$ROOT/tools" -p 'test_*.py' +python3 "$ROOT/tools/project_integrity.py" + step "Format check (gdformat $GDTOOLKIT_VERSION)" gdtoolkit gdformat --check . || fail "format (run: cd game && uvx --from gdtoolkit==$GDTOOLKIT_VERSION gdformat .)" diff --git a/tools/export.sh b/tools/export.sh index 484850ee..a9f3d99b 100755 --- a/tools/export.sh +++ b/tools/export.sh @@ -47,13 +47,10 @@ import_log="$BUILD/logs/export-import.log" status=0 perl -e 'alarm shift; exec @ARGV or die "exec: $!"' "${EXPORT_TIMEOUT:-1800}" \ "$GODOT" --headless --path "$GAME" --import >"$import_log" 2>&1 || status=$? -sed -e $'s/\x1b\[[0-9;]*m//g' "$import_log" >"$import_log.txt" -cat "$import_log.txt" +diagnostic_status=0 +python3 "$ROOT/tools/godot_diagnostics.py" "$import_log" --allow-import-noise || diagnostic_status=$? [ "$status" -eq 0 ] || fail "export import failed (status $status; $import_log)" -if grep -E '^(SCRIPT ERROR|ERROR|WARNING|USER ERROR|USER WARNING):' "$import_log.txt" \ - | grep -Ev '^ERROR: \[GUT\] Could not get version info' >/dev/null; then - fail "export import reported errors or warnings ($import_log)" -fi +[ "$diagnostic_status" -eq 0 ] || fail "export import reported errors or warnings ($import_log)" for preset in "${presets[@]}"; do case "$preset" in @@ -73,12 +70,10 @@ for preset in "${presets[@]}"; do status=0 perl -e 'alarm shift; exec @ARGV or die "exec: $!"' "${EXPORT_TIMEOUT:-1800}" \ "$GODOT" --headless --path "$GAME" --export-release "$preset" "$out" >"$log" 2>&1 || status=$? - sed -e $'s/\x1b\[[0-9;]*m//g' "$log" >"$log.txt" - cat "$log.txt" + diagnostic_status=0 + python3 "$ROOT/tools/godot_diagnostics.py" "$log" || diagnostic_status=$? [ "$status" -eq 0 ] || fail "export of $preset failed (status $status; $log)" - if grep -E '^(SCRIPT ERROR|ERROR|WARNING|USER ERROR|USER WARNING):' "$log.txt" >/dev/null; then - fail "export of $preset reported errors or warnings ($log)" - fi + [ "$diagnostic_status" -eq 0 ] || fail "export of $preset reported errors or warnings ($log)" [ -e "$out" ] || fail "export of $preset produced no $out" if [[ "$preset" == Web* ]]; then python3 "$ROOT/tools/web_manifest.py" "$(dirname "$out")" --preset "$preset" diff --git a/tools/godot_diagnostics.py b/tools/godot_diagnostics.py new file mode 100644 index 00000000..615ae86c --- /dev/null +++ b/tools/godot_diagnostics.py @@ -0,0 +1,35 @@ +"""Print plain Godot logs and reject engine/GUT diagnostics, even after exit 0.""" + +import argparse +from pathlib import Path +import re + +ANSI = re.compile(r'\x1b\[[0-9;]*m') +DIAGNOSTIC = re.compile( + r'^\s*(?:SCRIPT ERROR|ERROR|WARNING|USER ERROR|USER WARNING|' + r'\[GUT WARNING\]|\[GUT ERROR\]|\[DEPRECATED\]):', re.MULTILINE +) +# Editor-plugin version lookup is external and rate-limited on shared runners. +IMPORT_NOISE = 'ERROR: [GUT] Could not get version info' + + +def failures(log: str, allow_import_noise: bool = False) -> list[str]: + plain = ANSI.sub('', log) + return [line for line in plain.splitlines() + if DIAGNOSTIC.match(line) + and not (allow_import_noise and line == IMPORT_NOISE)] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('log', type=Path) + parser.add_argument('--allow-import-noise', action='store_true') + args = parser.parse_args() + plain = ANSI.sub('', args.log.read_text(errors='replace')) + args.log.with_suffix(args.log.suffix + '.txt').write_text(plain) + print(plain, end='') + return int(bool(failures(plain, args.allow_import_noise))) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/project_integrity.py b/tools/project_integrity.py new file mode 100644 index 00000000..622364fa --- /dev/null +++ b/tools/project_integrity.py @@ -0,0 +1,66 @@ +"""Fast source-boundary and generated-audio integrity checks; no asset synthesis.""" + +import hashlib +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parent.parent +AUDIO_SUFFIXES = {'.wav', '.mp3', '.ogg'} + + +def check_audio(root: Path) -> list[str]: + entries = json.loads((root / 'audio_src/manifest.json').read_text())['sounds'] + errors = [] + ids = set() + paths = set() + for entry in entries: + name = entry['file'] + if entry['id'] in ids or name in paths: + errors.append(f'duplicate audio manifest entry: {name}') + ids.add(entry['id']) + paths.add(name) + path = root / name + if not path.is_file(): + errors.append(f'missing audio: {name}') + elif hashlib.sha256(path.read_bytes()).hexdigest() != entry['sha256']: + errors.append(f'audio hash mismatch: {name}') + if not Path(str(path) + '.import').is_file(): + errors.append(f'missing audio import settings: {name}') + actual = {p.relative_to(root).as_posix() for p in (root / 'game/assets/audio').rglob('*') + if p.suffix in AUDIO_SUFFIXES} + for name in sorted(actual - paths): + errors.append(f'untracked generated audio: {name}') + return errors + + +def check_sim_dependencies(root: Path) -> list[str]: + """Scenes may compose visuals; simulation scripts must not depend on adapters.""" + game = root / 'game' + classes = {'Audio', 'UiTheme'} + for layer in ('ui', 'audio', 'presentation'): + for path in (game / layer).rglob('*.gd'): + match = re.search(r'^class_name\s+(\w+)', path.read_text(), re.MULTILINE) + if match: + classes.add(match[1]) + forbidden = re.compile(r'\b(' + '|'.join(sorted(classes)) + r')\b') if classes else None + errors = [] + for path in (game / 'sim').rglob('*.gd'): + for number, line in enumerate(path.read_text().splitlines(), 1): + code = line.split('#', 1)[0] + if re.search(r'res://(?:ui|audio|presentation)/', code) or ( + forbidden and forbidden.search(code)): + errors.append(f'{path.relative_to(root)}:{number}: simulation depends on an adapter') + return errors + + +def main() -> int: + errors = check_audio(ROOT) + check_sim_dependencies(ROOT) + for error in errors: + print(error) + print(f'Project integrity: {len(errors)} failures') + return int(bool(errors)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/test_godot_diagnostics.py b/tools/test_godot_diagnostics.py new file mode 100644 index 00000000..3f85a83e --- /dev/null +++ b/tools/test_godot_diagnostics.py @@ -0,0 +1,21 @@ +import unittest +from godot_diagnostics import failures, IMPORT_NOISE + + +class GodotDiagnosticsTest(unittest.TestCase): + def test_all_diagnostic_prefixes_are_rejected_even_with_color(self): + for prefix in ('SCRIPT ERROR', 'ERROR', 'WARNING', 'USER ERROR', + 'USER WARNING', '[GUT WARNING]', '[GUT ERROR]', '[DEPRECATED]'): + with self.subTest(prefix=prefix): + self.assertEqual(failures(f'\x1b[33m{prefix}: bad\x1b[0m\n'), [prefix + ': bad']) + self.assertEqual(failures(f' {prefix}: bad'), [' ' + prefix + ': bad']) + + def test_only_exact_import_noise_is_allowed_and_only_when_requested(self): + self.assertEqual(failures(IMPORT_NOISE), [IMPORT_NOISE]) + self.assertEqual(failures(IMPORT_NOISE, True), []) + other = IMPORT_NOISE + ' and another error' + self.assertEqual(failures(other, True), [other]) + self.assertEqual(failures(IMPORT_NOISE + '\nERROR: real', True), ['ERROR: real']) + + def test_clean_results_and_summary_counts_are_not_diagnostics(self): + self.assertEqual(failures('Tests 749\nWarnings 0\nDeprecated 0\nAll tests passed!'), []) diff --git a/tools/test_project_integrity.py b/tools/test_project_integrity.py new file mode 100644 index 00000000..d0ea3c70 --- /dev/null +++ b/tools/test_project_integrity.py @@ -0,0 +1,48 @@ +import hashlib +import json +from pathlib import Path +import tempfile +import unittest +from project_integrity import check_audio, check_sim_dependencies + + +class ProjectIntegrityTest(unittest.TestCase): + def test_audio_inventory_and_hashes(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'audio_src').mkdir() + audio = root / 'game/assets/audio/a.mp3' + audio.parent.mkdir(parents=True) + audio.write_bytes(b'original') + Path(str(audio) + '.import').touch() + entry = {'id': 'a', 'file': 'game/assets/audio/a.mp3', + 'sha256': hashlib.sha256(b'original').hexdigest()} + manifest = root / 'audio_src/manifest.json' + manifest.write_text(json.dumps({'sounds': [entry]})) + self.assertEqual(check_audio(root), []) + audio.write_bytes(b'changed') + self.assertIn('hash mismatch', ' '.join(check_audio(root))) + audio.unlink() + self.assertIn('missing audio:', ' '.join(check_audio(root))) + audio.write_bytes(b'original') + audio.with_name('extra.ogg').touch() + self.assertIn('untracked generated audio', ' '.join(check_audio(root))) + manifest.write_text(json.dumps({'sounds': [entry, entry]})) + self.assertIn('duplicate', ' '.join(check_audio(root))) + + def test_script_boundary_allows_scene_composition(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for layer in ('sim', 'presentation'): + (root / 'game' / layer).mkdir(parents=True) + (root / 'game/presentation/visual.gd').write_text('class_name Visual\nextends Node\n') + script = root / 'game/sim/unit.gd' + script.write_text('extends Node\n# Visuals listen to events.\n') + (root / 'game/sim/unit.tscn').write_text('res://presentation/visual.gd') + self.assertEqual(check_sim_dependencies(root), []) + script.write_text('Audio.play(&"click")\n') + self.assertEqual(len(check_sim_dependencies(root)), 1) + script.write_text('var visual: Visual\n') + self.assertEqual(len(check_sim_dependencies(root)), 1) + script.write_text('const SCRIPT = preload("res://presentation/visual.gd")\n') + self.assertEqual(len(check_sim_dependencies(root)), 1) diff --git a/tools/test_web_tools.py b/tools/test_web_tools.py index 2ee3d768..4b20bc91 100644 --- a/tools/test_web_tools.py +++ b/tools/test_web_tools.py @@ -76,6 +76,7 @@ def test_export_rejects_zero_exit_with_script_errors(self): root = Path(temporary) (root / 'tools').mkdir() shutil.copy(ROOT / 'tools/export.sh', root / 'tools/export.sh') + shutil.copy(ROOT / 'tools/godot_diagnostics.py', root / 'tools/godot_diagnostics.py') shutil.copy(ROOT / 'tools/prepare_import.py', root / 'tools/prepare_import.py') importer = root / 'game/presentation/import/model_post_import.gd' importer.parent.mkdir(parents=True) diff --git a/tools/web_tests/deployment.spec.cjs b/tools/web_tests/deployment.spec.cjs index 2f843463..741eae92 100644 --- a/tools/web_tests/deployment.spec.cjs +++ b/tools/web_tests/deployment.spec.cjs @@ -1,3 +1,4 @@ +const { openSingleMissions } = require('./release_navigation.cjs'); const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); @@ -26,7 +27,7 @@ if (process.env.WEB_DEPLOYMENT_URL && !process.env.WEB_DEPLOYMENT_PUBLIC_ONLY) { await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); expect(await page.evaluate(() => crossOriginIsolated)).toBe(true); expect(await page.evaluate(() => window.farlanding.diagnostics)).toBeUndefined(); - await page.mouse.click(630, 388, { delay: 80 }); + await openSingleMissions(page); await page.mouse.click(600, 285, { delay: 80 }); const landing = page.waitForEvent('console', { predicate: entry => entry.text().includes('kessel_proving: 18 resource nodes and the bases placed'), timeout: 90000, diff --git a/tools/web_tests/game.spec.cjs b/tools/web_tests/game.spec.cjs index df733800..24e2f416 100644 --- a/tools/web_tests/game.spec.cjs +++ b/tools/web_tests/game.spec.cjs @@ -1,3 +1,4 @@ +const { openSingleMissions } = require('./release_navigation.cjs'); const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); const fs = require('node:fs/promises'); @@ -61,7 +62,7 @@ test('release starts on WebGL2 and uses real menu input', async ({ page }, info) expect(renderer).toBeTruthy(); await info.attach('runtime', { body: JSON.stringify({ renderer, startupMs: Date.now() - started }), contentType: 'application/json' }); await page.screenshot({ path: info.outputPath('release-title.png') }); - await page.mouse.click(630, 388); + await openSingleMissions(page); await page.screenshot({ path: info.outputPath('release-menu.png') }); await page.mouse.click(600, 285, { delay: 80 }); const landing = page.waitForEvent('console', { predicate: entry => entry.text().includes('kessel_proving: 18 resource nodes and the bases placed'), timeout: 90000 }); diff --git a/tools/web_tests/launch.cjs b/tools/web_tests/launch.cjs index 9033821e..bc38423a 100644 --- a/tools/web_tests/launch.cjs +++ b/tools/web_tests/launch.cjs @@ -2,7 +2,10 @@ async function play(page, choice) { const profile = choice ?? process.env.WEB_GRAPHICS_PROFILE ?? (process.env.WEB_SOFTWARE || process.env.CI ? 'low' : 'saved'); - await page.getByLabel('Graphics', { exact: true }).selectOption(profile); + if (profile !== 'saved') { + await page.getByText('Launch options', { exact: true }).click(); + await page.getByLabel('Graphics preset', { exact: true }).selectOption(profile); + } await page.getByRole('button', { name: 'Play Farlanding' }).click(); } module.exports = { play }; diff --git a/tools/web_tests/launcher.spec.cjs b/tools/web_tests/launcher.spec.cjs new file mode 100644 index 00000000..0a9f8c42 --- /dev/null +++ b/tools/web_tests/launcher.spec.cjs @@ -0,0 +1,19 @@ +const { test, expect } = require('@playwright/test'); + +test('launcher explains graphics defaults and keeps launch options secondary', async ({ page }, info) => { + await page.goto('http://127.0.0.1:8070/'); + await expect(page.getByRole('button', { name: 'Play Farlanding' })).toBeVisible(); + await expect(page.getByLabel('Graphics preset')).toBeHidden(); + await expect.poll(() => page.locator('.identity img').evaluate(image => image.complete && image.naturalWidth > 0)).toBe(true); + await page.screenshot({ path: info.outputPath('browser-launcher.png') }); + await page.getByText('Launch options', { exact: true }).click(); + await expect(page.getByLabel('Graphics preset')).toHaveValue('saved'); + await expect(page.locator('#graphics-help')).toContainText('On your first visit, the game starts on High.'); + await page.getByLabel('Graphics preset').selectOption('low'); + await expect(page.getByLabel('Graphics preset')).toHaveValue('low'); + await page.setViewportSize({ width: 360, height: 640 }); + const button = await page.getByRole('button', { name: 'Play Farlanding' }).boundingBox(); + expect(button.x).toBeGreaterThanOrEqual(0); + expect(button.x + button.width).toBeLessThanOrEqual(360); + await page.screenshot({ path: info.outputPath('browser-launcher-narrow.png') }); +}); diff --git a/tools/web_tests/menu_navigation.spec.cjs b/tools/web_tests/menu_navigation.spec.cjs new file mode 100644 index 00000000..ec19c59b --- /dev/null +++ b/tools/web_tests/menu_navigation.spec.cjs @@ -0,0 +1,38 @@ +const { play } = require('./launch.cjs'); +const { test, expect } = require('@playwright/test'); +const state = page => page.evaluate(() => window.farlanding?.diagnostics); +async function click(page, prefix) { + await expect.poll(async () => (await state(page))?.buttons.some(b => b.text.startsWith(prefix))).toBe(true); + const target = (await state(page)).buttons.find(b => b.text.startsWith(prefix)); + await page.mouse.click(...target.pixel, { delay: 80 }); +} + +test('title Load game returns with Back or Escape and restores a saved landing', async ({ page }, info) => { + 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); + await click(page, 'GOT IT'); + await page.keyboard.press('k'); + await expect.poll(async () => (await state(page)).notice).toBe('Saved to Quicksave.'); + const saved = (await state(page)).quicksave; + await page.keyboard.press('Escape'); + await click(page, 'QUIT TO MISSIONS'); + await click(page, 'BACK'); + await expect.poll(async () => (await state(page)).screen).toBe('title'); + await click(page, 'LOAD GAME'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('QUICKSAVE'))).toBe(true); + await page.screenshot({ path: info.outputPath('title-load-game.png') }); + await click(page, 'BACK'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('QUICKSAVE'))).toBe(false); + await click(page, 'LOAD GAME'); + await page.keyboard.press('Escape'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('QUICKSAVE'))).toBe(false); + await click(page, 'LOAD GAME'); + await click(page, 'QUICKSAVE'); + await expect.poll(async () => (await state(page)).notice).toContain('Loaded Quicksave'); + await expect.poll(async () => (await state(page)).tick).toBeGreaterThan(0); + expect((await state(page)).quicksave).toBe(saved); + expect((await state(page)).paused).toBe(false); + expect((await state(page)).buttons.some(b => b.text === 'LOAD GAME')).toBe(false); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); +}); diff --git a/tools/web_tests/release_navigation.cjs b/tools/web_tests/release_navigation.cjs new file mode 100644 index 00000000..2d480c02 --- /dev/null +++ b/tools/web_tests/release_navigation.cjs @@ -0,0 +1,7 @@ +// Release smoke runs at the pinned 1280x720 viewport on a fresh profile. +// Keep the actual title-menu pointer route shared by local and staged checks. +async function openSingleMissions(page) { + await page.locator('#launch').waitFor({ state: 'detached' }); + await page.mouse.click(640, 344, { delay: 80 }); +} +module.exports = { openSingleMissions }; diff --git a/tools/web_tests/sell.spec.cjs b/tools/web_tests/sell.spec.cjs new file mode 100644 index 00000000..b7bc0203 --- /dev/null +++ b/tools/web_tests/sell.spec.cjs @@ -0,0 +1,46 @@ +const { play } = require('./launch.cjs'); +const { test, expect } = require('@playwright/test'); +const state = page => page.evaluate(() => window.farlanding?.diagnostics); +async function click(page, prefix) { + await expect.poll(async () => (await state(page))?.buttons.some(b => b.text.startsWith(prefix))).toBe(true); + const button = (await state(page)).buttons.find(b => b.text.startsWith(prefix)); + await page.mouse.click(...button.pixel, { delay: 80 }); +} + +test('owned building sale previews refunds confirms and stays removed after saving', async ({ page }, info) => { + test.setTimeout(240000); + 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); + await click(page, 'GOT IT'); + const worker = (await state(page)).units.find(u => u.kind === 'concord_fabricator'); + await page.mouse.click(...worker.pixel, { delay: 80 }); + await click(page, 'Reactor'); + await expect.poll(async () => (await state(page)).placing).toBe(true); + await page.mouse.move(...(await state(page)).ground[0]); + await expect.poll(async () => (await state(page)).placement_reason).toBe(''); + await page.mouse.click(...(await state(page)).ground[0], { delay: 80 }); + await expect.poll(async () => (await state(page)).buildings.some(b => b.kind === 'concord_reactor' && !b.constructing), { timeout: 90000 }).toBe(true); + const reactor = (await state(page)).buildings.find(b => b.kind === 'concord_reactor'); + await page.mouse.click(...reactor.pixel, { delay: 80 }); + await click(page, 'SELL'); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('Confirm sell') && b.text.includes('+75 Alloy'))).toBe(true); + await page.screenshot({ path: info.outputPath('sell-confirmation.png') }); + await click(page, 'Cancel'); + expect((await state(page)).buildings.some(b => b.id === reactor.id)).toBe(true); + await click(page, 'SELL'); + const before = (await state(page)).stockpile; + await click(page, 'Confirm sell'); + await expect.poll(async () => (await state(page)).buildings.some(b => b.id === reactor.id)).toBe(false); + expect((await state(page)).stockpile.alloy).toBeGreaterThanOrEqual(before.alloy + 75); + expect((await state(page)).stockpile.power_produced).toBe(before.power_produced - 15); + await page.keyboard.press('k'); + await expect.poll(async () => (await state(page)).notice).toBe('Saved to Quicksave.'); + await page.keyboard.press('l'); + await expect.poll(async () => (await state(page)).notice).toContain('Loaded Quicksave'); + expect((await state(page)).buildings.some(b => b.id === reactor.id)).toBe(false); + const lander = (await state(page)).buildings.find(b => b.kind === 'concord_lander'); + await page.mouse.click(...lander.pixel, { delay: 80 }); + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith('Fabricator'))).toBe(true); + expect((await state(page)).buttons.some(b => b.text.startsWith('SELL'))).toBe(false); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); +});