Phase 0: save v12, persisted AI timers, strict damage block, simulated AIS

- Bump the save format to v12 (u-jagd-save-v12); every v11 save is rejected
  without migration. Remove the same-version v10/v11 upgrader chain, the
  legacy ESM v1/v2 and two-channel ECM restore paths.
- Declare exact save key sets in src/core/save_schema.py.
- Persist Sub._active_ping_cd and SurfaceShip torpedo-evasion state, which
  were silently reset on load and broke deterministic continuation.
- Validate the damage block exactly (keys, teams, bounded flood/fire).
- Add a simulated own-ship AIS receiver (ITU-R M.1371 class-A cadence,
  VHF line of sight). Radar observations of civilians no longer carry the
  true name and course (observation-boundary leak).
- Add src/core/detrand.py for stateless deterministic draws.
- Add tools/calibrate.py with golden 1.0.0 gameplay metrics and a test that
  keeps later physics phases within tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 13:16:05 +02:00
1 parent 3b3753cf4e
commit bd9260ba09
29 files changed
+1420 -728

No files matched your search

+5 -5
View File
@@ -2,7 +2,7 @@
## Authority and scope
- This is U-Jagd 1.0.0 (`src/core/version.py`); current saves are v11-only. Treat these as compatibility contracts, not changelog entries.
- This is U-Jagd 1.0.0 (`src/core/version.py`); current saves are v12-only. Treat these as compatibility contracts, not changelog entries.
- Resolve conflicts in this order: executable code and focused tests; packaged JSON/runtime resources; `pyproject.toml` and provenance/license notices; `README.md`; design/history documents under `docs/`. A plan or old comment is not an implementation contract.
- Preserve explicit compatibility tests and user data unless a task intentionally changes the contract. Add a regression test for behavior changes.
- Older phase/milestone labels under `docs/GDD.md`, `docs/implementation-plan.md`, `docs/plan-0.1.6.md`, and `docs/plan-0.1.7.md` are historical. Current resumable work is tracked in `docs/plan-0.1.8.md` and `docs/resume.md`.
@@ -54,8 +54,8 @@
## Persistence and user content
- Runtime root is `~/.u-jagd/`: `settings.json`; `slot1.json` through `slot5.json`; editor files in `missions/` and `units/`. Tests replace save paths with temporary directories; never write real user paths from tests. `.u-jagd/`, build products, caches, and egg metadata stay untracked.
- Preferences persist language/fullscreen/audio/large text/tooltips in `settings.json`; v11 saves also retain the mission's tooltip state. CLI `--windowed` and `--no-audio` override saved values for one launch; no inverse fullscreen or CLI-language switch exists.
- Write and load save v11 only. Require the exact `u-jagd-save-v11` schema and the complete current catalog, platform, ESM, ASW, and RNG state. Reject malformed, non-integer, older, newer, incomplete, or unknown schemas without migration.
- Preferences persist language/fullscreen/audio/large text/tooltips in `settings.json`; v12 saves also retain the mission's tooltip state. CLI `--windowed` and `--no-audio` override saved values for one launch; no inverse fullscreen or CLI-language switch exists.
- Write and load save v12 only. Require the exact `u-jagd-save-v12` schema (exact key sets live in `src/core/save_schema.py`) and the complete current catalog, platform, ESM, ASW, AIS, and RNG state. Reject malformed, non-integer, older, newer, incomplete, or unknown schemas without migration.
- Writes must stage beside the destination, flush and `fsync`, then atomically `os.replace`; failure leaves the prior file intact and save-and-quit quits only after success. Load into a candidate state and commit only after complete validation/restoration; failure must leave the live game and global ID counters unchanged.
- Treat imported/editor JSON as hostile. Require finite typed/bounded values, strict schemas, `user.<lowercase/digit/_/->` keys, confined destinations, and no symlinked root/file. Never interpret a logical reference as a filesystem path.
- Bundle import validates every item and collision before the first visible write, stages all files, rechecks confinement/symlinks, and rolls back the whole commit on failure. Preserve backups if rollback itself fails. JSON output must reject NaN/Infinity.
@@ -63,13 +63,13 @@
## Remote Crew multiplayer
- Remote Crew is authoritative-host multiplayer for multiple authenticated browser clients. The uConsole process remains the sole simulation authority. Browsers never run simulation, advance time, resolve physics, read live entities, or mutate game state from transport threads.
- Multiplayer protocol versions are independent of application and save versions. Remote Crew is protocol v2-only; every `/api/v1/*` route is retired and returns 404. Saves remain exact v11; credentials, clients, station leases, network queues, drafts, and unaccepted commands are transient and never enter saves or settings.
- Multiplayer protocol versions are independent of application and save versions. Remote Crew is protocol v2-only; every `/api/v1/*` route is retired and returns 404. Saves remain exact v12; credentials, clients, station leases, network queues, drafts, and unaccepted commands are transient and never enter saves or settings.
- Support a hard-bounded client count. Each client has an independent cryptographic session, expiry, request namespace, and revocation state. The host explicitly grants one exclusive station role per client and can revoke or take over any role. Reconnect never inherits another client's authority.
- Role capabilities are allowlisted. A granted browser may directly operate its station, including weapons when the host separately enables direct fire, but every action must pass the same observation freshness, damage, inventory, ROE, envelope, and readiness checks as local input. Save/load, reset, editors, options, quit, network administration, and credentials remain host-only, with one explicit exception: solo mode (below).
- Transport handlers accept only strict, finite, size-bounded, versioned messages and enqueue detached envelopes. The main thread revalidates client, role, lease generation, world epoch, resource revision, freshness, and readiness immediately before applying each command. Never synthesize Pygame events or dispatch arbitrary method names from network data.
- Apply accepted remote commands exactly once in deterministic station order and per-client FIFO order before `Game.update()`. Wall clock, packet scheduling, polling frequency, browser rendering, and hash iteration must not affect simulation results. Administrative transitions, pause, focus loss, role loss, disconnect, save/load, and world replacement reject unsafe queued commands and clear held remote controls.
- Each normal role view receives only an allowlisted detached projection of own ship and commanded assets, published observations, annotations, and known geography. Never export simulation objects, hidden IDs, undiscovered positions, true hostile identity, RNG state, or save dumps through station state. The explicit host-granted SimLog capability is the sole diagnostic exception: its read-only history may include detached full-truth snapshots, but never simulation objects, RNG state, credentials, settings, or save dumps.
- Solo mode is a per-launch, never-persisted host decision (`--solo-crew` or the F9 "Crew mode" row; changing it revokes every session and rotates the code). One paired session then holds all nine stations and may use the closed host command surface: pause/resume, time scale, save/load slots 1-5 and new game, sent as pseudo-role `host` over the normal command pipeline (same CSRF/Origin, exactly-once, phase and world-session checks; rejected in crew mode and while a host menu/overlay is open). Editors, options, quit, network administration and credentials stay host-only, saves stay exact v11, and a world replacement keeps the solo session but re-leases every station and drops queued commands. The browser runs on a desktop PC, so the web UI targets large screens; `data/commander/` keeps the accessible single-column fallback for narrow windows only.
- Solo mode is a per-launch, never-persisted host decision (`--solo-crew` or the F9 "Crew mode" row; changing it revokes every session and rotates the code). One paired session then holds all nine stations and may use the closed host command surface: pause/resume, time scale, save/load slots 1-5 and new game, sent as pseudo-role `host` over the normal command pipeline (same CSRF/Origin, exactly-once, phase and world-session checks; rejected in crew mode and while a host menu/overlay is open). Editors, options, quit, network administration and credentials stay host-only, saves stay exact v12, and a world replacement keeps the solo session but re-leases every station and drops queued commands. The browser runs on a desktop PC, so the web UI targets large screens; `data/commander/` keeps the accessible single-column fallback for narrow windows only.
- Browser sessions may use host-only HttpOnly SameSite cookies for reload recovery. Credentials never enter JavaScript, URLs, DOM, logs, settings, or saves. State-changing requests also require exact Origin and a separate CSRF token. Plain HTTP remains trusted-LAN-only; Internet-capable deployment requires a separately reviewed encrypted endpoint or reverse proxy.
- Keep clients, histories, queues, projections, polling, and render work bounded for the uConsole. Cache immutable projections shared by clients with identical visibility, apply backpressure, and verify maximum-client CPU, memory, bandwidth, frame time, reconnect, and thermal behavior on real hardware.
- New multiplayer prose uses exact EN/DE catalog parity and safe DOM insertion. Browser controls require keyboard and touch access, bounded responsive layouts, explicit stale/revoked states, and tests at desktop, mobile, large zoom, and pseudolocale where applicable.
+7 -6
View File
@@ -297,7 +297,7 @@ Die Einstellungen für Sprache, Vollbildmodus, Audio, Großschrift und
Kontexthinweise werden in `~/.u-jagd/settings.json` geschrieben. Der Zustand der
Kontexthinweise gilt daher global und wird für die deterministische
Wiederherstellung bestehender Sitzungen zusätzlich in Spielständen des Formats
v11 gespeichert.
v12 gespeichert.
## Commander-LAN-Koop
@@ -372,7 +372,7 @@ Beim Überfahren eines nicht verfügbaren Browser-Bedienelements erscheint der
aktuelle lokalisierte Grund, etwa fehlende Freigabe, Stationsschaden, Abklingzeit,
leerer Bestand, ausstehender Befehl oder die TAS-Fahrtgrenze.
Anwendungsversion **1.0.0**, API-Protokoll **v2** und Speicherformat **v11** sind
Anwendungsversion **1.0.0**, API-Protokoll **v2** und Speicherformat **v12** sind
voneinander unabhängige Kompatibilitätsverträge. Remote Crew verwendet
ausschließlich Protokoll v2; sämtliche Legacy-Routen unter `/api/v1/*` sind
entfernt und liefern 404.
@@ -424,11 +424,12 @@ Validiert bedeutet nicht, dass ein Wert zur Laufzeit wirksam ist. In Version
## Spielstände und Benutzerdaten
Version 1.0.0 schreibt und lädt ausschließlich das Speicherformat **v11**. V11
verlangt das exakte Schema `u-jagd-save-v11` einschließlich des aktuellen
Dieser Stand schreibt und lädt ausschließlich das Speicherformat **v12**. V12
verlangt das exakte Schema `u-jagd-save-v12` einschließlich des aktuellen
Schnappschusses des Laufzeitkatalogs und des gesamten Zustands für die
deterministische Fortsetzung. Ältere, neuere, fehlerhafte oder unvollständige
Spielstände werden abgelehnt, ohne das laufende Spiel zu ersetzen.
deterministische Fortsetzung. Ältere (auch alle v11-Spielstände von 1.0.0),
neuere, fehlerhafte oder unvollständige Spielstände werden ohne Migration
abgelehnt, ohne das laufende Spiel zu ersetzen.
Die fünf Speicherplätze sind `~/.u-jagd/slot1.json` bis `slot5.json`.
Spielstände enthalten einen Schnappschuss der Küstengeometrie und der
+6 -5
View File
@@ -282,7 +282,7 @@ between `en` and `de` and controls fullscreen, audio, large text, and tooltips.
Language, fullscreen, audio, large-text, and tooltip preferences are written to
`~/.u-jagd/settings.json`. Tooltip state is therefore global and is also stored
in v11 game saves for deterministic restoration of existing sessions.
in v12 game saves for deterministic restoration of existing sessions.
## Commander LAN Co-op
@@ -385,10 +385,11 @@ Validated does not mean runtime-effective. In release 1.0.0:
## Saves and User Data
Release 1.0.0 writes and loads save format **v11** only. V11 requires the exact
`u-jagd-save-v11` schema, including the current runtime catalog snapshot and all
deterministic continuation state. Older, newer, malformed, or incomplete saves
are rejected without replacing the running game.
This build writes and loads save format **v12** only. V12 requires the exact
`u-jagd-save-v12` schema, including the current runtime catalog snapshot and all
deterministic continuation state. Older (including every 1.0.0 v11 save),
newer, malformed, or incomplete saves are rejected without replacing the
running game; there is no migration.
The five slots are `~/.u-jagd/slot1.json` through `slot5.json`. Saves include a
snapshot of coastline geometry and synthetic bathymetry so an existing game is
+1 -1
View File
@@ -19,7 +19,7 @@ Seite 1 ist eine freie Karte über die volle Höhe mit allen veröffentlichten T
- **Überwasserradar:** 30 sm, begrenzt durch Radarhorizont (20-m-Mast) und Zielhöhe; getauchte U-Boote sind unsichtbar.
- **Luftradar:** 100 sm für Flugzeuge und Seezielflugkörper (ASM).
- Wetter verringert die Reichweite; ab Seegang 5 nehmen Clutter und Messfehler zu. Regen kostet weitere Reichweite.
- **AIS:** zivile Schiffe senden Identität und Position; optionaler Live-AIS/ADS-B-Verkehr ist von simuliertem Verkehr nicht unterscheidbar.
- **AIS:** zivile Schiffe senden Kurs und Fahrt alle 2-10 s (vor Anker alle 3 min) und ihren Namen etwa alle 6 min. Der UKW-Empfänger hört sie nur in Sichtlinie (etwa 20 NM). Ein Radartrack eines Zivilschiffs zeigt Name und Kurs erst, wenn die passende AIS-Meldung empfangen wurde; Radar allein liefert nur die Position. Optionaler Live-AIS/ADS-B-Verkehr ist von simuliertem Verkehr nicht unterscheidbar.
- **Fusion:** 2-8 Rohmeldungen markieren (`Leertaste`) und zu einem Bedienertrack fusionieren (`L`); `Shift+L` löst ihn auf.
- **Unterdrückung:** `Entf` blendet eine Meldung lokal aus; `H` zeigt unterdrückte Meldungen wieder.
+1 -1
View File
@@ -19,7 +19,7 @@ Page 1 is a full-height free chart with all published tracks; page 2 is the targ
- **Surface radar:** 30 NM, limited by the radar horizon (20 m mast) and target height; submerged submarines are invisible.
- **Air radar:** 100 NM for aircraft and anti-ship missiles (ASM).
- Weather reduces range; from sea state 5 clutter and measurement errors increase. Rain costs further range.
- **AIS:** civilian ships broadcast identity and position; optional live AIS/ADS-B traffic is indistinguishable from simulated traffic.
- **AIS:** civilian ships broadcast course and speed every 2-10 s (3 min at anchor) and their name about every 6 min. The VHF receiver hears them only within line of sight (about 20 NM). A radar track of a civilian shows name and course only after the matching AIS report has been received; radar alone gives position only. Optional live AIS/ADS-B traffic is indistinguishable from simulated traffic.
- **Fusion:** mark 2-8 raw reports (`Space`) and fuse them (`L`) into one operator track; `Shift+L` dissolves it.
- **Suppression:** `Delete` hides a report locally; `H` shows suppressed reports again.
+1 -1
View File
@@ -2,7 +2,7 @@
[English](commander-protocol.md)
Anwendung 1.0.0, API-Protokoll 2, ausschließlich Spielstandsformat v11. Diese
Anwendung 1.0.0, API-Protokoll 2, ausschließlich Spielstandsformat v12. Diese
Versionen sind voneinander unabhängig. Zugangsdaten, Netzwerksitzungen, Leases,
Befehlswarteschlangen oder Vorschläge werden nicht gespeichert. Gemeinsame
Anmerkungen und von der Besatzung angenommene Ziel-/Navigations-Sollwerte verwenden
+1 -1
View File
@@ -2,7 +2,7 @@
[Deutsch](commander-protocol.de.md)
Application 1.0.0, API protocol 2, save format v11-only. These versions are independent.
Application 1.0.0, API protocol 2, save format v12-only. These versions are independent.
No credentials, network sessions, leases, command queues or proposals are saved.
Shared annotations and crew-accepted target/navigation setpoints use normal game
persistence.
+5 -1
View File
@@ -1,5 +1,9 @@
# Simulation Realism Gap Analysis — U-Jagd 0.2.2
> **Status (physics upgrade, save v12):** rows are marked *Closed (Phase N)* as the
> phased upgrade on branch `sim-gaps-v12` lands. Calibration against the 1.0.0
> behaviour is enforced by `tools/calibrate.py --check` (`tests/calibration/`).
Analysis date: 2026-07-15
Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
@@ -306,7 +310,7 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| **No ECCM / jamming effect on radar** | Jamming only produces a HOJ bearing (bearing-only, no range) | Radar jamming: range-gate pull-off, angle deception, burn-through; radar self-protection |
| **ESM: no signal strength** | Detection is binary (in range or not); no amplitude | Signal level vs distance; frequency-agile waveform detection; dwell time |
| **HFDF: no frequency** | Only bearing; no frequency measurement | HF frequency → rough distance via ionospheric model; or at least frequency for emitter ID |
| **No AIS decoding** | AIS gives name/callsign but no MMSI, no SOG/COG from signal | AIS message types (position, SAR, vessel type); MMSI-based identity |
| ~~**No AIS decoding**~~ | **Closed (Phase 0).** `src/sensors/ais.py` is a simulated own-ship AIS receiver: ITU-R M.1371 class-A dynamic reports (COG/SOG every 2-10 s, 3 min at anchor) and static reports (name every 6 min), received only inside VHF line of sight and not through land. Radar observations of civilians no longer carry the true name/course (an observation-boundary leak); both come from the latest decoded report. MMSI is deliberately not shown to the player, so live and simulated traffic stay indistinguishable. Decoded reports are saved (save v12). | — |
| **Lookout: no silhouette / size** | Visual detection is a range gate; no target size effect | Target height, silhouette against sea/sky; searchlight; smoke |
### 8.3 Data structures touched
+59
View File
@@ -0,0 +1,59 @@
"""Stateless, counter-based deterministic randomness.
New simulation draws use these helpers instead of adding more mutable
``random.Random`` streams: a draw is a pure function of ``(seed, tag, key,
counter)``. Nothing has to be saved, the existing saved streams keep their
sequences, and the result never depends on hash randomization, wall clock,
render rate or evaluation order.
"""
from __future__ import annotations
import math
_MASK = (1 << 64) - 1
def _mix(value: int) -> int:
"""splitmix64 finalizer."""
value = (value + 0x9E3779B97F4A7C15) & _MASK
value = ((value ^ (value >> 30)) * 0xBF58476D1CE4E5B9) & _MASK
value = ((value ^ (value >> 27)) * 0x94D049BB133111EB) & _MASK
return value ^ (value >> 31)
def _tag_value(tag: str) -> int:
# FNV-1a 64 over UTF-8: stable across processes (unlike ``hash``).
value = 0xCBF29CE484222325
for byte in tag.encode("utf-8"):
value = ((value ^ byte) * 0x100000001B3) & _MASK
return value
def bits(seed: int, tag: str, *keys: int) -> int:
"""Return 64 deterministic bits for integer ``keys`` in stream ``tag``."""
value = _mix((int(seed) & _MASK) ^ _tag_value(tag))
for key in keys:
value = _mix(value ^ (int(key) & _MASK))
return value
def u01(seed: int, tag: str, *keys: int) -> float:
"""Uniform float in ``[0, 1)`` with 53 bits of resolution."""
return (bits(seed, tag, *keys) >> 11) * (1.0 / (1 << 53))
def uniform(low: float, high: float, seed: int, tag: str, *keys: int) -> float:
return low + (high - low) * u01(seed, tag, *keys)
def normal(seed: int, tag: str, *keys: int) -> float:
"""Standard normal draw (Box-Muller on two independent sub-draws)."""
u1 = max(u01(seed, tag, *keys, 1), 1e-300)
u2 = u01(seed, tag, *keys, 2)
return math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
def phase(seed: int, tag: str, *keys: int) -> float:
"""Deterministic phase in ``[0, 2*pi)``."""
return 2.0 * math.pi * u01(seed, tag, *keys)
+61 -560
View File
@@ -35,6 +35,10 @@ from src.core.mission import Mission
from src.core.mission_definition import static_preview, validate_mission
from src.core.station import Station
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.sensors.ais import AISReceiver
from src.core.save_schema import (
COMPARTMENT_FIELDS, COMPARTMENT_STATES, DAMAGE_FIELDS, RNG_STREAMS,
SAVE_ROOT_FIELDS, SHIP_FIELDS, WORLD_FIELDS)
from src.data import fingerprint as fingerprint_mod
from src.data.catalog import CATALOG, EmitterProfile, catalog_from_runtime_snapshot
from src.enemies.animal import Animal
@@ -143,22 +147,6 @@ SONAR_BAND_PRESETS = {
"SHAFT": (8.0, 55.0),
"MID": (20.0, 120.0),
}
SAVE_ROOT_FIELDS = {
"version", "save_schema", "platform_state_version", "catalog_snapshot",
"seed", "level", "mission_type", "scenario_key", "mission_name",
"mission_runtime", "world", "sim_t", "mission_time", "time_scale_idx",
"score", "mission_result", "result_reason", "ship", "torpedoes",
"chaff_cd", "vls_cells", "ciws_ammo", "roe", "sonar_mode", "radars",
"asm_sel", "radio_sel", "hq_timer", "damage", "dmg_cursor", "dmg_team",
"incident", "subs", "animals", "civilians", "warships", "decoys",
"torpedoes_in_flight", "enemy_torpedoes", "asw", "air_defense", "asms", "essms",
"buoys", "helo", "flights", "sonar_controls", "sonar", "messages",
"hfdf_fixes", "hfdf_log", "radio_picture", "air_picture",
"opz_affiliations", "air_threat_reported", "esm", "next_entity_ids",
"asm_spawned", "asm_seq", "warship_asm_seq", "torpedo_seq", "buoy_seq",
"ciws_cooldown_s", "schedulers", "rngs", "ui",
"autocrew",
}
def _read_save_document(path):
@@ -635,6 +623,7 @@ class Game:
self.asm_sel = 0
self.air_picture = TrackPicture(
config.RADAR_TRACK_STALE_S, maximum=MAX_AIR_PICTURE_TRACKS)
self.ais = AISReceiver(seed)
self.opz_selected_track_id = None
self.opz_contact_filter = "ALL"
self.opz_affiliations = {}
@@ -3730,6 +3719,7 @@ class Game:
air_live = self.air_radar_on and station_live
surface_eff = self.radar_effective_range("surface")
air_eff = self.radar_effective_range("air")
self.ais.update(self.sim_t, self.civilians, self.ship, self.world)
error_scale = 1.0 + (config.RADAR_WEATHER_ERROR_GAIN
* self.radar_weather_severity()
+ config.RADAR_RAIN_ERROR_GAIN
@@ -3752,10 +3742,13 @@ class Game:
range_error = config.RADAR_RANGE_ERR_FRAC * error_scale
measured = max(0.0, dist * (1.0 + rng.uniform(
-range_error, range_error)))
# Radar measures position only. Name and course of a civilian
# are known only from AIS reports the receiver has decoded.
self.air_picture.observe(track_id=f"S-{c.id}", kind="SURFACE",
target_id=c.id, source="RADAR-S", bearing=brg,
range_nm=measured, observer_x=self.ship.x, observer_y=self.ship.y,
course=c.course, quality=.95, now=self.sim_t, label=c.name,
course=self.ais.course_for(c.id, self.sim_t), quality=.95,
now=self.sim_t, label=self.ais.label_for(c.id) or f"S-{c.id}",
bearing_uncertainty_deg=bearing_error / math.sqrt(3.0))
for w in self.warships:
if w.sunk:
@@ -6523,6 +6516,7 @@ class Game:
key: max(cls._next_id, max((e.id + 1 for e in entities), default=0))
for key, (cls, entities) in entity_groups.items()},
"autocrew": self.autocrew.serialize(),
"ais": self.ais.serialize(),
"seed": self.seed,
"mission_type": self.mission.type_key,
"mission_time": self.mission_time,
@@ -6692,6 +6686,7 @@ class Game:
fingerprint=s.fingerprint.to_dict(),
torpedo_alerted=s.torpedo_alerted,
decoy_cd=s._decoy_cd,
active_ping_cd=s._active_ping_cd,
turn_left=s.turn_left, turn_delta=s.turn_delta,
target_course=s.target_course,
target_depth=s.target_depth,
@@ -6728,6 +6723,8 @@ class Game:
sensor_contact=c.sensor_contact,
sensor_contact_age=c.sensor_contact_age,
sunk_score_awarded=c.sunk_score_awarded,
torpedo_evade_left=c._torpedo_evade_left,
torpedo_threat_bearing=c._torpedo_threat_bearing,
sensor_seed=c.sensor_seed,
fingerprint=c.fingerprint.to_dict(),
platform=c.sensor_suite.serialize())
@@ -6745,6 +6742,8 @@ class Game:
sensor_contact=w.sensor_contact,
sensor_contact_age=w.sensor_contact_age,
sunk_score_awarded=w.sunk_score_awarded,
torpedo_evade_left=w._torpedo_evade_left,
torpedo_threat_bearing=w._torpedo_threat_bearing,
pending_asm=list(w.pending_asm),
asroc_battery=(w.asroc_battery.serialize()
if w.asroc_battery is not None
@@ -7167,6 +7166,8 @@ class Game:
self.air_picture = TrackPicture(
config.RADAR_TRACK_STALE_S, maximum=MAX_AIR_PICTURE_TRACKS)
self.air_picture.restore(data["air_picture"])
self.ais = AISReceiver(data["seed"])
self.ais.restore(data["ais"])
self._raider_visible_last = any(
track.track_id.startswith("R-")
for track in self.air_picture.tracks(self.sim_t, ("FLG",)))
@@ -7181,10 +7182,9 @@ class Game:
self.eloka_annotations = {}
esm = data["esm"]
self.esm_picture.restore(esm["picture"], esm["track_seq"], self.sim_t)
if esm["version"] in (2, ESM_STATE_VERSION):
self.ecm_jammer.restore(esm["ecm"], {
track.track_key for track in self.esm_picture.tracks(self.sim_t)},
self.sim_t, version=esm["version"])
self.ecm_jammer.restore(esm["ecm"], {
track.track_key for track in self.esm_picture.tracks(self.sim_t)},
self.sim_t)
self.eloka_selected_track_key = esm["selected_track_key"]
self.eloka_annotations = {
row["track_key"]: row["emitter_key"]
@@ -7282,6 +7282,7 @@ class Game:
s.attack_left = sd["attack_left"]
s.torpedo_alerted = sd["torpedo_alerted"]
s._decoy_cd = sd["decoy_cd"]
s._active_ping_cd = sd["active_ping_cd"]
s.turn_left = sd["turn_left"]
s.turn_delta = sd["turn_delta"]
s.target_course = sd["target_course"]
@@ -7348,6 +7349,8 @@ class Game:
if cd["sensor_contact"] is not None else None)
c.sensor_contact_age = cd["sensor_contact_age"]
c.sunk_score_awarded = cd["sunk_score_awarded"]
c._torpedo_evade_left = cd["torpedo_evade_left"]
c._torpedo_threat_bearing = cd["torpedo_threat_bearing"]
c.sensor_seed = cd["sensor_seed"]
c.fingerprint = fingerprint_mod.Fingerprint.from_dict(
cd["fingerprint"])
@@ -7380,6 +7383,8 @@ class Game:
if wd["sensor_contact"] is not None else None)
w.sensor_contact_age = wd["sensor_contact_age"]
w.sunk_score_awarded = wd["sunk_score_awarded"]
w._torpedo_evade_left = wd["torpedo_evade_left"]
w._torpedo_threat_bearing = wd["torpedo_threat_bearing"]
w.pending_asm = [tuple(row) for row in wd["pending_asm"]]
if wd["asroc_battery"] is not None:
w.asroc_battery = WeaponBattery.restore(wd["asroc_battery"])
@@ -7738,7 +7743,7 @@ class Game:
data = _read_save_document(path)
except (OSError, ValueError, RecursionError):
return False
return self._load_save_data(data, allow_pre_r9=True)
return self._load_save_data(data)
@staticmethod
def _catalog_for_save(data):
@@ -7747,458 +7752,6 @@ class Game:
raise ValueError("unsupported save version")
return catalog_from_runtime_snapshot(data["catalog_snapshot"])
@staticmethod
def _upgrade_pre_r9_v10(data):
"""Upgrade only the exact R8 v10 shape that existed before R9."""
if not isinstance(data, dict) or "air_defense" in data:
return data
if set(data) not in (SAVE_ROOT_FIELDS - {"air_defense"},
SAVE_ROOT_FIELDS - {"air_defense", "autocrew"}):
return data
old_asm = {"x", "y", "course", "seq", "state", "jammer", "age_s",
"travel", "chaff_left", "broken"}
old_essm = {"x", "y", "course", "seq", "state", "travel",
"guidance_x", "guidance_y", "track_target_id",
"seeker_acquired", "target_id"}
if (not isinstance(data.get("asms"), list)
or not isinstance(data.get("essms"), list)
or any(not isinstance(row, dict) or set(row) != old_asm
for row in data["asms"])
or any(not isinstance(row, dict) or set(row) != old_essm
for row in data["essms"])):
return data
upgraded = copy.deepcopy(data)
loadout = copy.deepcopy(air_defense_loadout())
store = make_softkill_store(loadout)
cooldown = upgraded.get("chaff_cd")
if isinstance(cooldown, (int, float)) and not isinstance(cooldown, bool) \
and math.isfinite(cooldown) and cooldown > 0.0:
store.fire()
store.loading = [float(cooldown)]
spent = loadout["vls"]["sam_loadout"] - upgraded.get("vls_cells", -1)
upgraded["air_defense"] = {
"version": AIR_DEFENSE_STATE_VERSION,
"loadout": loadout,
"sam_remaining": upgraded.get("vls_cells"),
"essm_seq": spent,
"softkill": store.serialize(),
"aa_ammo": loadout["aa_gun"]["ammo"],
"aa_cooldown_s": 0.0,
"raiders": [],
"raider_seq": 0,
"waves_spawned": 0,
}
for row in upgraded["asms"]:
row["profile_key"] = loadout["asm"]["key"]
for row in upgraded["essms"]:
row["profile_key"] = loadout["sam"]["key"]
import random
upgraded["rngs"]["raid"] = Game._rng_state(
random.Random(upgraded.get("seed", 0) + 40424))
return upgraded
@staticmethod
def _upgrade_pre_r14_v10(data):
"""Upgrade only the exact canonical R13 sonar sub-shape."""
controls_fields = {"gain_db", "band_low_hz", "band_high_hz",
"notch_enabled", "peak_hold", "focus_locked",
"tma_enabled", "listen_bearing", "listen_filtered",
"sonar_page", "audio_enabled", "volume"}
controls = data.get("sonar_controls") if isinstance(data, dict) else None
sonar = data.get("sonar") if isinstance(data, dict) else None
contacts = sonar.get("contacts") if isinstance(sonar, dict) else None
if (not isinstance(controls, dict) or set(controls) != controls_fields
or not isinstance(contacts, dict)
or any(not isinstance(contact, dict) or "fixes" in contact
for contact in contacts.values())):
return data
upgraded = copy.deepcopy(data)
controls = upgraded["sonar_controls"]
controls["audition_mode"] = ("FILTERED" if controls["listen_filtered"]
else "BROADBAND")
for contact in upgraded["sonar"]["contacts"].values():
fixes = []
source = contact.get("range_source")
x, y, measured = (contact.get("observed_x"), contact.get("observed_y"),
contact.get("range_seen"))
if source in ("ping", "tma", "buoy") and None not in (x, y, measured):
fixes.append(dict(
source={"ping": "PING", "tma": "TMA",
"buoy": "SONOBUOY"}[source],
measured_at=measured, fixed_at=measured, x=x, y=y,
uncertainty_nm=contact.get("range_sigma_nm") or .1,
depth_m=contact.get("depth_est") if source == "ping" else None,
depth_uncertainty_m=(contact.get("depth_sigma_m")
if source == "ping" else None),
quality=contact.get("quality", 0.0)))
contact["fixes"] = fixes
return upgraded
@staticmethod
def _upgrade_pre_r16_v10(data):
"""Upgrade only the exact canonical R15 endurance-free save shape."""
if (not isinstance(data, dict) or set(data) not in (
SAVE_ROOT_FIELDS, SAVE_ROOT_FIELDS - {"autocrew"})):
return data
subs = data.get("subs")
prior_sub_fields = {
"id", "x", "y", "depth", "course", "state", "speed", "damage",
"torpedoes_left", "heard_ping", "asw_battery",
"countermeasure_store", "stype", "start_pos", "evac_left",
"sink_left", "quiet_mult", "attack_mult", "attack_cooldown",
"attack_left", "fingerprint", "torpedo_alerted", "decoy_cd",
"turn_left", "turn_delta", "target_course", "target_depth",
"evade_offset", "sensor_seed", "memory", "pending_torpedoes",
"pending_decoys", "decision_reason", "platform",
}
if (not isinstance(subs, list)
or any(not isinstance(row, dict) or set(row) != prior_sub_fields
for row in subs)):
return data
snapshot = data.get("catalog_snapshot")
current_snapshot = CATALOG.runtime_snapshot()
prior_snapshot = copy.deepcopy(current_snapshot)
for component in prior_snapshot["components"].values():
del component["endurances"]
if not _same_save_value_strict(snapshot, prior_snapshot):
return data
upgraded = copy.deepcopy(data)
upgraded["catalog_snapshot"] = current_snapshot
for row in upgraded["subs"]:
profile = CATALOG.endurances.get(f"endurance.{row['stype']}")
endurance = (SubmarineEndurance(profile)
if profile is not None else None)
if row["state"] == "SNOCKEL" and endurance is not None:
endurance.phase = "RADIO"
endurance.return_depth_m = max(
row["depth"], endurance.profile.snorkel_depth_m)
endurance.radio_left_s = float(row["evac_left"])
row["state"] = "PATROLLE"
row["evac_left"] = 0.0
row["endurance"] = (endurance.serialize()
if endurance is not None else None)
return upgraded
@staticmethod
def _upgrade_pre_r18_v10(data):
"""Upgrade only the exact canonical same-v10 pre-grounding ship shape."""
old_ship_fields = {
"x", "y", "course", "target_course", "speed", "target_speed",
"order_idx", "turn_rate_scale", "rudder_angle", "yaw_rate",
"roll", "pitch", "quiet_mode", "clock",
}
if (not isinstance(data, dict) or set(data) not in (
SAVE_ROOT_FIELDS, SAVE_ROOT_FIELDS - {"autocrew"})
or not isinstance(data.get("ship"), dict)
or set(data["ship"]) != old_ship_fields):
return data
ship = data["ship"]
pose = [ship.get("x"), ship.get("y"), ship.get("course")]
if any(type(value) not in (int, float) or isinstance(value, bool)
or not math.isfinite(value) for value in pose):
return data
upgraded = copy.deepcopy(data)
upgraded["ship"].update(
astern=False, hull=DEFAULT_HULL_SPEC.to_dict(),
grounding={"latched": False, "last_safe_pose": pose,
"contact": None})
return upgraded
@staticmethod
def _upgrade_pre_r20_v10(data):
"""Upgrade only the exact canonical same-v10 pre-raid shape.
Pre-raid saves hold an air_defense state version 1 whose embedded
loadout is version 1 (no raider/aa_gun) and an rngs map without the
raid stream. Everything else stays untouched.
"""
if not isinstance(data, dict):
return data
air = data.get("air_defense")
loadout = air.get("loadout") if isinstance(air, dict) else None
old_state_fields = {"version", "loadout", "sam_remaining",
"essm_seq", "softkill"}
old_loadout_fields = {"version", "asm", "sam", "vls", "ciws",
"softkill"}
if (not isinstance(air, dict) or set(air) != old_state_fields
or air.get("version") != 1
or not isinstance(loadout, dict)
or set(loadout) != old_loadout_fields
or loadout.get("version") != 1):
return data
rngs = data.get("rngs")
if (not isinstance(rngs, dict) or "raid" in rngs
or set(rngs) != {"world", "world_weather", "asm", "damage",
"helo", "sonar", "flight", "asw"}):
return data
import random
current = air_defense_loadout()
upgraded = copy.deepcopy(data)
upgraded["air_defense"]["loadout"].update(
raider=copy.deepcopy(current["raider"]),
aa_gun=copy.deepcopy(current["aa_gun"]))
upgraded["air_defense"]["loadout"]["version"] = 2
upgraded["air_defense"].update(
version=AIR_DEFENSE_STATE_VERSION,
aa_ammo=current["aa_gun"]["ammo"], aa_cooldown_s=0.0,
raiders=[], raider_seq=0, waves_spawned=0)
upgraded["rngs"]["raid"] = Game._rng_state(
random.Random(upgraded.get("seed", 0) + 40424))
return upgraded
@staticmethod
def _upgrade_pre_dipping_v10(data):
"""Upgrade only the exact pre-dipping/release canonical v10 sub-shapes."""
if (not isinstance(data, dict) or set(data) not in (
SAVE_ROOT_FIELDS, SAVE_ROOT_FIELDS - {"autocrew"})):
return data
old_helo_fields = {
"state", "x", "y", "torpedo_profile_key", "course", "torps",
"buoys_left", "fuel_s", "waypoint_x", "waypoint_y",
}
old_contact_fields = {
"contact_id", "target_id", "origin", "kind", "bearing",
"range_est", "range_sigma_nm", "range_source", "range_seen",
"confidence", "quality", "last_seen", "depth_est",
"depth_sigma_m", "player_class", "signature", "snr",
"passive_bearing", "raw_bearing", "raw_bearings", "passive_epoch",
"bearing_filter_t", "bearing_filter_rate_deg_s",
"bearing_filter_uncertainty_deg", "bearing_uncertainty_deg",
"ping_pos", "observed_x", "observed_y", "array_observations",
"fusion_status", "fusion_delta_deg", "fused_quality", "tma_pos",
"tma_course", "tma_speed", "tma_quality", "tma_seen",
"buoy_fixes", "fixes",
}
helo = data.get("helo")
sonar = data.get("sonar")
contacts = sonar.get("contacts") if isinstance(sonar, dict) else None
if (not isinstance(helo, dict) or set(helo) != old_helo_fields
or not isinstance(contacts, dict)
or any(not isinstance(row, dict) or set(row) != old_contact_fields
for row in contacts.values())):
return data
upgraded = copy.deepcopy(data)
upgraded["helo"].update(
dip_state="STOWED", dip_depth_m=0.0,
dip_depth_target_m=config.HELO_DIP_DEPTH_DEFAULT_M,
dip_water_depth_m=0.0, dip_ping_cooldown=0.0)
observer_x = upgraded["ship"]["x"]
observer_y = upgraded["ship"]["y"]
for contact in upgraded["sonar"]["contacts"].values():
contact.update(
released_to_opz=contact.get("player_class") in config.PLAYER_CLASSES,
passive_source="SONAR-BRG", observer_x=observer_x,
observer_y=observer_y)
return upgraded
@staticmethod
def _upgrade_pre_ownship_fuel_v10(data):
"""Upgrade only the exact canonical same-v10 pre-fuel ship shape."""
old_ship_fields = {
"x", "y", "course", "target_course", "speed", "target_speed",
"order_idx", "astern", "hull", "grounding", "turn_rate_scale",
"rudder_angle", "yaw_rate", "roll", "pitch", "quiet_mode", "clock",
}
if (not isinstance(data, dict) or set(data) not in (
SAVE_ROOT_FIELDS, SAVE_ROOT_FIELDS - {"autocrew"})
or not isinstance(data.get("ship"), dict)
or set(data["ship"]) != old_ship_fields):
return data
upgraded = copy.deepcopy(data)
upgraded["ship"].update(
fuel_capacity_kg=config.SHIP_FUEL_CAPACITY_KG,
fuel_kg=config.SHIP_FUEL_CAPACITY_KG)
return upgraded
@staticmethod
def _upgrade_pre_autocrew_v10(data):
"""Upgrade only the exact canonical same-v10 pre-Autocrew root shape."""
if (not isinstance(data, dict)
or set(data) != SAVE_ROOT_FIELDS - {"autocrew"}):
return data
upgraded = copy.deepcopy(data)
upgraded["autocrew"] = AutocrewController().serialize()
return upgraded
@staticmethod
def _upgrade_pre_helo_dip_bearing_v10(data):
"""Upgrade only the exact canonical same-v10 pre-dip-bearing shape.
W2: adds the helicopter's own independent dip-passive bearing track
(dip_bearing/dip_bearing_uncertainty_deg/dip_last_seen/
dip_observer_x/dip_observer_y), which used to share state with the
ship's own passive_bearing/observer_x/observer_y - the reported bug
where a helicopter dip silently overwrote the frigate's own bearing.
"""
old_contact_fields = {
"contact_id", "target_id", "origin", "kind", "bearing",
"range_est", "range_sigma_nm", "range_source", "range_seen",
"confidence", "quality", "last_seen", "depth_est",
"depth_sigma_m", "player_class", "signature", "snr",
"passive_bearing", "raw_bearing", "raw_bearings", "passive_epoch",
"bearing_filter_t", "bearing_filter_rate_deg_s",
"bearing_filter_uncertainty_deg", "bearing_uncertainty_deg",
"ping_pos", "observed_x", "observed_y", "array_observations",
"fusion_status", "fusion_delta_deg", "fused_quality", "tma_pos",
"tma_course", "tma_speed", "tma_quality", "tma_seen",
"buoy_fixes", "fixes", "released_to_opz", "passive_source",
"observer_x", "observer_y",
}
if not isinstance(data, dict):
return data
sonar = data.get("sonar")
contacts = sonar.get("contacts") if isinstance(sonar, dict) else None
if (not isinstance(contacts, dict)
or any(not isinstance(row, dict) or set(row) != old_contact_fields
for row in contacts.values())):
return data
upgraded = copy.deepcopy(data)
for contact in upgraded["sonar"]["contacts"].values():
contact.update(dip_bearing=None, dip_bearing_uncertainty_deg=None,
dip_last_seen=None, dip_observer_x=None,
dip_observer_y=None)
return upgraded
@staticmethod
def _upgrade_pre_dip_release_v10(data):
"""Canonicalize exact earlier rows without independent sensor origins."""
if not isinstance(data, dict):
return data
sonar = data.get("sonar")
contacts = sonar.get("contacts") if isinstance(sonar, dict) else None
if not isinstance(contacts, dict) or not contacts:
return data
current_fields = {
"contact_id", "target_id", "origin", "kind", "bearing",
"range_est", "range_sigma_nm", "range_source", "range_seen",
"confidence", "quality", "last_seen", "depth_est",
"depth_sigma_m", "player_class", "signature", "snr",
"passive_bearing", "raw_bearing", "raw_bearings", "passive_epoch",
"bearing_filter_t", "bearing_filter_rate_deg_s",
"bearing_filter_uncertainty_deg", "bearing_uncertainty_deg",
"ping_pos", "observed_x", "observed_y", "array_observations",
"fusion_status", "fusion_delta_deg", "fused_quality", "tma_pos",
"tma_course", "tma_speed", "tma_quality", "tma_seen",
"buoy_fixes", "fixes", "released_to_opz", "passive_source",
"observer_x", "observer_y", "dip_bearing",
"dip_bearing_uncertainty_deg", "dip_last_seen",
"dip_observer_x", "dip_observer_y",
}
# The existing upgrader above has supplied the five dip measurement
# fields. Earlier rows lack the separate release and ship-origin fields.
if (any(not isinstance(row, dict) or set(row) not in (
current_fields, current_fields | {"dip_released_to_opz"})
for row in contacts.values())):
return data
upgraded = copy.deepcopy(data)
for row in upgraded["sonar"]["contacts"].values():
row.setdefault("dip_released_to_opz", False)
row["ship_observer_x"] = row["observer_x"] if row["passive_bearing"] is not None else None
row["ship_observer_y"] = row["observer_y"] if row["passive_bearing"] is not None else None
return upgraded
@staticmethod
def _upgrade_pre_torpedo_spoolup_v10(data):
"""Upgrade only the exact canonical pre-launch-ramp torpedo rows.
W2: adds `time_since_launch`, used for a short deterministic
motor-spoolup ramp at launch. Legacy in-flight torpedoes are treated
as already at cruise speed (the pre-existing behaviour).
"""
old_player_fields = {
"x", "y", "course", "depth", "travel", "state", "idx",
"target_depth", "target_id", "speed_kn", "range_nm",
"terminal_active", "guidance_x", "guidance_y", "seeker_acquired",
"profile_key", "launch_origin", "launch_platform_id",
"launch_weapon_key", "search_phase", "midcourse",
"midcourse_timer", "kill_dist_nm", "kill_depth_m",
}
old_enemy_fields = {
"id", "x", "y", "course", "depth", "travel", "idx", "profile_key",
"guidance_x", "guidance_y", "terminal_active", "seeker_acquired",
"launch_platform_id", "launch_weapon_key", "seeker_target",
}
if not isinstance(data, dict):
return data
player_rows = data.get("torpedoes_in_flight")
enemy_rows = data.get("enemy_torpedoes")
if (not isinstance(player_rows, list)
or any(not isinstance(row, dict) or set(row) != old_player_fields
for row in player_rows)
or not isinstance(enemy_rows, list)
or any(not isinstance(row, dict) or set(row) != old_enemy_fields
for row in enemy_rows)):
return data
upgraded = copy.deepcopy(data)
for row in upgraded["torpedoes_in_flight"]:
row["time_since_launch"] = config.TORP_SPOOLUP_S
for row in upgraded["enemy_torpedoes"]:
row["time_since_launch"] = config.TORP_SPOOLUP_S
return upgraded
@staticmethod
def _upgrade_pre_depth_inertia_v10(data):
"""Upgrade only the exact canonical pre-depth-inertia sub rows.
W2: adds `depth_rate_mps`, the signed vertical rate carried between
ticks for the acceleration-limited depth approach. Legacy subs
backfill to 0.0 (stationary vertical rate) - equivalent to how the
old linear-rate model always started a fresh clamp each tick.
"""
old_sub_fields = {
"id", "x", "y", "depth", "course", "state", "speed", "damage",
"torpedoes_left", "heard_ping", "asw_battery",
"countermeasure_store", "stype", "start_pos", "evac_left",
"sink_left", "quiet_mult", "attack_mult", "attack_cooldown",
"attack_left", "fingerprint", "torpedo_alerted", "decoy_cd",
"turn_left", "turn_delta", "target_course", "target_depth",
"evade_offset", "sensor_seed", "memory", "pending_torpedoes",
"pending_decoys", "decision_reason", "endurance", "platform",
}
if not isinstance(data, dict):
return data
rows = data.get("subs")
if (not isinstance(rows, list)
or any(not isinstance(row, dict) or set(row) != old_sub_fields
for row in rows)):
return data
upgraded = copy.deepcopy(data)
for row in upgraded["subs"]:
row["depth_rate_mps"] = 0.0
return upgraded
@staticmethod
def _upgrade_pre_opz_map_current_save(data):
"""Add the optional native-OPZ camera to an otherwise current save UI."""
if not isinstance(data, dict) or not isinstance(data.get("ui"), dict):
return data
ui = data["ui"]
fields = {"opz_map_cx", "opz_map_cy", "opz_map_scale",
"opz_map_follow"}
if fields & set(ui):
return data
ship = data.get("ship")
if not isinstance(ship, dict):
return data
chart = opz_ppi_rect(config.OPZ_STATION_RECT)
world = data.get("world")
coast = world.get("coast") if isinstance(world, dict) else None
world_size = (coast.get("world_nm") if isinstance(coast, dict)
else config.WORLD_SIZE_NM)
default_scale = min(chart.w, chart.h) / (
2.0 * config.OPZ_MAP_DEFAULT_RADIUS_NM)
if isinstance(world_size, (int, float)) and not isinstance(world_size, bool) \
and math.isfinite(world_size) and world_size > 0.0:
default_scale = max(default_scale,
min(chart.w, chart.h) / world_size)
upgraded = copy.deepcopy(data)
upgraded["ui"].update(
opz_map_cx=ship.get("x"), opz_map_cy=ship.get("y"),
opz_map_scale=default_scale,
opz_map_follow=True)
return upgraded
@staticmethod
def _valid_save_document(data, runtime_catalog=None) -> bool:
def finite_number(value) -> bool:
@@ -8237,6 +7790,11 @@ class Game:
return False
if set(data) != SAVE_ROOT_FIELDS:
return False
if not AISReceiver.valid_state(
data.get("ais"), data.get("sim_t"),
{row.get("id") for row in data.get("civilians", ())
if isinstance(row, dict)}):
return False
if not AutocrewController.valid_state(data.get("autocrew"), data.get("sim_t")):
return False
controls = data.get("sonar_controls")
@@ -8344,11 +7902,7 @@ class Game:
chaff_cd=data.get("chaff_cd"))):
return False
rng_data = data.get("rngs")
rng_keys = {
"world", "world_weather", "asm", "damage", "helo", "sonar",
"flight", "asw", "raid",
}
if not isinstance(rng_data, dict) or set(rng_data) != rng_keys:
if not isinstance(rng_data, dict) or set(rng_data) != RNG_STREAMS:
return False
for raw_rng in rng_data.values():
try:
@@ -8478,13 +8032,7 @@ class Game:
for track_id, value in affiliations.items())):
return False
ship = data.get("ship")
ship_fields = {
"x", "y", "course", "target_course", "speed", "target_speed",
"order_idx", "astern", "hull", "grounding", "turn_rate_scale",
"rudder_angle", "yaw_rate", "roll", "pitch", "quiet_mode", "clock",
"fuel_capacity_kg", "fuel_kg",
}
if not isinstance(ship, dict) or set(ship) != ship_fields:
if not isinstance(ship, dict) or set(ship) != SHIP_FIELDS:
return False
radars = data.get("radars")
if (not isinstance(radars, dict)
@@ -8539,22 +8087,26 @@ class Game:
from src.ship.damage import COMPARTMENTS
compartment_keys = {key for key, _ in COMPARTMENTS}
damage = data.get("damage")
if not isinstance(damage, dict):
if not isinstance(damage, dict) or set(damage) != DAMAGE_FIELDS:
return False
teams = damage.get("teams")
compartments = damage.get("compartments")
teams = damage["teams"]
compartments = damage["compartments"]
if not isinstance(teams, dict) or not isinstance(compartments, dict):
return False
if any(key not in {str(i) for i in range(1, DamageModel.TEAM_COUNT + 1)}
or (room is not None and (not isinstance(room, str)
or room not in compartment_keys))
for key, room in teams.items()):
if not bounded(damage["repair_mult"], 0.1, 10.0):
return False
if any(key not in compartment_keys or not isinstance(room, dict)
or room.get("state") not in ("OK", "FLUTEND", "BESCHAEDIGT", "ZERSTOERT")
or not bounded(room.get("flood"), 0, 1000)
or not bounded(room.get("fire", 0), 0, 1000)
for key, room in compartments.items()):
if (set(teams) != {str(i) for i in range(1, DamageModel.TEAM_COUNT + 1)}
or any(room is not None and (not isinstance(room, str)
or room not in compartment_keys)
for room in teams.values())):
return False
if set(compartments) != compartment_keys or any(
not isinstance(room, dict) or set(room) != COMPARTMENT_FIELDS
or room["state"] not in COMPARTMENT_STATES
or not bounded(room["flood"], 0, config.DMG_DESTROY_FLOOD)
# A lethal fire may overshoot the kill threshold by one step.
or not bounded(room["fire"], 0, config.DMG_FIRE_KILL + 5.0)
for room in compartments.values()):
return False
groups = {"sub": ("subs",), "animal": ("animals",),
@@ -8724,6 +8276,11 @@ class Game:
awarded = entry.get("sunk_score_awarded", False)
if type(awarded) is not bool or (awarded and not entry.get("sunk", False)):
return False
if (not bounded(entry.get("torpedo_evade_left"), 0.0,
config.WARSHIP_TORPEDO_EVADE_S)
or not bounded(entry.get("torpedo_threat_bearing"),
0.0, 359.999999999)):
return False
if name == "warships":
if not {
"asroc_battery", "pending_asroc",
@@ -8800,6 +8357,9 @@ class Game:
"asw_battery", "countermeasure_store",
"endurance"} <= set(entry):
return False
if not bounded(entry.get("active_ping_cd"), 0.0,
config.SUB_ACTIVE_PING_COOLDOWN_S):
return False
endurance_profile = runtime_catalog.endurances.get(
f"endurance.{profile_key}")
endurance_state = entry.get("endurance")
@@ -9272,9 +8832,7 @@ class Game:
"sam_loadout"] - data["vls_cells"]):
return False
world = data.get("world")
world_fields = {"hour", "sea_state", "weather_shift_timer", "mode",
"generator", "coast"}
if (not isinstance(world, dict) or set(world) != world_fields
if (not isinstance(world, dict) or set(world) != WORLD_FIELDS
or world["mode"] not in ("fixed", "procedural", "real_fixed")
or world["generator"] != (
"natural-earth-v1" if world["mode"] in ("procedural", "real_fixed")
@@ -9611,40 +9169,8 @@ class Game:
return False
return True
def _load_save_data(self, data: dict, *, allow_pre_r9: bool = False) -> bool:
def _load_save_data(self, data: dict) -> bool:
try:
if allow_pre_r9:
data = self._upgrade_pre_r9_v10(data)
data = self._upgrade_pre_r14_v10(data)
data = self._upgrade_pre_r16_v10(data)
data = self._upgrade_pre_r18_v10(data)
data = self._upgrade_pre_r20_v10(data)
data = self._upgrade_pre_dipping_v10(data)
data = self._upgrade_pre_ownship_fuel_v10(data)
data = self._upgrade_pre_autocrew_v10(data)
data = self._upgrade_pre_helo_dip_bearing_v10(data)
data = self._upgrade_pre_dip_release_v10(data)
data = self._upgrade_pre_torpedo_spoolup_v10(data)
data = self._upgrade_pre_depth_inertia_v10(data)
# Exact same-version predecessor: no helicopter buoy receiver state.
if isinstance(data, dict) and isinstance(data.get("sonar"), dict):
contacts = data["sonar"].get("contacts")
buoys = data.get("buoys")
added_contact = {"buoy_reports", "helo_qualified",
"buoy_released_to_opz"}
if (isinstance(contacts, dict) and all(isinstance(row, dict)
and not (set(row) & added_contact)
for row in contacts.values())
and isinstance(buoys, list) and all(isinstance(row, dict)
and not (set(row) & {"mode", "last_ping_epoch"})
for row in buoys)):
data = copy.deepcopy(data)
for row in data["sonar"]["contacts"].values():
row.update(buoy_reports={}, helo_qualified=False,
buoy_released_to_opz=False)
for row in data["buoys"]:
row.update(mode="PASSIVE", last_ping_epoch=-1)
data = self._upgrade_pre_opz_map_current_save(data)
if (not isinstance(data, dict)
or type(data.get("time_scale_idx")) is not int
or not 0 <= data["time_scale_idx"] < 6):
@@ -9657,31 +9183,6 @@ class Game:
data["time_scale_idx"] = config.TIME_SCALE_DEFAULT
except (KeyError, TypeError, ValueError, OverflowError, RecursionError):
return False
legacy_esm_fields = {
"version", "track_seq", "picture", "selected_track_key", "annotations"}
esm_state = data.get("esm") if isinstance(data, dict) else None
if (isinstance(esm_state, dict) and set(esm_state) == legacy_esm_fields
and esm_state.get("version") == 1):
# The sole accepted same-save-version compatibility shape: the
# pre-ECM ESM envelope. Canonicalize only after the catalog and
# exact legacy keys have validated structurally.
data = copy.deepcopy(data)
data["esm"]["version"] = ESM_STATE_VERSION
data["esm"]["ecm"] = {"auto_enabled": False, "channels": []}
data["catalog_snapshot"] = runtime_catalog.runtime_snapshot()
elif (isinstance(esm_state, dict) and esm_state.get("version") == 2
and valid_esm_state(esm_state, data.get("sim_t", -1.0),
runtime_catalog.emitters)):
# Canonicalize the earlier two-channel ECM envelope while keeping
# the outer save schema unchanged.
legacy_jammer = ECMJammer()
legacy_jammer.restore(
esm_state["ecm"],
{row["track_key"] for row in esm_state["picture"]},
data["sim_t"], version=2)
data = copy.deepcopy(data)
data["esm"]["version"] = ESM_STATE_VERSION
data["esm"]["ecm"] = legacy_jammer.serialize()
if not self._valid_save_document(data, runtime_catalog):
return False
candidate = copy.copy(self)
@@ -9750,7 +9251,7 @@ class Game:
data = _read_save_document(path)
except (OSError, ValueError, RecursionError):
return False
if not self._load_save_data(data, allow_pre_r9=True):
if not self._load_save_data(data):
return False
self.announce(message("status.loaded", slot=slot), "mission", 2.0)
return True
+45
View File
@@ -0,0 +1,45 @@
"""Declarative exact key sets for the ``u-jagd-save-v12`` document.
Every persisted block whose shape is validated exactly is declared here, so a
new saved field is added in exactly three places: this module,
``Game.save_state()`` and ``Game._restore_state()``. The loader additionally
re-serializes every restored candidate and requires byte-for-byte equality
with the input, so a field missing from any of the three places fails loudly.
"""
SAVE_ROOT_FIELDS = frozenset({
"version", "save_schema", "platform_state_version", "catalog_snapshot",
"seed", "level", "mission_type", "scenario_key", "mission_name",
"mission_runtime", "world", "sim_t", "mission_time", "time_scale_idx",
"score", "mission_result", "result_reason", "ship", "torpedoes",
"chaff_cd", "vls_cells", "ciws_ammo", "roe", "sonar_mode", "radars",
"asm_sel", "radio_sel", "hq_timer", "damage", "dmg_cursor", "dmg_team",
"incident", "subs", "animals", "civilians", "warships", "decoys",
"torpedoes_in_flight", "enemy_torpedoes", "asw", "air_defense", "asms", "essms",
"buoys", "helo", "flights", "sonar_controls", "sonar", "messages",
"hfdf_fixes", "hfdf_log", "radio_picture", "air_picture",
"opz_affiliations", "air_threat_reported", "esm", "next_entity_ids",
"asm_spawned", "asm_seq", "warship_asm_seq", "torpedo_seq", "buoy_seq",
"ciws_cooldown_s", "schedulers", "rngs", "ui",
"autocrew", "ais",
})
RNG_STREAMS = frozenset({
"world", "world_weather", "asm", "damage", "helo", "sonar",
"flight", "asw", "raid",
})
SHIP_FIELDS = frozenset({
"x", "y", "course", "target_course", "speed", "target_speed",
"order_idx", "astern", "hull", "grounding", "turn_rate_scale",
"rudder_angle", "yaw_rate", "roll", "pitch", "quiet_mode", "clock",
"fuel_capacity_kg", "fuel_kg",
})
WORLD_FIELDS = frozenset({
"hour", "sea_state", "weather_shift_timer", "mode", "generator", "coast",
})
DAMAGE_FIELDS = frozenset({"repair_mult", "compartments", "teams"})
COMPARTMENT_FIELDS = frozenset({"state", "flood", "fire"})
COMPARTMENT_STATES = ("OK", "FLUTEND", "BESCHAEDIGT", "ZERSTOERT")
+2 -2
View File
@@ -5,8 +5,8 @@ version while building the project.
"""
APP_VERSION = "1.0.0"
SAVE_VERSION = 11
SAVE_SCHEMA = "u-jagd-save-v11"
SAVE_VERSION = 12
SAVE_SCHEMA = "u-jagd-save-v12"
SPLASH_TEXT = (
"Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer "
f"Version {APP_VERSION}"
+176
View File
@@ -0,0 +1,176 @@
"""Simulated AIS VHF receiver for the own ship.
Civilian ships that transmit AIS broadcast their own name, course and speed.
Those broadcasts are legitimate observations: the receiver only learns what a
report contained, only when a report was actually sent (ITU-R M.1371 class-A
reporting cadence) and only inside VHF line-of-sight. Radar observations of
civilian ships therefore no longer carry the ship's true name or course; the
label/course come from the latest received AIS report instead.
The transmission phase of each ship is a stateless function of its sensor
seed, so the schedule needs no saved clock. What the receiver has decoded is
saved and restored exactly.
"""
from __future__ import annotations
import math
from dataclasses import asdict, dataclass
from src.core import config, detrand
AIS_MAX_REPORTS = 128
AIS_STATIC_INTERVAL_S = 360.0
# Own VHF antenna mast and a typical merchant VHF antenna height.
AIS_RX_ANTENNA_HEIGHT_M = 25.0
AIS_TX_ANTENNA_HEIGHT_M = 15.0
AIS_NAME_MAX = 40
# A dynamic report older than this many nominal intervals is not used.
AIS_DYNAMIC_STALE_INTERVALS = 3.0
def reporting_interval_s(speed_kn: float) -> float:
"""ITU-R M.1371 class-A dynamic report interval (not changing course)."""
if speed_kn <= 3.0:
return 180.0 # at anchor / moored
if speed_kn <= 14.0:
return 10.0
if speed_kn <= 23.0:
return 6.0
return 2.0
def vhf_range_nm() -> float:
"""VHF radio line-of-sight between the two antennas (4/3-Earth)."""
return config.radar_horizon_nm(AIS_RX_ANTENNA_HEIGHT_M,
AIS_TX_ANTENNA_HEIGHT_M)
@dataclass
class AISReport:
target_id: int
name: str | None
cog: float
sog: float
t_dynamic: float
t_static: float | None
dynamic_epoch: int
static_epoch: int
class AISReceiver:
"""Own-ship AIS decoder state; holds received reports only."""
def __init__(self, seed: int = 0):
self.seed = int(seed)
self.reports: dict[int, AISReport] = {}
def _epoch(self, sensor_seed: int, tag: str, now: float,
interval: float) -> int:
offset = detrand.u01(self.seed, tag, sensor_seed) * interval
return math.floor((now - offset) / interval)
def update(self, now: float, ships, own_ship, world) -> None:
"""Decode every report that was broadcast inside VHF range."""
reach = vhf_range_nm()
present = {ship.id for ship in ships}
for target_id in [key for key in self.reports if key not in present]:
del self.reports[target_id]
for ship in sorted(ships, key=lambda item: item.id):
if not getattr(ship, "ais_transmitting", False):
continue
distance = math.hypot(ship.x - own_ship.x, ship.y - own_ship.y)
if distance > reach or world.land_blocks_line(
own_ship.x, own_ship.y, ship.x, ship.y):
continue
interval = reporting_interval_s(ship.speed)
dynamic_epoch = self._epoch(ship.sensor_seed, "ais-dynamic",
now, interval)
static_epoch = self._epoch(ship.sensor_seed, "ais-static", now,
AIS_STATIC_INTERVAL_S)
report = self.reports.get(ship.id)
if report is None:
if len(self.reports) >= AIS_MAX_REPORTS:
oldest = min(self.reports.values(),
key=lambda item: (item.t_dynamic, item.target_id))
del self.reports[oldest.target_id]
# First decoded message is a position report; the name only
# arrives with the next static/voyage message.
report = AISReport(ship.id, None, ship.course % 360.0,
max(0.0, ship.speed), now, None,
dynamic_epoch, static_epoch)
self.reports[ship.id] = report
continue
if dynamic_epoch != report.dynamic_epoch:
report.dynamic_epoch = dynamic_epoch
report.cog = ship.course % 360.0
report.sog = max(0.0, ship.speed)
report.t_dynamic = now
if static_epoch != report.static_epoch:
report.static_epoch = static_epoch
report.name = str(ship.name)[:AIS_NAME_MAX]
report.t_static = now
def forget(self, target_ids) -> None:
for target_id in list(target_ids):
self.reports.pop(target_id, None)
def label_for(self, target_id: int) -> str | None:
report = self.reports.get(target_id)
return None if report is None else report.name
def course_for(self, target_id: int, now: float) -> float | None:
report = self.reports.get(target_id)
if report is None:
return None
limit = AIS_DYNAMIC_STALE_INTERVALS * reporting_interval_s(report.sog)
if now - report.t_dynamic > limit:
return None
return report.cog
# --- persistence -------------------------------------------------------
def serialize(self) -> list[dict]:
return [asdict(self.reports[key]) for key in sorted(self.reports)]
@staticmethod
def valid_state(rows, now: float, known_ids) -> bool:
fields = set(AISReport.__dataclass_fields__)
if not isinstance(rows, list) or len(rows) > AIS_MAX_REPORTS:
return False
previous = None
def finite(value) -> bool:
return (isinstance(value, (int, float)) and not isinstance(value, bool)
and math.isfinite(value))
for row in rows:
if not isinstance(row, dict) or set(row) != fields:
return False
target_id = row["target_id"]
if (type(target_id) is not int or target_id not in known_ids
or (previous is not None and target_id <= previous)):
return False
previous = target_id
name = row["name"]
if name is not None and (not isinstance(name, str)
or len(name) > AIS_NAME_MAX):
return False
if (not finite(row["cog"]) or not 0.0 <= row["cog"] < 360.0
or not finite(row["sog"]) or not 0.0 <= row["sog"] <= 100.0
or not finite(row["t_dynamic"])
or not 0.0 <= row["t_dynamic"] <= now):
return False
t_static = row["t_static"]
if (t_static is None) != (name is None):
return False
if t_static is not None and (not finite(t_static)
or not 0.0 <= t_static <= now):
return False
if any(type(row[key]) is not int or abs(row[key]) > 2**53
for key in ("dynamic_epoch", "static_epoch")):
return False
return True
def restore(self, rows) -> None:
self.reports = {row["target_id"]: AISReport(**row) for row in rows}
+10 -26
View File
@@ -601,25 +601,18 @@ class ECMJammer:
return {"auto_enabled": self.auto_enabled,
"channels": [asdict(channel) for channel in self.channels]}
def restore(self, state: dict, valid_track_keys: set[str], now: float,
*, version: int = ESM_STATE_VERSION) -> None:
def restore(self, state: dict, valid_track_keys: set[str],
now: float) -> None:
if not isinstance(state, dict) or set(state) != {"auto_enabled", "channels"}:
raise ValueError("invalid ECM state")
if type(state["auto_enabled"]) is not bool or not isinstance(state["channels"], list):
raise ValueError("invalid ECM state")
legacy_limit = 2 if version == 2 else self.MAX_CHANNELS
if len(state["channels"]) > legacy_limit:
if len(state["channels"]) > self.MAX_CHANNELS:
raise ValueError("too many ECM channels")
fields = set(ECMChannel.__dataclass_fields__)
channels = []
keys = set()
for row in state["channels"]:
if version == 2 and isinstance(row, dict):
row = dict(row)
row.update(technique=ECMTechnique.NOISE.value,
tuned_bearing_deg=0.0,
power_draw=self.TECHNIQUE_POWER[ECMTechnique.NOISE.value],
is_locked_on=row.get("effectiveness", 0.0) > 0.0)
if not isinstance(row, dict) or set(row) != fields:
raise ValueError("invalid ECM channel")
channel = ECMChannel(**row)
@@ -953,17 +946,11 @@ def correlate_observations(track: ESMTrack, evidence,
def valid_esm_state(state, now: float, emitters: Mapping[str, object]) -> bool:
"""Validate the exact ESM envelope in the canonical save schema."""
if not isinstance(state, dict) or set(state) not in ({
"version", "track_seq", "picture", "selected_track_key", "annotations"}, {
if not isinstance(state, dict) or set(state) != {
"version", "track_seq", "picture", "selected_track_key", "annotations",
"ecm"}):
"ecm"}:
return False
if type(state["version"]) is not int or state["version"] not in (
1, 2, ESM_STATE_VERSION):
return False
if state["version"] == 1 and "ecm" in state:
return False
if state["version"] in (2, ESM_STATE_VERSION) and "ecm" not in state:
if type(state["version"]) is not int or state["version"] != ESM_STATE_VERSION:
return False
track_seq = state["track_seq"]
if type(track_seq) is not int or not 0 <= track_seq <= 2**63 - 1:
@@ -991,13 +978,10 @@ def valid_esm_state(state, now: float, emitters: Mapping[str, object]) -> bool:
or emitter is None or getattr(emitter, "domain", None) != "radar"):
return False
previous = track_key
if "ecm" in state:
try:
jammer = ECMJammer()
jammer.restore(state["ecm"], set(picture._tracks), now,
version=state["version"])
except (TypeError, ValueError, OverflowError):
return False
try:
ECMJammer().restore(state["ecm"], set(picture._tracks), now)
except (TypeError, ValueError, OverflowError):
return False
return True
+1
View File
@@ -0,0 +1 @@
{}
+302
View File
@@ -0,0 +1,302 @@
{
"metrics": {
"damage.flood_total_1800s_two_hits.mean": {
"kind": "statistic",
"value": 203.0
},
"damage.flood_total_600s_no_repair.mean": {
"kind": "statistic",
"value": 115.5
},
"damage.sink_total": {
"kind": "equilibrium",
"value": 540.0
},
"lookout.range_nm.flight.day.sea1": {
"kind": "range",
"value": 18.4
},
"lookout.range_nm.sub.day.sea1": {
"kind": "range",
"value": 4.6
},
"lookout.range_nm.surface.day.sea1": {
"kind": "range",
"value": 11.04
},
"radar.horizon_nm.surface_target": {
"kind": "equilibrium",
"value": 16.991151
},
"radar.range_nm.air.sea1.rain0": {
"kind": "range",
"value": 100.0
},
"radar.range_nm.air.sea1.rain1": {
"kind": "range",
"value": 80.0
},
"radar.range_nm.air.sea5.rain0": {
"kind": "range",
"value": 95.0
},
"radar.range_nm.air.sea6.rain0": {
"kind": "range",
"value": 90.0
},
"radar.range_nm.surface.sea1.rain0": {
"kind": "range",
"value": 30.0
},
"radar.range_nm.surface.sea1.rain1": {
"kind": "range",
"value": 27.0
},
"radar.range_nm.surface.sea5.rain0": {
"kind": "range",
"value": 26.25
},
"radar.range_nm.surface.sea6.rain0": {
"kind": "range",
"value": 22.5
},
"ship.cavitation_onset_kn": {
"kind": "equilibrium",
"value": 15.0
},
"ship.fuel_kg_h.FLANK": {
"kind": "equilibrium",
"value": 7800.0
},
"ship.fuel_kg_h.FULL": {
"kind": "equilibrium",
"value": 2339.8656
},
"ship.fuel_kg_h.HALF": {
"kind": "equilibrium",
"value": 873.6
},
"ship.fuel_kg_h.SLOW": {
"kind": "equilibrium",
"value": 502.2976
},
"ship.fuel_kg_h.STOP": {
"kind": "equilibrium",
"value": 400.0
},
"ship.rpm_eq.FLANK": {
"kind": "equilibrium",
"value": 80.0
},
"ship.rpm_eq.FULL": {
"kind": "equilibrium",
"value": 58.4
},
"ship.rpm_eq.HALF": {
"kind": "equilibrium",
"value": 44.0
},
"ship.rpm_eq.SLOW": {
"kind": "equilibrium",
"value": 34.4
},
"ship.rpm_eq.STOP": {
"kind": "equilibrium",
"value": 20.0
},
"ship.speed_eq.FLANK": {
"kind": "equilibrium",
"value": 25.0
},
"ship.speed_eq.FULL": {
"kind": "equilibrium",
"value": 16.0
},
"ship.speed_eq.HALF": {
"kind": "equilibrium",
"value": 10.0
},
"ship.speed_eq.SLOW": {
"kind": "equilibrium",
"value": 6.0
},
"ship.speed_eq.STOP": {
"kind": "equilibrium",
"value": 0.0
},
"ship.t10_stop_from_full_s": {
"kind": "transient",
"value": 92.15
},
"ship.t90_full_s": {
"kind": "transient",
"value": 92.15
},
"ship.tactical_diameter_nm.FULL": {
"kind": "transient",
"value": 0.424801
},
"ship.tactical_diameter_nm.HALF": {
"kind": "transient",
"value": 0.398049
},
"ship.yaw_steady_deg_s.FULL": {
"kind": "equilibrium",
"value": 1.2
},
"ship.yaw_steady_deg_s.HALF": {
"kind": "equilibrium",
"value": 0.8
},
"sonar.active_nm.BOW.d250": {
"kind": "range",
"value": 6.111
},
"sonar.active_nm.BOW.d30": {
"kind": "range",
"value": 17.46
},
"sonar.bearing_err_deg.BOW.own12.q05": {
"kind": "equilibrium",
"value": 13.908
},
"sonar.bearing_err_deg.BOW.own6.q05": {
"kind": "equilibrium",
"value": 9.804
},
"sonar.bearing_err_deg.TOWED.own12.q05": {
"kind": "equilibrium",
"value": 4.636
},
"sonar.bearing_err_deg.TOWED.own6.q05": {
"kind": "equilibrium",
"value": 3.268
},
"sonar.passive_nm.BOW.sea1.own12.d150": {
"kind": "range",
"value": 12.331414
},
"sonar.passive_nm.BOW.sea1.own12.d30": {
"kind": "range",
"value": 23.14859
},
"sonar.passive_nm.BOW.sea1.own18.d150": {
"kind": "range",
"value": 4.055514
},
"sonar.passive_nm.BOW.sea1.own18.d30": {
"kind": "range",
"value": 7.69076
},
"sonar.passive_nm.BOW.sea1.own25.d150": {
"kind": "range",
"value": 3.18232
},
"sonar.passive_nm.BOW.sea1.own25.d30": {
"kind": "range",
"value": 6.04234
},
"sonar.passive_nm.BOW.sea1.own6.d150": {
"kind": "range",
"value": 12.794754
},
"sonar.passive_nm.BOW.sea1.own6.d30": {
"kind": "range",
"value": 24.006045
},
"sonar.passive_nm.BOW.sea4.own12.d150": {
"kind": "range",
"value": 9.156709
},
"sonar.passive_nm.BOW.sea4.own12.d30": {
"kind": "range",
"value": 19.08886
},
"sonar.passive_nm.BOW.sea4.own18.d150": {
"kind": "range",
"value": 3.002833
},
"sonar.passive_nm.BOW.sea4.own18.d30": {
"kind": "range",
"value": 6.318585
},
"sonar.passive_nm.BOW.sea4.own25.d150": {
"kind": "range",
"value": 2.35566
},
"sonar.passive_nm.BOW.sea4.own25.d30": {
"kind": "range",
"value": 4.962285
},
"sonar.passive_nm.BOW.sea4.own6.d150": {
"kind": "range",
"value": 9.502208
},
"sonar.passive_nm.BOW.sea4.own6.d30": {
"kind": "range",
"value": 19.799699
},
"sonar.passive_nm.TOWED.sea1.own12.d150": {
"kind": "range",
"value": 31.242358
},
"sonar.passive_nm.TOWED.sea1.own12.d30": {
"kind": "range",
"value": 13.44305
},
"sonar.passive_nm.TOWED.sea1.own6.d150": {
"kind": "range",
"value": 36.418335
},
"sonar.passive_nm.TOWED.sea1.own6.d30": {
"kind": "range",
"value": 15.732937
},
"sonar.passive_nm.TOWED.sea4.own12.d150": {
"kind": "range",
"value": 25.811668
},
"sonar.passive_nm.TOWED.sea4.own12.d30": {
"kind": "range",
"value": 9.986033
},
"sonar.passive_nm.TOWED.sea4.own6.d150": {
"kind": "range",
"value": 30.12386
},
"sonar.passive_nm.TOWED.sea4.own6.d30": {
"kind": "range",
"value": 11.696364
},
"sub.max_speed_kn.aip_modern": {
"kind": "equilibrium",
"value": 13.0
},
"sub.quiet.aip_modern.patrol": {
"kind": "equilibrium",
"value": 0.68
},
"torpedo.depth_after_5s_m": {
"kind": "transient",
"value": 55.0
},
"torpedo.depth_after_run_m": {
"kind": "equilibrium",
"value": 67.76187
},
"torpedo.run_time_s.frigate_torp": {
"kind": "equilibrium",
"value": 960.75
},
"torpedo.travel_nm.frigate_torp": {
"kind": "equilibrium",
"value": 12.0
},
"torpedo.wire_turn_deg_s": {
"kind": "transient",
"value": 8.0
}
},
"note": "Kinematic U-Jagd 1.0.0 reference behaviour.",
"recorded_from_commit": "3b3753cf4e79927103cb03e44d0fc4b50dd8c6cb"
}
+1 -1
View File
@@ -1,4 +1,4 @@
"""Frozen active evidence and transactional save-v11 validation."""
"""Frozen active evidence and transactional save-v12 validation."""
import copy
import json
+4 -3
View File
@@ -366,7 +366,7 @@ def test_sam_sequence_must_match_consumed_inventory(game, offset):
assert game.save_state() == before
def test_exact_pre_r9_v10_file_upgrades_without_mutating_input(game, tmp_path):
def test_exact_pre_r9_shape_is_rejected_without_mutating_input(game, tmp_path):
current = game.save_state()
legacy = copy.deepcopy(current)
del legacy["air_defense"]
@@ -378,11 +378,12 @@ def test_exact_pre_r9_v10_file_upgrades_without_mutating_input(game, tmp_path):
path = tmp_path / "pre-r9-v10.json"
path.write_text(json.dumps(legacy), encoding="utf-8")
before = game.save_state()
assert not game._load_save_data(legacy)
assert game.load_game(str(path))
assert not game.load_game(str(path))
assert legacy == original
assert game.save_state()["air_defense"]["sam_remaining"] == legacy["vls_cells"]
assert game.save_state() == before
def test_integrated_softkill_and_datalink_split_run(game, monkeypatch):
+4 -12
View File
@@ -413,7 +413,7 @@ def test_raid_state_roundtrips_save_load(game):
assert restored.raid_seq == 7 and restored.raid_waves_spawned == 3
def test_pre_r20_save_upgrades_to_raid_shape(game):
def test_pre_r20_save_shape_is_rejected(game):
state = json.loads(json.dumps(game.save_state(), allow_nan=False))
ad = state["air_defense"]
loadout = ad["loadout"]
@@ -424,18 +424,10 @@ def test_pre_r20_save_upgrades_to_raid_shape(game):
del ad[key]
ad["version"] = 1
del state["rngs"]["raid"]
# ohne Upgrade-Pfad: abgelehnt
assert not game._load_save_data(copy.deepcopy(state))
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state), allow_pre_r9=True)
out = restored.save_state()["air_defense"]
assert out["version"] == AIR_DEFENSE_STATE_VERSION == 2
assert out["loadout"]["version"] == 2
assert out["loadout"]["raider"] == air_defense_loadout()["raider"]
assert out["aa_ammo"] == out["loadout"]["aa_gun"]["ammo"]
assert out["raiders"] == [] and out["raider_seq"] == 0
assert out["waves_spawned"] == 0
assert "raid" in restored.save_state()["rngs"]
before = restored.save_state()
assert not restored._load_save_data(copy.deepcopy(state))
assert restored.save_state() == before
@pytest.mark.parametrize("mutate", [
+35
View File
@@ -0,0 +1,35 @@
"""Physics upgrades must keep the recorded 1.0.0 gameplay calibration."""
import importlib.util
import json
import os
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _tool():
spec = importlib.util.spec_from_file_location(
"calibrate", os.path.join(ROOT, "tools", "calibrate.py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_golden_calibration_holds_within_tolerance():
tool = _tool()
golden = tool.load_json(tool.GOLDEN_PATH, None)
assert golden is not None and golden["metrics"]
problems = tool.compare(tool.measure_all(), golden,
tool.load_json(tool.DEVIATIONS_PATH, {}))
assert problems == []
def test_every_deviation_is_justified_and_known():
tool = _tool()
golden = tool.load_json(tool.GOLDEN_PATH, None)
with open(tool.DEVIATIONS_PATH, encoding="utf-8") as handle:
deviations = json.load(handle)
for key, entry in deviations.items():
assert key in golden["metrics"], key
assert isinstance(entry.get("reason"), str) and len(entry["reason"]) > 20
assert set(entry) <= {"reason", "value", "tolerance", "phase"}
+6 -56
View File
@@ -443,28 +443,16 @@ def _prior_r16_save(game):
return prior
def test_exact_prior_r16_v10_shape_upgrades_and_canonicalizes(tmp_path):
def test_exact_prior_r16_shape_is_rejected_transactionally(tmp_path):
source = Game(seed=1612, start_menu=False, audio_enabled=False)
prior = _prior_r16_save(source)
frozen_component_fields = {
"version", "profiles", "references", "machines", "sensors",
"emitters", "weapons", "launchers", "magazines", "countermeasures",
}
assert all(set(component) == frozen_component_fields
for component in prior["catalog_snapshot"]["components"].values())
assert all("endurance" not in row for row in prior["subs"])
assert not source._load_save_data(copy.deepcopy(prior))
path = tmp_path / "r15-v10.json"
path.write_text(json.dumps(prior), encoding="utf-8")
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored.load_game(str(path))
assert restored.save_state()["catalog_snapshot"] == catalog.CATALOG.runtime_snapshot()
for sub in restored.subs:
expected = catalog.CATALOG.endurances.get(f"endurance.{sub.stype.key}")
assert (sub.endurance is None) == (expected is None)
if expected is not None:
assert sub.endurance.battery_kwh == expected.battery_capacity_kwh
assert sub.endurance.aip_energy_kwh == (expected.aip_energy_kwh or 0)
before = restored.save_state()
assert not restored.load_game(str(path))
assert restored.save_state() == before
@pytest.mark.parametrize("mutation", [
@@ -480,7 +468,7 @@ def test_prior_r16_near_misses_are_rejected_transactionally(mutation):
prior = _prior_r16_save(game)
mutation(prior)
before = game.save_state()
assert not game._load_save_data(prior, allow_pre_r9=True)
assert not game._load_save_data(prior)
assert game.save_state() == before
@@ -496,48 +484,10 @@ def test_prior_r16_snapshot_numeric_types_are_exact_and_transactional(mutation):
prior = _prior_r16_save(game)
mutation(prior)
before = game.save_state()
assert not game._load_save_data(prior, allow_pre_r9=True)
assert not game._load_save_data(prior)
assert game.save_state() == before
def test_prior_r16_snockel_resumes_without_patrol_or_rng_draw(tmp_path):
source = Game(seed=1615, start_menu=False, audio_enabled=False)
prior = _prior_r16_save(source)
row = next(item for item in prior["subs"]
if f"endurance.{item['stype']}" in catalog.CATALOG.endurances)
row["state"] = "SNOCKEL"
row["depth"] = 20.0
row["target_depth"] = 8.0
row["evac_left"] = 12.5
path = tmp_path / "r15-snockel-v10.json"
path.write_text(json.dumps(prior), encoding="utf-8")
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored.load_game(str(path))
sub = next(item for item in restored.subs if item.id == row["id"])
before_rng = sub.rng.getstate()
before_battery = sub.endurance.battery_kwh
sub.update(.5, None, Ocean())
assert sub.state == "PATROLLE"
assert sub.evac_left == 0.0
assert sub.endurance.phase == "RADIO"
assert sub.endurance.radio_left_s == pytest.approx(12.0)
assert sub.endurance.battery_kwh < before_battery
assert sub.rng.getstate() == before_rng
@pytest.mark.parametrize("legacy_state", [
"PATROLLE", "EVADE", "LAUER", "SINKING", "SUNK",
])
def test_prior_r16_other_submarine_states_map_exactly(legacy_state):
game = Game(seed=1616, start_menu=False, audio_enabled=False)
prior = _prior_r16_save(game)
prior["subs"][0]["state"] = legacy_state
prior["subs"][0]["evac_left"] = 7.25
upgraded = Game._upgrade_pre_r16_v10(prior)
assert upgraded["subs"][0]["state"] == legacy_state
assert upgraded["subs"][0]["evac_left"] == 7.25
def test_v10_endurance_transition_continues_identically_through_save():
control = Game(seed=1610, start_menu=False, audio_enabled=False)
sub = Sub(control.ship.x + 10, control.ship.y, 60, 0, "diesel_alt",
+8 -7
View File
@@ -270,7 +270,7 @@ def test_contact_save_split_recovery_continuation_is_deterministic():
assert restored.save_state()["rngs"] == game.save_state()["rngs"]
def test_current_roundtrip_and_exact_pre_r18_upgrade_preserve_bathymetry(tmp_path):
def test_current_roundtrip_preserves_bathymetry_and_pre_r18_shape_is_rejected(tmp_path):
game = Game(seed=818, start_menu=False, audio_enabled=False)
current = game.save_state()
clone = Game(seed=1, start_menu=False, audio_enabled=False)
@@ -282,13 +282,14 @@ def test_current_roundtrip_and_exact_pre_r18_upgrade_preserve_bathymetry(tmp_pat
old = copy.deepcopy(current)
for key in ("astern", "hull", "grounding", "fuel_kg", "fuel_capacity_kg"):
old["ship"].pop(key)
bathymetry = copy.deepcopy(old["world"]["coast"]["bathymetry"])
assert clone.world.coast.to_dict()["bathymetry"] == \
current["world"]["coast"]["bathymetry"]
path = tmp_path / "old.json"
path.write_text(json.dumps(old))
assert clone.load_game(str(path))
assert clone.world.coast.to_dict()["bathymetry"] == bathymetry
assert not clone.ship.grounded and not clone.ship.astern
assert clone.ship.last_safe_pose == (clone.ship.x, clone.ship.y, clone.ship.course)
before = clone.save_state()
# v12 has no same-version upgraders: the older ship shape is rejected.
assert not clone.load_game(str(path))
assert clone.save_state() == before
near_miss = copy.deepcopy(old)
near_miss["ship"]["almost_grounding"] = None
@@ -318,7 +319,7 @@ def test_world_snapshot_is_strictly_rejected_before_restore(pre_r18, mutation):
mutation(malformed["world"]["coast"])
before = game.save_state()
assert not game._load_save_data(malformed, allow_pre_r9=True)
assert not game._load_save_data(malformed)
assert game.save_state() == before
+4 -9
View File
@@ -278,7 +278,7 @@ def test_ship_and_helicopter_release_create_two_independent_opz_bearings():
assert [track.observation_id for track in game.opz_tracks()] == [dip.observation_id]
def test_same_v10_upgrader_recognizes_only_prior_exact_release_shape():
def test_prior_release_shape_is_rejected_without_upgrader():
game = Game(seed=902, start_menu=False, audio_enabled=False)
contact = Contact(1, game.subs[0].id, "passiv", "sub")
contact.update_passive(45.0, .8, .8, "hidden", game.sim_t)
@@ -298,14 +298,9 @@ def test_same_v10_upgrader_recognizes_only_prior_exact_release_shape():
del row[key]
restored = Game(seed=903, start_menu=False, audio_enabled=False)
assert restored._load_save_data(old, allow_pre_r9=True)
upgraded = restored.sonar.contacts[contact.target_id]
assert upgraded.released_to_opz and upgraded.player_class == "U_BOOT"
assert restored.helo.dip_state == "STOWED"
malformed = copy.deepcopy(old)
malformed["helo"]["dip_state"] = "STOWED"
assert not restored._load_save_data(malformed, allow_pre_r9=True)
before = restored.save_state()
assert not restored._load_save_data(old)
assert restored.save_state() == before
def test_v10_roundtrip_preserves_dip_release_and_pending_echo(monkeypatch):
+4 -5
View File
@@ -160,14 +160,13 @@ def test_fix_and_audition_mode_save_roundtrip_and_malformed_rejection():
assert restored.save_state() == before
def test_exact_r13_sonar_shape_has_narrow_v10_upgrade():
def test_exact_r13_sonar_shape_is_rejected():
game = Game(seed=1404, start_menu=False, audio_enabled=False)
prior = game.save_state()
del prior["sonar_controls"]["audition_mode"]
for contact in prior["sonar"]["contacts"].values():
del contact["fixes"]
candidate = Game(seed=1, start_menu=False, audio_enabled=False)
assert candidate._load_save_data(prior, allow_pre_r9=True)
malformed = copy.deepcopy(prior)
malformed["sonar_controls"]["unknown_r13_field"] = True
assert not candidate._load_save_data(malformed, allow_pre_r9=True)
before = candidate.save_state()
assert not candidate._load_save_data(prior)
assert candidate.save_state() == before
+6 -14
View File
@@ -257,24 +257,18 @@ def test_submarine_mast_radar_requires_shallow_tactical_state(monkeypatch):
assert analysis.radar_type is SignalType.NAVIGATION
def test_same_v10_pre_ecm_shape_loads_with_ecm_off():
def test_pre_ecm_esm_shape_is_rejected():
game = Game(seed=806, audio_enabled=False)
state = game.save_state()
state["esm"]["version"] = 1
del state["esm"]["ecm"]
new_fields = {"radar_role", "operating_mode", "power_class",
"operating_period_s", "on_duration_s"}
for components in state["catalog_snapshot"]["components"].values():
for emitter in components["emitters"]:
for field in new_fields:
del emitter[field]
restored = Game(seed=1, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.ecm_jammer.channels == []
assert restored.ecm_jammer.auto_enabled is False
before = restored.save_state()
assert not restored._load_save_data(copy.deepcopy(state))
assert restored.save_state() == before
def test_same_v10_ecm_v2_shape_restores_as_noise_channels():
def test_two_channel_ecm_v2_shape_is_rejected():
game = Game(seed=807, audio_enabled=False)
game.esm_picture.observe_batch([ESMMeasurement(
0, 0, 90, 1, 9e9, 1000, "pulse", .9, game.sim_t)], game.sim_t)
@@ -287,6 +281,4 @@ def test_same_v10_ecm_v2_shape_restores_as_noise_channels():
"is_locked_on"):
del channel[key]
restored = Game(seed=1, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
assert len(restored.ecm_jammer.channels) == 1
assert restored.ecm_jammer.channels[0].technique == "noise"
assert not restored._load_save_data(copy.deepcopy(state))
+7 -7
View File
@@ -1,4 +1,4 @@
"""Save/load roundtrips and strict save-v11 rejection behavior."""
"""Save/load roundtrips and strict save-v12 rejection behavior."""
import json
from pathlib import Path
@@ -159,7 +159,7 @@ def test_obsolete_save_versions_are_rejected(tmp_saves, version):
assert g.save_state() == before
def test_v11_requires_exact_schema_and_every_root_field():
def test_v12_requires_exact_schema_and_every_root_field():
game = Game(seed=100, start_menu=False)
state = game.save_state()
@@ -184,7 +184,7 @@ def test_v11_requires_exact_schema_and_every_root_field():
lambda state: state["sonar"].update(unknown=None),
lambda state: state["civilians"][0].pop("id"),
])
def test_v11_rejects_noncanonical_nested_shapes(mutation):
def test_v12_rejects_noncanonical_nested_shapes(mutation):
game = Game(seed=101, start_menu=False)
before = game.save_state()
malformed = json.loads(json.dumps(before))
@@ -194,7 +194,7 @@ def test_v11_rejects_noncanonical_nested_shapes(mutation):
assert game.save_state() == before
def test_v11_sonar_contact_sequence_must_exceed_existing_contacts():
def test_v12_sonar_contact_sequence_must_exceed_existing_contacts():
game = Game(seed=102, start_menu=False)
target = game.subs[0]
game.sonar.contacts[target.id] = Contact(7, target.id, "passiv", "sub")
@@ -247,7 +247,7 @@ def test_fixed_real_sector_roundtrip_keeps_selected_coast_and_airbases(tmp_saves
assert len(game.world.coast.airbases) >= 4
def test_v11_preserves_tas_ping_echo_and_operator_state(tmp_saves):
def test_v12_preserves_tas_ping_echo_and_operator_state(tmp_saves):
game = Game(seed=188, start_menu=False)
game.sonar.toggle_tow(6.0)
game.sonar.tow_payout = .42
@@ -271,7 +271,7 @@ def test_v11_preserves_tas_ping_echo_and_operator_state(tmp_saves):
assert restored.tooltips_enabled is False
def test_v11_split_run_preserves_scheduler_phase():
def test_v12_split_run_preserves_scheduler_phase():
uninterrupted = Game(seed=189, start_menu=False, audio_enabled=False)
uninterrupted._sensor_acc = .13
uninterrupted._radio_acc = .31
@@ -308,7 +308,7 @@ def test_v11_split_run_preserves_scheduler_phase():
uninterrupted._slow_acc))
def test_v11_split_run_preserves_filter_pictures_and_tma_gates(monkeypatch):
def test_v12_split_run_preserves_filter_pictures_and_tma_gates(monkeypatch):
uninterrupted = Game(seed=190, start_menu=False, audio_enabled=False)
target = uninterrupted.subs[0]
contact = Contact(41, target.id, "passiv", "sub")
+181
View File
@@ -0,0 +1,181 @@
"""Phase 0 of the physics upgrade: save v12, persisted AI timers, strict
damage block, the simulated AIS receiver and stateless randomness."""
import copy
import json
import math
import pytest
from src.core import config, detrand
from src.core.game import Game
from src.core.save_schema import SAVE_ROOT_FIELDS
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.enemies.surface import SurfaceShip
from src.sensors import ais
def _game(seed=1201):
return Game(seed=seed, start_menu=False, audio_enabled=False)
def test_save_is_v12_and_exact_v11_document_is_rejected():
game = _game()
state = json.loads(json.dumps(game.save_state()))
assert (state["version"], state["save_schema"]) == (12, "u-jagd-save-v12")
assert (SAVE_VERSION, SAVE_SCHEMA) == (12, "u-jagd-save-v12")
assert set(state) == SAVE_ROOT_FIELDS
legacy = copy.deepcopy(state)
legacy["version"] = 11
legacy["save_schema"] = "u-jagd-save-v11"
del legacy["ais"]
for row in legacy["subs"]:
del row["active_ping_cd"]
before = game.save_state()
assert not game._load_save_data(legacy)
assert game.save_state() == before
def test_sub_ping_cooldown_and_surface_evasion_survive_save_load():
game = _game(1202)
sub = game.subs[0]
sub._active_ping_cd = 37.5
ship = next(iter(game.warships or game.civilians), None)
if ship is None:
ship = SurfaceShip(game.ship.x + 8.0, game.ship.y, game.rng_world,
profile=game.runtime_catalog.surfaces["warship_01"],
side="hostile", doctrine="surface_combatant",
runtime_catalog=game.runtime_catalog)
game.warships.append(ship)
ship.alert_torpedo(123.0)
state = json.loads(json.dumps(game.save_state()))
restored = _game(1)
assert restored._load_save_data(copy.deepcopy(state))
again = next(item for item in restored.subs if item.id == sub.id)
assert again._active_ping_cd == 37.5
twin = next(item for item in restored.warships + restored.civilians
if item.id == ship.id)
assert twin._torpedo_evade_left == ship._torpedo_evade_left > 0.0
assert twin._torpedo_threat_bearing == pytest.approx(123.0)
for _ in range(40):
game._update_sim(.25)
restored._update_sim(.25)
assert restored.save_state()["subs"] == game.save_state()["subs"]
assert (restored.save_state()["warships"], restored.save_state()["civilians"]) \
== (game.save_state()["warships"], game.save_state()["civilians"])
@pytest.mark.parametrize("mutation", [
lambda d: d.update(extra=1),
lambda d: d.pop("teams"),
lambda d: d.update(repair_mult=-1.0),
lambda d: d["teams"].pop("3"),
lambda d: d["teams"].update({"1": "nowhere"}),
lambda d: d["compartments"].pop("bridge"),
lambda d: d["compartments"]["bridge"].update(extra=0),
lambda d: d["compartments"]["bridge"].pop("fire"),
lambda d: d["compartments"]["bridge"].update(flood=config.DMG_DESTROY_FLOOD + 1),
lambda d: d["compartments"]["bridge"].update(state="SUNK"),
])
def test_damage_block_is_validated_exactly(mutation):
game = _game(1203)
state = json.loads(json.dumps(game.save_state()))
mutation(state["damage"])
before = game.save_state()
assert not game._load_save_data(state)
assert game.save_state() == before
@pytest.mark.parametrize("field,value", [
("active_ping_cd", -1.0),
("active_ping_cd", config.SUB_ACTIVE_PING_COOLDOWN_S + 1.0),
])
def test_sub_ping_cooldown_is_bounded(field, value):
game = _game(1204)
state = json.loads(json.dumps(game.save_state()))
state["subs"][0][field] = value
assert not game._load_save_data(state)
def test_reporting_interval_follows_class_a_cadence():
assert ais.reporting_interval_s(0.0) == 180.0
assert ais.reporting_interval_s(10.0) == 10.0
assert ais.reporting_interval_s(18.0) == 6.0
assert ais.reporting_interval_s(25.0) == 2.0
assert 18.0 < ais.vhf_range_nm() < 22.0
def _civilian_near(game, distance):
civil = next(c for c in game.civilians if c.ais_transmitting)
civil.x, civil.y = game.ship.x + distance, game.ship.y
game.civilians = [civil]
game.warships = []
game.world.land_blocks_line = lambda *args: False
return civil
def test_radar_track_has_no_truth_name_or_course_until_ais_report():
game = _game(1205)
civil = _civilian_near(game, 4.0)
game.ais.reports.clear()
game.ais.update = lambda *args, **kwargs: None # receiver silent
game._update_air_picture()
track = game.air_picture._tracks[f"S-{civil.id}"]
assert track.label == f"S-{civil.id}"
assert track.course is None
assert civil.name not in track.label
def test_ais_decodes_dynamic_then_static_reports_in_vhf_range():
game = _game(1206)
civil = _civilian_near(game, 4.0)
receiver = game.ais
receiver.update(0.0, [civil], game.ship, game.world)
report = receiver.reports[civil.id]
assert report.name is None and receiver.label_for(civil.id) is None
assert receiver.course_for(civil.id, 0.0) == pytest.approx(civil.course % 360.0)
for step in range(1, 800):
receiver.update(step * 0.5, [civil], game.ship, game.world)
assert receiver.label_for(civil.id) == civil.name
far = _game(1207)
other = _civilian_near(far, ais.vhf_range_nm() + 1.0)
far.ais.update(0.0, [other], far.ship, far.world)
assert far.ais.reports == {}
def test_ais_state_round_trips_and_rejects_malformed_rows():
game = _game(1208)
civil = _civilian_near(game, 3.0)
for step in range(900):
game.ais.update(step * 0.5, [civil], game.ship, game.world)
game.sim_t = 450.0
state = json.loads(json.dumps(game.save_state()))
assert state["ais"] and state["ais"][0]["name"] == civil.name
restored = _game(1)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.save_state()["ais"] == state["ais"]
for mutation in (lambda r: r.update(cog=360.0),
lambda r: r.update(t_static=None),
lambda r: r.update(target_id=99999999),
lambda r: r.update(extra=1),
lambda r: r.update(t_dynamic=1e9)):
broken = copy.deepcopy(state)
mutation(broken["ais"][0])
assert not restored._load_save_data(broken)
def test_detrand_is_stable_and_uniform():
assert detrand.bits(1, "x", 2, 3) == detrand.bits(1, "x", 2, 3)
assert detrand.bits(1, "x", 2, 3) != detrand.bits(1, "y", 2, 3)
assert detrand.bits(1, "x", 2, 3) != detrand.bits(1, "x", 3, 2)
values = [detrand.u01(7, "stat", i) for i in range(4000)]
assert all(0.0 <= value < 1.0 for value in values)
assert abs(sum(values) / len(values) - 0.5) < 0.02
normals = [detrand.normal(7, "n", i) for i in range(4000)]
mean = sum(normals) / len(normals)
var = sum((n - mean) ** 2 for n in normals) / len(normals)
assert abs(mean) < 0.06 and abs(math.sqrt(var) - 1.0) < 0.06
# Frozen reference value: changing the mixer would silently re-seed
# every stateless draw in saved games.
assert detrand.bits(0, "", 0) == 0x21FA69A58F3D62F5
assert detrand.bits(42, "ujagd", 1) == 0xC19DD5FB35331834
+3 -5
View File
@@ -145,7 +145,7 @@ def test_save_load_restores_navigation_ui_state():
assert restored.map_view.scale == 4.0
def test_save_load_restores_independent_opz_map_and_accepts_prior_ui():
def test_save_load_restores_independent_opz_map_and_rejects_prior_ui():
game = Game(seed=31415, start_menu=False)
game.opz_map_follow = False
game.opz_map_view.cx = 210.0
@@ -163,10 +163,8 @@ def test_save_load_restores_independent_opz_map_and_accepts_prior_ui():
"opz_map_follow"):
del data["ui"][key]
legacy = Game(seed=1000, start_menu=False)
legacy.load_state(data)
assert legacy.opz_map_follow is True
assert (legacy.opz_map_view.cx, legacy.opz_map_view.cy) == pytest.approx(
(legacy.ship.x, legacy.ship.y))
with pytest.raises(ValueError):
legacy.load_state(data)
def test_escape_requires_explicit_quit_confirmation():
+474
View File
@@ -0,0 +1,474 @@
#!/usr/bin/env python3
"""Gameplay calibration harness for the physics upgrade.
``--record`` measures observable gameplay quantities (equilibrium speeds,
acceleration and turn behaviour, sensor detection ranges, weapon timings,
damage progression) through the *public runtime behaviour* of the current
code and writes them to ``tests/calibration/golden.json``. ``--check``
re-measures and compares against that file with per-metric tolerances.
The golden file was recorded once against the U-Jagd 1.0.0 kinematic models
before any physics replacement. Later physics phases must reproduce these
values within tolerance; an intentional deviation is listed with its reason in
``tests/calibration/deviations.json`` rather than by re-recording.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import statistics
import subprocess
import sys
import types
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
GOLDEN_PATH = os.path.join(ROOT, "tests", "calibration", "golden.json")
DEVIATIONS_PATH = os.path.join(ROOT, "tests", "calibration", "deviations.json")
# Tolerance classes (relative): equilibrium values, transients, range grids.
TOL = {"equilibrium": 0.02, "transient": 0.10, "range": 0.10,
"statistic": 0.20}
def _metric(value: float, kind: str) -> dict:
return {"value": round(float(value), 6), "kind": kind}
# --------------------------------------------------------------------------
# Own ship
def _ship_run(order: str, seconds: float, *, turn_deg: float = 0.0,
start_speed: float = 0.0, dt: float = 0.05):
from src.core import config
from src.ship.ship import Ship
ship = Ship(100.0, 100.0, 0.0, speed_kn=start_speed)
index = next(i for i, item in enumerate(config.TELEGRAPH_ORDERS)
if item[0] == order)
ship.order_idx = index
ship.target_speed = config.TELEGRAPH_ORDERS[index][1]
ship.target_course = turn_deg % 360.0
for step in range(int(round(seconds / dt))):
ship.update(dt)
yield (step + 1) * dt, ship
def measure_ship() -> dict:
from src.core import config
out = {}
for name, speed in config.TELEGRAPH_ORDERS:
final = None
for _t, ship in _ship_run(name, 900.0):
final = ship
out[f"ship.speed_eq.{name}"] = _metric(final.speed, "equilibrium")
out[f"ship.rpm_eq.{name}"] = _metric(final.rpm(), "equilibrium")
out[f"ship.fuel_kg_h.{name}"] = _metric(final.fuel_burn_kg_h(),
"equilibrium")
# Time to 90 % of FULL from rest.
full = dict(config.TELEGRAPH_ORDERS)["FULL"]
t90 = None
for t, ship in _ship_run("FULL", 900.0):
if ship.speed >= 0.9 * full:
t90 = t
break
out["ship.t90_full_s"] = _metric(t90, "transient")
# Coast-down from FULL to 10 % after STOP.
t10 = None
for t, ship in _ship_run("STOP", 1800.0, start_speed=full):
if ship.speed <= 0.1 * full:
t10 = t
break
out["ship.t10_stop_from_full_s"] = _metric(t10, "transient")
# Steady turn: yaw rate and tactical diameter with a continuous
# 90-degree lead on the ordered course.
for name in ("HALF", "FULL"):
speed = dict(config.TELEGRAPH_ORDERS)[name]
xs, prev_course, turned, yaw = [], 0.0, 0.0, 0.0
for _t, ship in _ship_run(name, 1200.0, start_speed=speed):
ship.target_course = (ship.course + 90.0) % 360.0
turned += (ship.course - prev_course + 540.0) % 360.0 - 180.0
prev_course = ship.course
xs.append(ship.x)
yaw = ship.yaw_rate
if turned >= 360.0:
break
out[f"ship.yaw_steady_deg_s.{name}"] = _metric(yaw, "equilibrium")
out[f"ship.tactical_diameter_nm.{name}"] = _metric(
max(xs) - min(xs), "transient")
# Cavitation onset (smallest steady speed that cavitates).
from src.ship.ship import Ship
onset = None
for tenth in range(0, 300):
ship = Ship(0.0, 0.0, speed_kn=tenth / 10.0)
if ship.cavitating:
onset = tenth / 10.0
break
out["ship.cavitation_onset_kn"] = _metric(onset, "equilibrium")
return out
# --------------------------------------------------------------------------
# Sonar
def _game(seed: int = 4242):
from src.core.game import Game
return Game(seed=seed, start_menu=False)
def _open_water_geometry(game, depth_needed=400.0):
"""Deterministically find a deep-water observer spot with open bearings."""
world = game.world
size = world.size_nm
for index in range(400):
x = size * (0.2 + 0.6 * ((index * 0.6180339887) % 1.0))
y = size * (0.2 + 0.6 * ((index * 0.4142135623) % 1.0))
ok = True
for bearing in range(0, 360, 30):
for dist in (0.0, 10.0, 20.0, 35.0):
px = x + dist * math.sin(math.radians(bearing))
py = y - dist * math.cos(math.radians(bearing))
if (not 0 <= px <= size or not 0 <= py <= size
or world.on_land(px, py)
or world.depth_m(px, py) < depth_needed):
ok = False
break
if not ok:
break
if ok:
return x, y
raise RuntimeError("no open deep-water calibration spot")
def _detection_range(game, target, mode: str, bearings=(0, 90, 180, 270),
max_nm: float = 80.0) -> float:
sonar = game.sonar
ship = game.ship
results = []
for bearing in bearings:
def excess(dist):
target.x = ship.x + dist * math.sin(math.radians(bearing))
target.y = ship.y - dist * math.cos(math.radians(bearing))
reach = sonar._passive_range_nm(
target, dist, ship, game.world, 1.0, mode,
target.bearing_from_frigate(ship), True)
return reach - dist
low, high = 0.05, max_nm
if excess(low) <= 0.0:
results.append(0.0)
continue
if excess(high) > 0.0:
results.append(high)
continue
for _ in range(40):
mid = 0.5 * (low + high)
if excess(mid) > 0.0:
low = mid
else:
high = mid
results.append(0.5 * (low + high))
return statistics.median(results)
def _set_sea(world, sea_state: int) -> None:
"""Pin the weather at ``sea_state`` with no transition blend."""
world.sea_state = sea_state
world.weather_shift_timer = 0.0
world.refresh_weather()
def measure_sonar() -> dict:
out = {}
game = _game()
ship = game.ship
x, y = _open_water_geometry(game)
ship.x, ship.y, ship.course = x, y, 45.0
from src.core import config
from src.sonar.sonar import TowState
game.sonar.tow_state = TowState.STREAMED
game.sonar.tow_payout = 1.0
game.sonar._tow_settle_s = config.SONAR_TOWED_SETTLE_S
game.sonar.towed_depth_m = 150.0
subs = sorted(game.subs, key=lambda s: s.stype.key)
target = subs[0]
target.speed = min(target.stype.speed_kn, 6.0)
for sea in (1, 4):
_set_sea(game.world, sea)
for own_speed in (6.0, 12.0, 18.0, 25.0):
ship.speed = ship.target_speed = own_speed
for depth in (30.0, 150.0):
target.depth = depth
for mode in ("BOW", "TOWED"):
if mode == "TOWED" and own_speed > 12.0:
continue
key = (f"sonar.passive_nm.{mode}.sea{sea}."
f"own{int(own_speed)}.d{int(depth)}")
out[key] = _metric(_detection_range(game, target, mode),
"range")
# Active range for a target above and below the layer.
_set_sea(game.world, 1)
for depth in (30.0, 250.0):
target.depth = depth
target.x, target.y = ship.x + 5.0, ship.y
out[f"sonar.active_nm.BOW.d{int(depth)}"] = _metric(
game.sonar._active_range_nm(target, game.world, 1.0, "BOW"),
"range")
from src.sonar.sonar import bearing_error_deg
for mode in ("BOW", "TOWED"):
for speed in (6.0, 12.0):
out[f"sonar.bearing_err_deg.{mode}.own{int(speed)}.q05"] = _metric(
bearing_error_deg(mode, speed, 0.5), "equilibrium")
return out
# --------------------------------------------------------------------------
# Radar / lookout
def measure_radar() -> dict:
out = {}
game = _game()
real_world = game.world
for sea, rain in ((1, 0.0), (5, 0.0), (6, 0.0), (1, 1.0)):
stub = types.SimpleNamespace(
sea_state=sea, effective_sea_state=float(sea),
rain_intensity=rain, world=real_world)
game.world = stub
try:
for domain in ("surface", "air"):
out[f"radar.range_nm.{domain}.sea{sea}.rain{rain:g}"] = _metric(
game.radar_effective_range(domain), "range")
finally:
game.world = real_world
from src.core import config
out["radar.horizon_nm.surface_target"] = _metric(config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, config.RADAR_SURFACE_TARGET_HEIGHT_M),
"equilibrium")
# Lookout detection range, by kind, clear day, sea state 1.
ship = game.ship
x, y = _open_water_geometry(game, depth_needed=20.0)
ship.x, ship.y = x, y
_set_sea(real_world, 1)
real_world.hour = 12.0
for namespace, kind, base in (
("surface", "SURFACE", config.LOOKOUT_SURFACE_RANGE_NM),
("sub", "SUB", config.LOOKOUT_SUB_RANGE_NM),
("flight", "FLG", config.LOOKOUT_AIR_RANGE_NM)):
low, high = 0.05, 60.0
for step in range(30):
mid = 0.5 * (low + high)
actor = types.SimpleNamespace(x=x + mid, y=y, id=900000 + step,
seq=900000 + step, depth=0.0,
altitude_m=100.0)
before = len(game.air_picture._tracks)
game.sim_t += 10.0
game._lookout_observe(actor, namespace, kind, base, 12345 + step)
seen = len(game.air_picture._tracks) > before
if seen:
low = mid
else:
high = mid
out[f"lookout.range_nm.{namespace}.day.sea1"] = _metric(
0.5 * (low + high), "range")
return out
# --------------------------------------------------------------------------
# Torpedo
def measure_torpedo() -> dict:
from src.core import config
from src.data.catalog import CATALOG
from src.weapons.torpedo import Torpedo
out = {}
profile = CATALOG.get_torpedo("frigate_torp")
torp = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=profile,
time_since_launch=0.0, guidance_x=100.0, guidance_y=0.0)
dt = 0.05
t = 0.0
t_cruise = None
while torp.state == "RUN" and t < 7200.0:
torp._midcourse_timer = 0.0
torp.update(dt)
t += dt
if t_cruise is None and torp.time_since_launch >= config.TORP_SPOOLUP_S:
t_cruise = t
out["torpedo.run_time_s.frigate_torp"] = _metric(t, "equilibrium")
out["torpedo.travel_nm.frigate_torp"] = _metric(torp.travel, "equilibrium")
out["torpedo.depth_after_run_m"] = _metric(torp.depth, "equilibrium")
# Turn rate on the wire toward a datum 90 degrees off the bow.
torp = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=profile,
guidance_x=130.0, guidance_y=100.0)
torp.update(dt)
start = torp.course
for _ in range(20):
torp._midcourse_timer = 0.0
torp.update(dt)
out["torpedo.wire_turn_deg_s"] = _metric(
((torp.course - start + 540.0) % 360.0 - 180.0) / (20 * dt),
"transient")
# Depth change rate.
torp = Torpedo(100.0, 100.0, 0.0, 200.0, None, 0, profile=profile,
guidance_x=100.0, guidance_y=0.0)
for _ in range(100):
torp._midcourse_timer = 0.0
torp.update(dt)
out["torpedo.depth_after_5s_m"] = _metric(torp.depth, "transient")
return out
# --------------------------------------------------------------------------
# Submarine
def measure_sub() -> dict:
out = {}
game = _game()
for sub in sorted(game.subs, key=lambda s: s.stype.key)[:1]:
out[f"sub.max_speed_kn.{sub.stype.key}"] = _metric(
sub.stype.speed_kn, "equilibrium")
out[f"sub.quiet.{sub.stype.key}.patrol"] = _metric(
sub.quiet_factor(), "equilibrium")
return out
# --------------------------------------------------------------------------
# Damage
def measure_damage() -> dict:
from src.core import config
from src.ship.damage import DamageModel
out = {}
totals_600, fires = [], []
for seed in range(20):
model = DamageModel(random.Random(1000 + seed))
model.torpedo_hit("center")
for _ in range(int(600 / 0.25)):
model.update(0.25)
totals_600.append(model.total)
fires.append(sum(c.fire for c in model.compartments.values()))
out["damage.flood_total_600s_no_repair.mean"] = _metric(
statistics.mean(totals_600), "statistic")
totals_two = []
for seed in range(20):
model = DamageModel(random.Random(2000 + seed))
model.torpedo_hit("center")
model.torpedo_hit("port")
for _ in range(1800):
model.update(1.0)
totals_two.append(model.total)
out["damage.flood_total_1800s_two_hits.mean"] = _metric(
statistics.mean(totals_two), "statistic")
out["damage.sink_total"] = _metric(config.DMG_SHIP_SINK_TOTAL,
"equilibrium")
return out
SECTIONS = {
"ship": measure_ship,
"sonar": measure_sonar,
"radar": measure_radar,
"torpedo": measure_torpedo,
"sub": measure_sub,
"damage": measure_damage,
}
def measure_all(sections=None) -> dict:
metrics = {}
for name, function in SECTIONS.items():
if sections is None or name in sections:
metrics.update(function())
return dict(sorted(metrics.items()))
def load_json(path: str, default):
if not os.path.exists(path):
return default
with open(path, encoding="utf-8") as handle:
return json.load(handle)
def compare(measured: dict, golden: dict, deviations: dict) -> list[str]:
problems = []
for key, entry in golden["metrics"].items():
if key in deviations:
expected = deviations[key].get("value")
if expected is None:
continue
tolerance = deviations[key].get("tolerance", TOL[entry["kind"]])
else:
expected = entry["value"]
tolerance = TOL[entry["kind"]]
if key not in measured:
problems.append(f"{key}: not measured")
continue
value = measured[key]["value"]
# Relative tolerance with a small absolute floor for zero-valued
# references (e.g. speed at STOP).
if abs(value - expected) > max(tolerance * abs(expected), 0.02):
problems.append(f"{key}: {value:.4f} vs golden {expected:.4f} "
f"(tol {tolerance:.0%})")
return problems
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--record", action="store_true")
group.add_argument("--check", action="store_true")
parser.add_argument("--section", action="append", choices=sorted(SECTIONS))
args = parser.parse_args(argv)
measured = measure_all(args.section)
if args.record:
try:
commit = subprocess.run(
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True,
text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = "unknown"
os.makedirs(os.path.dirname(GOLDEN_PATH), exist_ok=True)
document = {"recorded_from_commit": commit,
"note": "Kinematic U-Jagd 1.0.0 reference behaviour.",
"metrics": measured}
with open(GOLDEN_PATH, "w", encoding="utf-8") as handle:
json.dump(document, handle, indent=1, sort_keys=True,
allow_nan=False)
handle.write("\n")
print(f"recorded {len(measured)} metrics -> {GOLDEN_PATH}")
return 0
golden = load_json(GOLDEN_PATH, None)
if golden is None:
print("no golden file; run --record first", file=sys.stderr)
return 2
if args.section:
golden = {"metrics": {key: value for key, value in golden["metrics"].items()
if key.split(".", 1)[0] in {
"lookout" if s == "radar" else s
for s in args.section} | set(args.section)}}
problems = compare(measured, golden, load_json(DEVIATIONS_PATH, {}))
for line in problems:
print(line)
print(f"{len(golden['metrics']) - len(problems)}/{len(golden['metrics'])} "
"calibration metrics within tolerance")
return 1 if problems else 0
if __name__ == "__main__":
raise SystemExit(main())