From 3d7df84681fa2c58ebb1bc35e577a3fdd8dcace1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 14:58:44 +0000 Subject: [PATCH] Crewed boat: damage control with compartments and two teams (stage D) Six compartments with depth-dependent leaks, spill through open bulkheads, fire, chlorine gas from a flooded battery and power loss; two damage-control teams seal, pump and fight fire; shut bulkheads contain water, fire and gas. Floodwater feeds the trim model; flooded, burning or gassed compartments take out the tubes, masts, diesels or half the speed. Damage page on the uConsole engine room, damage-control card in the web station. Save format v20. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01BdXs5tkJ6kzdeubNWqPHtG --- AGENTS.md | 10 +- README.de.md | 10 +- README.md | 10 +- data/commander/css/components.css | 11 + data/commander/index.html | 2 +- data/commander/js/input/wiring.js | 13 +- data/commander/js/state/schema.js | 28 +- data/commander/js/stations/uboot-graphics.js | 37 +++ data/commander/js/stations/uboot.js | 45 ++- data/i18n/de.json | 93 +++++- data/i18n/en.json | 93 +++++- data/manual/10-reference.de.md | 7 +- data/manual/10-reference.en.md | 7 +- docs/manual/manual.de.md | 10 +- docs/manual/manual.en.md | 10 +- src/commander/bridge.py | 11 + src/commander/projections.py | 29 +- src/commander/v2/commands.py | 24 +- src/commander/v2/schema.py | 9 +- src/core/config.py | 30 +- src/core/game_save.py | 3 + src/core/help.py | 3 + src/core/i18n.py | 1 + src/core/opfor.py | 11 +- src/core/save_schema.py | 4 +- src/core/save_validate.py | 2 + src/core/uboot_local.py | 39 ++- src/core/version.py | 4 +- src/enemies/ballast.py | 49 +-- src/enemies/damage_control.py | 322 +++++++++++++++++++ src/enemies/sub.py | 85 ++++- src/ui/uboot_ballast.py | 20 +- src/ui/uboot_damage.py | 138 ++++++++ src/ui/uboot_view.py | 20 +- tests/test_boat_ballast.py | 25 +- tests/test_boat_damage_control.py | 245 ++++++++++++++ tests/test_commander_assets.py | 2 +- tests/test_save_v12_hygiene.py | 14 +- tools/gen_web_schema.py | 5 + 39 files changed, 1367 insertions(+), 114 deletions(-) create mode 100644 src/enemies/damage_control.py create mode 100644 src/ui/uboot_damage.py create mode 100644 tests/test_boat_damage_control.py diff --git a/AGENTS.md b/AGENTS.md index 38c8abd4..1eaa1455 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Authority and scope -- This is U-Jagd 1.3.0 (`src/core/version.py`); current saves are v19-only. Treat these as compatibility contracts, not changelog entries. +- This is U-Jagd 1.3.0 (`src/core/version.py`); current saves are v20-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-1.3.md` and `docs/resume.md`. @@ -63,8 +63,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`; v19 saves also retain the mission's tooltip state and the uConsole's local side. CLI `--windowed` and `--no-audio` override saved values for one launch; no inverse fullscreen or CLI-language switch exists. -- Write and load save v19 only. Require the exact `u-jagd-save-v19` schema (exact key sets live in `src/core/save_schema.py`) and the complete current catalog, platform, ESM, ASW, AIS, RNG and crewed-boat crew state (`crew` block: orders, wires, plot, ESM picture, feed, sonar station; a loaded boat keeps its binding for `UBOOT_RESTORE_HOLD_S` until its crew returns), plus foreign active pings still travelling to the frigate (`ping_intercepts`) and each conventional boat's diesel, charge rate and air stores (endurance state version 2) and every submarine's ballast, trim and high-pressure air (`ballast`). Reject malformed, non-integer, older, newer, incomplete, or unknown schemas without migration. +- Preferences persist language/fullscreen/audio/large text/tooltips in `settings.json`; v20 saves also retain the mission's tooltip state and the uConsole's local side. CLI `--windowed` and `--no-audio` override saved values for one launch; no inverse fullscreen or CLI-language switch exists. +- Write and load save v20 only. Require the exact `u-jagd-save-v20` schema (exact key sets live in `src/core/save_schema.py`) and the complete current catalog, platform, ESM, ASW, AIS, RNG and crewed-boat crew state (`crew` block: orders, wires, plot, ESM picture, feed, sonar station; a loaded boat keeps its binding for `UBOOT_RESTORE_HOLD_S` until its crew returns), plus foreign active pings still travelling to the frigate (`ping_intercepts`) and each conventional boat's diesel, charge rate and air stores (endurance state version 2) and every submarine's ballast, trim and high-pressure air (`ballast`) and its compartments, leaks, fires, gas and damage-control teams (`damage_control`). 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.` 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. @@ -72,14 +72,14 @@ ## 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 v19; 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 v20; 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). - The transport is `src/commander/server.py` (`CommanderServer`: sessions, leases, publications) with `src/commander/v2/` (`wire.py` constants and framing, `commands.py` the closed action registry and validators, `routes.py` HTTP and WebSocket handlers); `server.py` re-exports the v2 names. `/ws/v2/state` pushes the active role's projection (the same bytes as `GET /api/v2/state`, at most 4 Hz, heartbeat 2 s, latest state only) and the browser falls back to polling; both paths share one allowlist: `src/commander/v2/schema.py` is rendered into the generated block of `data/commander/js/state/schema.js` by `tools/gen_web_schema.py` (`--check` in CI). 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. Role loss, disconnect, load/new game, and world replacement reject unsafe queued commands and clear held remote controls; local overlays and focus loss do not. - 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. - Observers are a host-granted, never-persisted read-only pseudo-role (at most `OBSERVER_MAX` = 2): no lease, any station viewable through `stations/activate` with generation 0, every command rejected, SimLog included; occupancy and `station_leased()` ignore observers. Voice starts enabled in the web-host room and the host switches it off. -- 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: save/load slots 1-5, new game and the instructor environment, sent as pseudo-role `host` over the normal command pipeline (same CSRF/Origin, exactly-once, phase and world-session checks; rejected in crew mode). There is no pause or time-scale command. Editors, options, quit, network administration and credentials stay host-only, saves stay exact v19, 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: save/load slots 1-5, new game and the instructor environment, sent as pseudo-role `host` over the normal command pipeline (same CSRF/Origin, exactly-once, phase and world-session checks; rejected in crew mode). There is no pause or time-scale command. Editors, options, quit, network administration and credentials stay host-only, saves stay exact v20, 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. The local F9 listener accepts only its exact LAN `Host`/`http://` origin unless launched with `--public-origin https://…`; then it also accepts exactly that proxy host (plus explicit `:443`) and origin, and marks cookies `Secure` only on the HTTPS path. The `--web-host` room accepts its public origin only. - 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. diff --git a/README.de.md b/README.de.md index 2640d1a5..c76f0a08 100644 --- a/README.de.md +++ b/README.de.md @@ -30,7 +30,7 @@ Sprachfunk ab Start; und eine Missionslaufzeit im Umfang des Editors (Referenzsektoren, Schützen- und Erreichen-Ziele, Zufallsgruppen, zeitgesteuerte Ereignisse, eingestelltes Wetter, platzierte Luftfahrzeuge, Tiere und Täuschkörper). Der Kern ist in Mixins zerlegt, die Testsuite läuft -parallel. **Spielstände haben das Format v19 (Tauchzellen, Trimm und Pressluft sowie ESM-Bild des besetzten Boots, +parallel. **Spielstände haben das Format v20 (Abteilungen und Leckabwehr, Tauchzellen, Trimm und Pressluft sowie ESM-Bild des besetzten Boots, Diesel, Laderate und Luftvorräte der U-Boote, Crew-Zustand des Bootes, Sehrohr-Sichtungen, Waffeneinstellungen, Missionsereignisse, fremde Pings auf dem Weg zur Fregatte); v18 und ältere Stände werden abgewiesen.** @@ -357,7 +357,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 -v19 gespeichert. +v20 gespeichert. ## Commander-LAN-Koop @@ -491,11 +491,11 @@ Validiert bedeutet nicht, dass ein Wert zur Laufzeit wirksam ist. In Version ## Spielstände und Benutzerdaten -Dieser Stand schreibt und lädt ausschließlich das Speicherformat **v19**. V19 -verlangt das exakte Schema `u-jagd-save-v19` einschließlich des aktuellen +Dieser Stand schreibt und lädt ausschließlich das Speicherformat **v20**. V20 +verlangt das exakte Schema `u-jagd-save-v20` einschließlich des aktuellen Schnappschusses des Laufzeitkatalogs, des gesamten Zustands für die deterministische Fortsetzung, des Crew-Zustands des besetzten Boots mit seinem -ESM-Bild, von Tauchzellen, Trimm und Pressluft jedes U-Boots, von +ESM-Bild, von Tauchzellen, Trimm, Pressluft, Abteilungen und Leckwehrtrupps jedes U-Boots, von Diesel, Laderate und Luftvorräten jedes konventionellen U-Boots und der fremden Aktivpings, deren Schall noch zur Fregatte unterwegs ist. Ältere (auch alle v11-Spielstände von 1.0.0), neuere, fehlerhafte oder unvollständige Spielstände werden ohne Migration diff --git a/README.md b/README.md index 915a581a..344c1ec5 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ role, a debrief timeline with JSON export and voice on by default; and a mission runtime that takes the editor's scope (reference sectors, protect and reach objectives, random groups, timed events, authored weather, placed aircraft, animals and decoys). The core is split into mixins and the test -suite runs in parallel. **Saves are format v19 (the crewed boat's tanks, trim and high-pressure air, its ESM picture, +suite runs in parallel. **Saves are format v20 (the crewed boat's compartments and damage control, its tanks, trim and high-pressure air, its ESM picture, submarine diesel, charge rate and air stores, crewed-boat crew state, periscope sightings, weapon settings, mission events, foreign pings still travelling to the frigate); v18 and older saves are rejected.** @@ -337,7 +337,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 v19 game saves for deterministic restoration of existing sessions. +in v20 game saves for deterministic restoration of existing sessions. ## Commander LAN Co-op @@ -447,11 +447,11 @@ Validated does not mean runtime-effective. In release 1.0.0: ## Saves and User Data -This build writes and loads save format **v19** only. V19 requires the exact -`u-jagd-save-v19` schema, including the current runtime catalog snapshot, all +This build writes and loads save format **v20** only. V20 requires the exact +`u-jagd-save-v20` schema, including the current runtime catalog snapshot, all deterministic continuation state, the crewed submarine's crew state (orders, modes, mast, wires, plot, alarm bearings, its sonar station and its ESM -picture) when a crew holds the boat, every submarine's ballast, trim and high-pressure air, every conventional submarine's diesel, charge rate and air stores, +picture) when a crew holds the boat, every submarine's ballast, trim and high-pressure air and its compartments and damage-control teams, every conventional submarine's diesel, charge rate and air stores, and foreign active pings whose sound is still travelling to the frigate. Older (including every 1.0.0 v11 save), newer, malformed, or incomplete saves are rejected without replacing the diff --git a/data/commander/css/components.css b/data/commander/css/components.css index 68a83eaa..fb27126a 100644 --- a/data/commander/css/components.css +++ b/data/commander/css/components.css @@ -236,6 +236,17 @@ body.workstation-mode #station-uboot .uboot-grid > .station-controls:not(.statio .uboot-ballast-columns section { display: flex; flex-direction: column; gap: .35rem; min-width: 0; } .uboot-ballast-columns h4 { margin: 0; } #uboot-ballast-canvas { height: clamp(13rem, 30vh, 20rem); } +.uboot-dc-columns { display: grid; grid-template-columns: minmax(0, 3fr) minmax(16rem, 2fr); gap: .6rem; align-items: start; } +@media (max-width: 60rem) { .uboot-dc-columns { grid-template-columns: minmax(0, 1fr); } } +.uboot-dc-columns section { display: flex; flex-direction: column; gap: .35rem; min-width: 0; } +.uboot-dc-columns h4 { margin: 0; } +#uboot-dc-canvas { height: clamp(9rem, 20vh, 13rem); } +.uboot-dc-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } +.uboot-dc-table th, .uboot-dc-table td { padding: .2rem .35rem; text-align: left; border-bottom: 1px solid var(--line); } +.uboot-dc-table tr[data-alert="true"] { color: var(--amber); } +.uboot-dc-table tr[data-down="true"] { color: var(--red); } +#station-uboot .uboot-dc-form { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: .3rem .5rem; align-items: center; } +#station-uboot .uboot-dc-form button { grid-column: 1 / -1; } .uboot-ballast-orders { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .3rem; } .uboot-bars { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr)); gap: .45rem; } .uboot-bar { position: relative; display: grid; gap: .05rem; padding: .35rem .5rem .55rem; overflow: hidden; background: var(--bg-2); border: 1px solid var(--line); border-left: 3px solid var(--live); border-radius: var(--radius); } diff --git a/data/commander/index.html b/data/commander/index.html index 268d8baf..b89c3f37 100644 --- a/data/commander/index.html +++ b/data/commander/index.html @@ -194,7 +194,7 @@ - + diff --git a/data/commander/js/input/wiring.js b/data/commander/js/input/wiring.js index 12ed9ef4..f3f3fe93 100644 --- a/data/commander/js/input/wiring.js +++ b/data/commander/js/input/wiring.js @@ -541,6 +541,16 @@ export function init() { for (const button of document.querySelectorAll("[data-uboot-ballast]")) button.addEventListener("click", () => sendStationAction("uboot_ballast", {tank: button.dataset.ubootBallast, direction: Number(button.dataset.direction)})); + // Engine room damage control: send a team, shut or open a compartment. + $("uboot-dc-form").addEventListener("submit", (event) => { + event.preventDefault(); + sendStationAction("uboot_dc_team", {team: Number($("uboot-dc-team").value), + compartment: $("uboot-dc-compartment").value, task: $("uboot-dc-task").value}); + }); + $("uboot-dc-rows").addEventListener("click", (event) => { + const button = event.target.closest("[data-uboot-bulkhead]"); + if (button) sendStationAction("uboot_bulkhead", {compartment: button.dataset.ubootBulkhead, closed: button.dataset.closed === "true"}); + }); // Mast station ESM: pick an emitter, classify it, transfer it to the plot. $("uboot-esm-emitters").addEventListener("click", (event) => { const button = event.target.closest("[data-uboot-esm-emitter]"); @@ -990,7 +1000,8 @@ export function init() { if (boatFrame) return; boatFrame = requestAnimationFrame(() => { boatFrame = 0; drawUbootGraphics(S.v2State?.[S.v2State?.role]); }); }; - for (const id of ["uboot-depth-canvas", "uboot-esm-canvas", "uboot-scope-canvas", "uboot-ballast-canvas"]) + for (const id of ["uboot-depth-canvas", "uboot-esm-canvas", "uboot-scope-canvas", "uboot-ballast-canvas", + "uboot-dc-canvas"]) new ResizeObserver(boatRedraw).observe($(id)); window.addEventListener("resize", () => { queueDraw(); queueLookoutDraw(); queueVisualDraw(); }); window.addEventListener("hashchange", () => { applySimlogView(); loadSimlog(); }); diff --git a/data/commander/js/state/schema.js b/data/commander/js/state/schema.js index ff77cc93..a3f6b39d 100644 --- a/data/commander/js/state/schema.js +++ b/data/commander/js/state/schema.js @@ -130,12 +130,12 @@ export function validateV2State(state) { opz: ["observations", "fusions", "radar", "defense", "asm_observations", "source_classifications", "radar_blips", "designated_target_ref", "own_assets"], radio: ["observations", "logged_fixes", "logged_bearings", "messages", "station_down", "navigation", "tactical"], sonar: ["observations", "settings", "visualization"], - uboot: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast"], - uboot_engine: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast"], - uboot_esm: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast"], - uboot_nav: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast"], + uboot: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast", "damage_control"], + uboot_engine: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast", "damage_control"], + uboot_esm: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast", "damage_control"], + uboot_nav: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast", "damage_control"], uboot_sonar: ["observations", "settings", "visualization"], - uboot_weapons: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast"], + uboot_weapons: ["navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", "esm", "ballast", "damage_control"], weapons: ["inventory", "readiness", "designated_target", "navigation", "tactical", "target_choices", "depth_m", "tubes", "settings", "own_weapons", "active_assets"], }; const tacticalFields = ["ref", "label", "domain", "source", "affiliation", "bearing", "range_nm", "x", "y", "course", "speed_kn", "altitude_m", "observer_x", "observer_y", "quality", "age_s", "bearing_uncertainty_deg", "range_uncertainty_nm", "visual_class", "visual_type"]; @@ -152,6 +152,11 @@ export function validateV2State(state) { air: ["o2_pct", "co2_pct", "absorber_pct", "absorber_sets", "candles", "candle_left_s", "level", "efficiency"], ballast: ["blowing", "venting", "auto", "pumping", "compressor", "hp_air_bar", "hp_air_max_bar", "blows_left", "mbt_pct", "regulating_kg", "regulating_order_kg", "regulating_capacity_kg", "trim_kg", "trim_order_kg", "trim_capacity_kg", "load_kg", "flooding_kg", "residual_kg", "trim_deg", "drift_mps"], ballastFlags: ["blowing", "venting", "auto", "pumping", "compressor"], + damage: ["power", "pumping", "compartments", "teams"], + compartment: ["name", "water_kg", "capacity_kg", "leak_pct", "fire_pct", "chlorine_pct", "closed", "down"], + dcTeam: ["team", "compartment", "task", "transit_s"], + compartments: ["bow", "control", "quarters", "battery", "engine", "stern"], + dcTasks: ["idle", "seal", "pump", "fire"], esm: ["mast_up", "mast_s", "mast_time_s", "mast_threat", "mast_radar_nm", "wash", "emitters"], esmEmitter: ["number", "label", "bearing", "bearing_uncertainty_deg", "frequency_hz", "band", "prf_hz", "modulation", "signal_db", "trend", "trend_db_min", "age_s", "live", "quality", "classification", "candidates", "range_estimate_nm", "mast_threat", "history", "fix"], esmHistory: ["age_s", "x", "y", "bearing"], @@ -295,6 +300,19 @@ export function validateV2State(state) { boatFields.ballastFlags.some((key) => typeof ballast[key] !== "boolean") || boatFields.ballast.filter((key) => !boatFields.ballastFlags.includes(key)).some((key) => !finite(ballast[key])) || !Number.isInteger(ballast.blows_left) || ballast.blows_left < 0) throw new Error("protocol"); + // Compartments and damage-control teams: own-ship state, closed vocabulary. + const damage = payload.damage_control; + if (!exactKeys(damage, boatFields.damage) || + typeof damage.power !== "boolean" || typeof damage.pumping !== "boolean" || + !Array.isArray(damage.compartments) || damage.compartments.length !== boatFields.compartments.length || + damage.compartments.some((row, index) => !exactKeys(row, boatFields.compartment) || + row.name !== boatFields.compartments[index] || + typeof row.closed !== "boolean" || typeof row.down !== "boolean" || + ["water_kg", "capacity_kg", "leak_pct", "fire_pct", "chlorine_pct"].some((key) => !finite(row[key]))) || + !Array.isArray(damage.teams) || damage.teams.length !== 2 || + damage.teams.some((row, index) => !exactKeys(row, boatFields.dcTeam) || row.team !== index || + !boatFields.compartments.includes(row.compartment) || !boatFields.dcTasks.includes(row.task) || + !finite(row.transit_s))) throw new Error("protocol"); // The boat's own ESM picture: measured parameters, own-position history, // crew cross-fix and library classification (never identity or position). const esm = payload.esm; diff --git a/data/commander/js/stations/uboot-graphics.js b/data/commander/js/stations/uboot-graphics.js index 4be97648..b36bee89 100644 --- a/data/commander/js/stations/uboot-graphics.js +++ b/data/commander/js/stations/uboot-graphics.js @@ -181,6 +181,43 @@ export function drawBoatBallast(id, payload) { Math.abs(b.trim_deg) > 3 ? colors.amber : colors.muted, "right"); } +// Damage control: the pressure hull cut into its compartments (bow to the +// right) with the water in each, a flame bar for fire, a green frame for +// chlorine gas (accent), a dot for an open leak, thick bulkheads where they are shut +// and the two teams by number. +export function drawBoatDamage(id, payload) { + const plot = visualContext(id); + if (!plot) return; + const {context: g, width, height} = plot, colors = palette(), dc = payload.damage_control; + const count = dc.compartments.length, left = 28, right = width - 28, top = 26, bottom = height - 30; + const cell = (right - left) / count; + g.strokeStyle = colors.muted; g.lineWidth = 1.5; + g.beginPath(); g.moveTo(left, top); g.lineTo(8, (top + bottom) / 2); g.lineTo(left, bottom); + g.moveTo(right, top); g.lineTo(width - 8, (top + bottom) / 2); g.lineTo(right, bottom); g.stroke(); + dc.compartments.forEach((row, index) => { + const x = left + (count - 1 - index) * cell, h = bottom - top; + const water = Math.max(0, Math.min(1, row.water_kg / row.capacity_kg)); + g.globalAlpha = .75; g.fillStyle = colors.blue; g.fillRect(x, top + h * (1 - water), cell, h * water); g.globalAlpha = 1; + if (row.fire_pct > 0) { g.fillStyle = colors.red; g.fillRect(x + 4, top + 4, (cell - 8) * row.fire_pct / 100, 8); } + if (row.chlorine_pct > 0) { + g.strokeStyle = colors.accent; g.lineWidth = 1 + 3 * row.chlorine_pct / 100; g.strokeRect(x + 5, top + 16, cell - 10, h - 22); + } + if (row.leak_pct > 0) { + g.fillStyle = colors.amber; g.beginPath(); g.arc(x + cell / 2, bottom - 8, 2 + 5 * row.leak_pct / 100, 0, Math.PI * 2); g.fill(); + } + g.strokeStyle = row.down ? colors.red : colors.line; g.lineWidth = row.down ? 2 : 1; g.strokeRect(x, top, cell, h); + if (row.closed) { + g.strokeStyle = colors.amber; g.lineWidth = 4; + g.beginPath(); g.moveTo(x, top - 6); g.lineTo(x, bottom + 6); g.moveTo(x + cell, top - 6); g.lineTo(x + cell, bottom + 6); g.stroke(); + } + const teams = dc.teams.filter((team) => team.compartment === row.name).map((team) => String(team.team + 1)); + if (teams.length) label(g, teams.join(" "), x + cell / 2, top + 28, colors.text, "center"); + label(g, t(`uboot_compartment_${row.name}`), x + cell / 2, bottom + 14, row.down ? colors.red : colors.muted, "center"); + }); + label(g, t("uboot_canvas_bow"), right, top - 12, colors.muted, "right"); + label(g, dc.power ? t("uboot_dc_power_on") : t("uboot_dc_power_off"), left, top - 12, dc.power ? colors.muted : colors.red); +} + // Procedural outline by the coarse class the eye made out; `width` is the // apparent length in pixels, sitting on the horizon (aircraft above it). const HEIGHT_RATIO = {warship: .24, merchant: .17, unknown: .15, aircraft: .45, torpedo: .04}; diff --git a/data/commander/js/stations/uboot.js b/data/commander/js/stations/uboot.js index 1ff7d8ba..87415c7d 100644 --- a/data/commander/js/stations/uboot.js +++ b/data/commander/js/stations/uboot.js @@ -2,7 +2,7 @@ import { S } from "../state/store.js"; import { $ } from "../core/base.js"; import { duration, number, stateText, t, unit } from "../core/format.js"; import { fillFireTargets, metrics, node, sonarEntries, stationRows, yesNo } from "../views/dom.js"; -import { drawBoatBallast, drawBoatDepth, drawBoatEsm, drawBoatScope } from "./uboot-graphics.js"; +import { drawBoatBallast, drawBoatDamage, drawBoatDepth, drawBoatEsm, drawBoatScope } from "./uboot-graphics.js"; // Alarm age with the boat's own measured bearing (never the source's truth). const alarmText = (age, bearing) => age === null ? t("station_none") @@ -169,6 +169,45 @@ function renderBallast(ballast) { } } +// Damage control: one row per compartment (water, leak, fire, gas, the +// bulkhead switch), the two teams and the power. +function renderDamage(dc) { + const pct = (value) => number(value, 0); + $("uboot-dc-rows").replaceChildren(...dc.compartments.map((row) => { + const line = document.createElement("tr"); + line.dataset.down = String(row.down); + line.dataset.alert = String(row.fire_pct > 0 || row.leak_pct > 0 || row.chlorine_pct > 0); + const bulkhead = node("button", t(row.closed ? "uboot_dc_bulkhead_open" : "uboot_dc_bulkhead_close")); + bulkhead.type = "button"; + bulkhead.dataset.ubootBulkhead = row.name; + bulkhead.dataset.closed = String(!row.closed); + bulkhead.setAttribute("aria-pressed", String(row.closed)); + bulkhead.setAttribute("aria-label", t(row.closed ? "uboot_dc_bulkhead_open_label" : "uboot_dc_bulkhead_close_label", + {compartment: t(`uboot_compartment_${row.name}`)})); + const switchCell = document.createElement("td"); + switchCell.append(bulkhead); + const teams = dc.teams.filter((team) => team.compartment === row.name).map((team) => String(team.team + 1)); + const name = node("th", t(`uboot_compartment_${row.name}`)); + name.scope = "row"; + line.append(name, ...[number(row.water_kg / 1000, 1), pct(row.leak_pct), pct(row.fire_pct), pct(row.chlorine_pct), + teams.length ? teams.join(", ") : "\u2013"].map((text) => node("td", text)), switchCell); + return line; + })); + metrics($("uboot-dc-teams"), [["uboot_dc_power", t(dc.power ? "uboot_dc_power_on" : "uboot_dc_power_off")], + ...dc.teams.map((team) => [`uboot_dc_team_${team.team + 1}`, team.transit_s > 0 + ? t("uboot_dc_team_transit", {compartment: t(`uboot_compartment_${team.compartment}`), seconds: number(team.transit_s, 0)}) + : t("uboot_dc_team_at", {compartment: t(`uboot_compartment_${team.compartment}`), task: t(`uboot_dc_task_${team.task}`)})])]); + const warnings = []; + if (!dc.power) warnings.push(t("uboot_dc_warning_power")); + const burning = dc.compartments.filter((row) => row.fire_pct > 0).map((row) => t(`uboot_compartment_${row.name}`)); + if (burning.length) warnings.push(t("uboot_dc_warning_fire", {compartments: burning.join(", ")})); + const leaking = dc.compartments.filter((row) => row.leak_pct > 0).map((row) => t(`uboot_compartment_${row.name}`)); + if (leaking.length) warnings.push(t("uboot_dc_warning_leak", {compartments: leaking.join(", ")})); + if (dc.compartments.some((row) => row.chlorine_pct > 0)) warnings.push(t("uboot_dc_warning_gas")); + $("uboot-dc-warning").hidden = warnings.length === 0; + $("uboot-dc-warning").textContent = warnings.join(" "); +} + function renderSupply(plant) { const air = plant.air; const bars = [["uboot_battery", percent(plant.battery_kwh, plant.battery_capacity_kwh), 20, 3, @@ -359,6 +398,8 @@ export function renderUbootStation(payload) { renderSupply(payload.plant); renderBallast(payload.ballast); drawBoatBallast("uboot-ballast-canvas", payload); + renderDamage(payload.damage_control); + drawBoatDamage("uboot-dc-canvas", payload); } // Redraw the boat instruments only, when a canvas changes size: one that was @@ -368,4 +409,6 @@ export function drawUbootGraphics(payload) { drawBoatDepth("uboot-depth-canvas", payload); drawBoatEsm("uboot-esm-canvas", payload); drawBoatScope("uboot-scope-canvas", payload); + drawBoatBallast("uboot-ballast-canvas", payload); + drawBoatDamage("uboot-dc-canvas", payload); } diff --git a/data/i18n/de.json b/data/i18n/de.json index 5678873f..903a624b 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -4766,5 +4766,96 @@ "commander.web.uboot_canvas_trim": "Trimm", "commander.web.uboot_canvas_regulating": "Regelzelle", "commander.web.uboot_canvas_bow": "Bug", - "commander.web.uboot_canvas_air": "Pressluft {bar} bar ({blows} Anblasungen)" + "commander.web.uboot_canvas_air": "Pressluft {bar} bar ({blows} Anblasungen)", + "station.page.uboot_damage": "Leckwehr", + "uboot.panel.compartments": "ABTEILUNGEN", + "uboot.panel.dc_status": "WASSER, LECKS, BRAND, GAS", + "uboot.panel.dc_teams": "LECKWEHRTRUPPS", + "uboot.dc.col.water": "Wasser t", + "uboot.dc.col.leak": "Leck %", + "uboot.dc.col.fire": "Brand %", + "uboot.dc.col.gas": "Gas %", + "uboot.dc.col.bulkhead": "Schott", + "uboot.dc.closed": "dicht", + "uboot.dc.open": "offen", + "uboot.dc.label.power": "Strom", + "uboot.dc.power_on": "da", + "uboot.dc.power_off": "ausgefallen: kein Motor, nur Handpumpen", + "uboot.dc.label.team": "Trupp {number}", + "uboot.dc.team_at": "{compartment}: {task}", + "uboot.dc.team_transit": "unterwegs: {compartment} ({seconds} s)", + "uboot.dc.label.order": "Befehl", + "uboot.dc.order": "{compartment}: {task}", + "uboot.compartment.bow": "Bugraum", + "uboot.compartment.control": "Zentrale", + "uboot.compartment.quarters": "Wohnraum", + "uboot.compartment.battery": "Batterieraum", + "uboot.compartment.engine": "Maschinenraum", + "uboot.compartment.stern": "Heckraum", + "uboot.dc.task.idle": "bereithalten", + "uboot.dc.task.seal": "Leck abdichten", + "uboot.dc.task.pump": "lenzen", + "uboot.dc.task.fire": "Brand löschen", + "uboot.footer.dc_bulkhead": "SCHOTT", + "uboot.local.dc_team": "Trupp {team}: {compartment}, {task}.", + "uboot.local.dc_bulkhead_closed": "{compartment}: Schotten dicht.", + "uboot.local.dc_bulkhead_open": "{compartment}: Schotten offen.", + "uboot.local.dc_unavailable": "Leckwehr jetzt nicht befehlbar.", + "uboot.reason.uboot_compartment_down": "Abteilung geflutet, in Brand oder vergast", + "commander.web.reason_uboot_compartment_down": "Die Abteilung dafür ist geflutet, brennt oder ist vergast.", + "uboot.event.dc_leak": "Wassereinbruch: {compartment}.", + "uboot.event.dc_fire": "Brand: {compartment}.", + "uboot.event.dc_fire_out": "Brand gelöscht: {compartment}.", + "uboot.event.dc_leak_sealed": "Leck abgedichtet: {compartment}.", + "uboot.event.dc_flooded": "{compartment} vollgelaufen.", + "uboot.event.dc_chlorine": "Chlorgas: Seewasser an der Batterie.", + "uboot.event.dc_power_lost": "Stromausfall: Motor steht, Pumpen nur von Hand.", + "uboot.event.dc_power_restored": "Strom wieder da.", + "help.uboot.dc_select": "Maschine, Seite Leckwehr: Abteilung wählen (auf/ab) und Aufgabe (links/rechts)", + "help.uboot.dc_team": "Maschine, Seite Leckwehr: Trupp 1 (Umschalt: Trupp 2) mit der Aufgabe schicken", + "help.uboot.dc_bulkhead": "Maschine, Seite Leckwehr: Schotten der Abteilung schließen oder öffnen", + "commander.web.uboot_dc_title": "Leckwehr", + "commander.web.uboot_dc_compartments": "Abteilungen", + "commander.web.uboot_dc_col_compartment": "Abteilung", + "commander.web.uboot_dc_col_water": "Wasser t", + "commander.web.uboot_dc_col_leak": "Leck %", + "commander.web.uboot_dc_col_fire": "Brand %", + "commander.web.uboot_dc_col_gas": "Gas %", + "commander.web.uboot_dc_col_teams": "Trupps", + "commander.web.uboot_dc_col_bulkhead": "Schotten", + "commander.web.uboot_dc_teams": "Trupps und Strom", + "commander.web.uboot_dc_team": "Trupp", + "commander.web.uboot_dc_team_1": "Trupp 1", + "commander.web.uboot_dc_team_2": "Trupp 2", + "commander.web.uboot_dc_compartment": "Abteilung", + "commander.web.uboot_dc_task": "Aufgabe", + "commander.web.uboot_dc_send": "Trupp schicken", + "commander.web.uboot_dc_bulkhead_close": "Schließen", + "commander.web.uboot_dc_bulkhead_open": "Öffnen", + "commander.web.uboot_dc_bulkhead_close_label": "Schotten zum {compartment} schließen", + "commander.web.uboot_dc_bulkhead_open_label": "Schotten zum {compartment} öffnen", + "commander.web.uboot_dc_power": "Strom", + "commander.web.uboot_dc_power_on": "Strom da", + "commander.web.uboot_dc_power_off": "Stromausfall", + "commander.web.uboot_dc_team_transit": "unterwegs: {compartment} ({seconds} s)", + "commander.web.uboot_dc_team_at": "{compartment}: {task}", + "commander.web.uboot_dc_warning_power": "Stromausfall: Motor steht, die Trupps lenzen von Hand.", + "commander.web.uboot_dc_warning_fire": "Brand: {compartments}.", + "commander.web.uboot_dc_warning_leak": "Wassereinbruch: {compartments}.", + "commander.web.uboot_dc_warning_gas": "Chlorgas im Boot.", + "commander.web.uboot_compartment_bow": "Bugraum", + "commander.web.uboot_compartment_control": "Zentrale", + "commander.web.uboot_compartment_quarters": "Wohnraum", + "commander.web.uboot_compartment_battery": "Batterieraum", + "commander.web.uboot_compartment_engine": "Maschinenraum", + "commander.web.uboot_compartment_stern": "Heckraum", + "commander.web.uboot_dc_task_idle": "Bereithalten", + "commander.web.uboot_dc_task_seal": "Leck abdichten", + "commander.web.uboot_dc_task_pump": "Lenzen", + "commander.web.uboot_dc_task_fire": "Brand löschen", + "uboot.footer.dc_team": "TRUPP 1 (UMSCH. 2)", + "uboot.threat.power": "STROMAUSFALL", + "uboot.threat.fire": "BRAND: {compartment}", + "uboot.threat.leak": "LECK: {compartment}", + "uboot.footer.dc_pick": "WÄHLEN" } diff --git a/data/i18n/en.json b/data/i18n/en.json index 7cfd2ec9..aed5e824 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -4766,5 +4766,96 @@ "commander.web.uboot_canvas_trim": "Trim", "commander.web.uboot_canvas_regulating": "Regulating", "commander.web.uboot_canvas_bow": "Bow", - "commander.web.uboot_canvas_air": "HP air {bar} bar ({blows} blows)" + "commander.web.uboot_canvas_air": "HP air {bar} bar ({blows} blows)", + "station.page.uboot_damage": "Damage", + "uboot.panel.compartments": "COMPARTMENTS", + "uboot.panel.dc_status": "WATER, LEAKS, FIRE, GAS", + "uboot.panel.dc_teams": "DAMAGE-CONTROL TEAMS", + "uboot.dc.col.water": "Water t", + "uboot.dc.col.leak": "Leak %", + "uboot.dc.col.fire": "Fire %", + "uboot.dc.col.gas": "Gas %", + "uboot.dc.col.bulkhead": "Bulkhead", + "uboot.dc.closed": "shut", + "uboot.dc.open": "open", + "uboot.dc.label.power": "Power", + "uboot.dc.power_on": "on", + "uboot.dc.power_off": "out: no motor, hand pumps only", + "uboot.dc.label.team": "Team {number}", + "uboot.dc.team_at": "{compartment}: {task}", + "uboot.dc.team_transit": "to {compartment} ({seconds} s)", + "uboot.dc.label.order": "Order", + "uboot.dc.order": "{compartment}: {task}", + "uboot.compartment.bow": "Bow room", + "uboot.compartment.control": "Control room", + "uboot.compartment.quarters": "Quarters", + "uboot.compartment.battery": "Battery room", + "uboot.compartment.engine": "Engine room", + "uboot.compartment.stern": "Stern room", + "uboot.dc.task.idle": "stand by", + "uboot.dc.task.seal": "seal leak", + "uboot.dc.task.pump": "pump out", + "uboot.dc.task.fire": "fight fire", + "uboot.footer.dc_bulkhead": "BULKHEAD", + "uboot.local.dc_team": "Team {team}: {compartment}, {task}.", + "uboot.local.dc_bulkhead_closed": "{compartment}: bulkheads shut.", + "uboot.local.dc_bulkhead_open": "{compartment}: bulkheads open.", + "uboot.local.dc_unavailable": "Damage control cannot be ordered now.", + "uboot.reason.uboot_compartment_down": "compartment flooded, burning or gassed", + "commander.web.reason_uboot_compartment_down": "The compartment for this is flooded, burning or gassed.", + "uboot.event.dc_leak": "Water coming in: {compartment}.", + "uboot.event.dc_fire": "Fire: {compartment}.", + "uboot.event.dc_fire_out": "Fire out: {compartment}.", + "uboot.event.dc_leak_sealed": "Leak sealed: {compartment}.", + "uboot.event.dc_flooded": "{compartment} flooded.", + "uboot.event.dc_chlorine": "Chlorine gas: seawater on the battery.", + "uboot.event.dc_power_lost": "Power lost: motor stopped, pumps by hand.", + "uboot.event.dc_power_restored": "Power restored.", + "help.uboot.dc_select": "Engine room, damage page: pick a compartment (up/down) and a task (left/right)", + "help.uboot.dc_team": "Engine room, damage page: send team 1 (Shift: team 2) with the task", + "help.uboot.dc_bulkhead": "Engine room, damage page: shut or open the compartment's bulkheads", + "commander.web.uboot_dc_title": "Damage control", + "commander.web.uboot_dc_compartments": "Compartments", + "commander.web.uboot_dc_col_compartment": "Compartment", + "commander.web.uboot_dc_col_water": "Water t", + "commander.web.uboot_dc_col_leak": "Leak %", + "commander.web.uboot_dc_col_fire": "Fire %", + "commander.web.uboot_dc_col_gas": "Gas %", + "commander.web.uboot_dc_col_teams": "Teams", + "commander.web.uboot_dc_col_bulkhead": "Bulkheads", + "commander.web.uboot_dc_teams": "Teams and power", + "commander.web.uboot_dc_team": "Team", + "commander.web.uboot_dc_team_1": "Team 1", + "commander.web.uboot_dc_team_2": "Team 2", + "commander.web.uboot_dc_compartment": "Compartment", + "commander.web.uboot_dc_task": "Task", + "commander.web.uboot_dc_send": "Send team", + "commander.web.uboot_dc_bulkhead_close": "Shut", + "commander.web.uboot_dc_bulkhead_open": "Open", + "commander.web.uboot_dc_bulkhead_close_label": "Shut the bulkheads of the {compartment}", + "commander.web.uboot_dc_bulkhead_open_label": "Open the bulkheads of the {compartment}", + "commander.web.uboot_dc_power": "Power", + "commander.web.uboot_dc_power_on": "Power on", + "commander.web.uboot_dc_power_off": "Power out", + "commander.web.uboot_dc_team_transit": "on the way to {compartment} ({seconds} s)", + "commander.web.uboot_dc_team_at": "{compartment}: {task}", + "commander.web.uboot_dc_warning_power": "Power out: the motor stops and teams pump by hand.", + "commander.web.uboot_dc_warning_fire": "Fire: {compartments}.", + "commander.web.uboot_dc_warning_leak": "Water coming in: {compartments}.", + "commander.web.uboot_dc_warning_gas": "Chlorine gas in the boat.", + "commander.web.uboot_compartment_bow": "Bow room", + "commander.web.uboot_compartment_control": "Control room", + "commander.web.uboot_compartment_quarters": "Quarters", + "commander.web.uboot_compartment_battery": "Battery room", + "commander.web.uboot_compartment_engine": "Engine room", + "commander.web.uboot_compartment_stern": "Stern room", + "commander.web.uboot_dc_task_idle": "Stand by", + "commander.web.uboot_dc_task_seal": "Seal leak", + "commander.web.uboot_dc_task_pump": "Pump out", + "commander.web.uboot_dc_task_fire": "Fight fire", + "uboot.footer.dc_team": "TEAM 1 (SHIFT 2)", + "uboot.threat.power": "POWER OUT", + "uboot.threat.fire": "FIRE: {compartment}", + "uboot.threat.leak": "LEAK: {compartment}", + "uboot.footer.dc_pick": "PICK" } diff --git a/data/manual/10-reference.de.md b/data/manual/10-reference.de.md index 82b88c62..09847460 100644 --- a/data/manual/10-reference.de.md +++ b/data/manual/10-reference.de.md @@ -108,7 +108,8 @@ Eine zweite Crew kann den Gegner spielen. Das Boot hat sechs Stationen: Führung - **Befehle und Waffen:** das Boot folgt Kurs-, Fahrt- und Tiefenbefehlen im Rahmen seiner Wende-, Tiefen- und Beschleunigungsgrenzen; Fahrtstufen (Stopp, 3, 6, 10, 15 kn, Maximum) setzen die Fahrt schnell. Schießt einen Torpedo auf die gemessene Peilung eines Sonarkontakts, mit Ping-Fix oder TMA-Lösung, solange aktuell, oder auf eine freie Peilung mit optionaler Entfernung; der Schuss braucht ein klares Rohr und das Ziel im Schussfeld der Rohre. Die Crew stellt die Lauftiefe ein (5-300 m, sonst eine flache Voreinstellung) und schießt einen Torpedo oder zwei im Fächer von ±4°, jeder mit eigenem Datum. Jeder Crew-Torpedo läuft am Draht: die Crew kann sein Datum versetzen (Peilung und Entfernung vom Boot), und der Draht dreht ihn darauf ein, bis sein Suchkopf erfasst; schneller als 10 kn oder stärker als 1,5°/s drehen für 5 s lässt den Draht reißen, ebenso eine abgelaufene Spule, und die Crew kann ihn kappen. Stößt einen Täuschkörper aus und bläst im Notfall die Hauptzellen an (mit voller Pressluft dreimal). - **Anlage und Bootsbetrieb:** ein besetztes Boot taucht nie von selbst auf, schnorchelt nicht und funkt nicht von selbst. Die Batterie entlädt sich mit Fahrt und Bordnetz; unter 20 % warnt das Bootslog, eine leere Batterie begrenzt die Fahrt auf das, was die Anlage noch liefert (eine AIP-Anlage übernimmt die Last weiterhin selbst). **Schnorcheln** betreibt die Diesel auf Schnorcheltiefe und lädt die Batterie, höchstens 6 kn; tieferes Tauchen schließt das Kopfventil. Die laufenden Diesel sind laut: +12 dB abgestrahlter Pegel, ein niedrigerer Stillefaktor und zwei Zündlinien bei 50 und 100 Hz in der LOFAR-Signatur des Boots (auch bei KI-Booten). **Schleichfahrt** begrenzt das Boot auf 5 kn und macht es so leise wie ein lauerndes KI-Boot. **Auf Grund legen** stoppt das Boot 3 m über dem Grund, wo das Wasser nicht tiefer als die Tauchtiefe ist: leise und ohne Drift; jeder Fahrt- oder Tiefenbefehl hebt ab. Vor Land oder einer Untiefe stoppt das Boot, statt auszuweichen, und das Log warnt bei wenig Wasser unter dem Kiel. - **Energie und Vorräte:** die Maschine zeigt unter **Energie & Vorräte** (Karte im Browser, auf der uConsole Maschine Seite 2 **Vorräte**) die Energiebilanz bei der aktuellen Fahrt (Verbrauch, Erzeugung und Bilanz in kW, die Zeit bis die Batterie leer oder voll ist), Batterie und AIP-Sauerstoff, die Dieselbunker und eine Tabelle, wie lange die Batterie getaucht bei jeder Telegrafenstufe reicht und wie weit das Boot damit kommt. **Diesel:** die Bunker fassen 300 Stunden volle Generatorleistung, eine Fahrt beginnt mit 65 %; nur laufende Diesel verbrauchen (0,27 l je kWh), das Log warnt bei 10 %, und mit leeren Bunkern lädt Schnorcheln nicht mehr. Die **Laderate** bestimmt, was Schnorcheln tut: *voll* (die ganze Generatorleistung, +12 dB und beide Diesellinien), *halb* (die halbe Leistung, +9 dB, schwächere Linien) oder *nur lüften* (die Lüfter ohne Diesel, +4 dB, keine Linien). **Luft:** getaucht verbraucht die Crew Sauerstoff und atmet Kohlendioxid aus (je etwa 0,45 % pro Stunde); ein CO2-Absorbersatz nimmt CO2 auf, bis er verbraucht ist (8 Ersatzsätze), eine O2-Kerze setzt in 15 Minuten 1 % O2 zu (12 an Bord, eine zur Zeit), und Schnorcheln lüftet das Boot in wenigen Minuten Richtung Frischluft. Ab 3 % CO2 oder unter 18 % O2 ist die Luft verbraucht, ab 5 % CO2 oder unter 16 % O2 gefährlich; das Log warnt bei jeder Stufe. Schlechte Luft macht die Crew langsamer (bis 30 % Leistung), und die Torpedomannschaft lädt entsprechend langsamer nach. KI-Boote versorgen ihre Luft selbst und tauchen zum Lüften auf, wenn sie gefährlich wird. Ein Atom-U-Boot hat keine dieser Vorräte. -- **Tauchzellen, Trimm und Pressluft:** die Maschine zeigt unter **Tauchzellen & Trimm** (Karte im Browser mit Schnittbild des Boots, auf der uConsole Maschine Seite 3 **Zellen**) die Hauptzellen, die Regelzelle, die Trimmzellen, die Pressluft und den Trimmzustand des Boots. Jede Gewichtsänderung bringt das Boot aus dem Gleichgewicht: ein Torpedo aus einem Bugrohr macht es 1,5 t leichter und achterlastig, Wasser durch den beschädigten Druckkörper (über 30 % Schaden, bis 30 t bei 100 %) schwerer. Mit der **Trimmautomatik** pumpt der LI die Regelzelle (±8 t, 25 kg/s) und die Trimmzellen (±3 t vorn und achtern, 15 kg/s) zurück ins Gleichgewicht; von Hand verschiebt jeder Befehl die Regelzelle um 0,5 t oder das Trimmwasser um 0,25 t (und schaltet die Automatik aus). Laufende Trimmpumpen sind hörbar (+3 dB und eine Linie bei 120 Hz). Was die Zellen nicht aufnehmen, lässt das Boot mit 0,03 m/s je Tonne sinken oder steigen, und ein Trimmwinkel (1° je Tonne Moment, + vorlastig) drückt es mit Fahrt nach unten oder oben; die Tiefenruder halten das nur mit Fahrt, ein schweres Boot sinkt bei wenig Fahrt unter seine befohlene Tiefe; das Log warnt ab 2 t und ab 3°. Die **Pressluft** (200 bar) reicht für drei Notanblasungen zu je 60 bar; Anblasen leert die Hauptzellen in 20 s, das Boot steigt auf 10 m und bleibt dort, die befohlene Tiefe steht dann auf 10 m. Der nächste Befehl unter 12 m öffnet die Entlüftung: die Hauptzellen fluten in 40 s, erst dann kann das Boot tauchen. Schnorcheln auf Diesel betreibt den Kompressor (0,05 bar/s); mit nur lüften läuft er nicht. Die KI-Boote halten sich selbst im Trimm und behalten ihr eines Notanblasen. +- **Tauchzellen, Trimm und Pressluft:** die Maschine zeigt unter **Tauchzellen & Trimm** (Karte im Browser mit Schnittbild des Boots, auf der uConsole Maschine Seite 3 **Zellen**) die Hauptzellen, die Regelzelle, die Trimmzellen, die Pressluft und den Trimmzustand des Boots. Jede Gewichtsänderung bringt das Boot aus dem Gleichgewicht: ein Torpedo aus einem Bugrohr macht es 1,5 t leichter und achterlastig, Wasser in vollgelaufenen Abteilungen (siehe Leckwehr) macht es schwerer und trimmt es zum gefluteten Ende; die Trimmautomatik gleicht davon aus, was ihre Zellen fassen. Mit der **Trimmautomatik** pumpt der LI die Regelzelle (±8 t, 25 kg/s) und die Trimmzellen (±3 t vorn und achtern, 15 kg/s) zurück ins Gleichgewicht; von Hand verschiebt jeder Befehl die Regelzelle um 0,5 t oder das Trimmwasser um 0,25 t (und schaltet die Automatik aus). Laufende Trimmpumpen sind hörbar (+3 dB und eine Linie bei 120 Hz). Was die Zellen nicht aufnehmen, lässt das Boot mit 0,03 m/s je Tonne sinken oder steigen, und ein Trimmwinkel (1° je Tonne Moment, + vorlastig) drückt es mit Fahrt nach unten oder oben; die Tiefenruder halten das nur mit Fahrt, ein schweres Boot sinkt bei wenig Fahrt unter seine befohlene Tiefe; das Log warnt ab 2 t und ab 3°. Die **Pressluft** (200 bar) reicht für drei Notanblasungen zu je 60 bar; Anblasen leert die Hauptzellen in 20 s, das Boot steigt auf 10 m und bleibt dort, die befohlene Tiefe steht dann auf 10 m. Der nächste Befehl unter 12 m öffnet die Entlüftung: die Hauptzellen fluten in 40 s, erst dann kann das Boot tauchen. Schnorcheln auf Diesel betreibt den Kompressor (0,05 bar/s); mit nur lüften läuft er nicht. Ohne Strom laufen weder Trimmpumpen noch Kompressor. Die KI-Boote halten sich selbst im Trimm und behalten ihr eines Notanblasen. +- **Leckwehr:** die Maschine zeigt unter **Leckwehr** (Karte im Browser mit den Abteilungen und einer Tabelle, auf der uConsole Maschine Seite 4 **Leckwehr**) den Druckkörper in sechs Abteilungen: Bugraum, Zentrale, Wohnraum, Batterieraum, Maschinenraum und Heckraum. Ein Treffer auf das besetzte Boot schlägt ein Leck in die getroffene Abteilung (1,5 % Leck je % Trefferschaden, höchstens ein volles Leck; ab 50 % Schaden auch in die Nachbarabteilung mit halbem Leck) und kann dort einen Brand auslösen (Wahrscheinlichkeit = Schaden / 150); ein Ermüdungsriss unter der Testtiefe öffnet ein kleines Leck. Durch ein volles Leck dringen in 100 m Tiefe 40 kg/s ein, mit der Wurzel der Tiefe mehr; über halbvoll läuft das Wasser in offene Nachbarabteilungen über (20 kg/s) und erstickt einen Brand. Ein Brand wächst in 2 min zum Vollbrand und greift dann durch offene Schotten über; Seewasser im Batterieraum (ab 2 t) setzt Chlorgas frei, das durch offene Schotten zieht und erst langsam abzieht, wenn die Batterie trocken ist. Wasser im Batterieraum (ab 5 t) oder ein Brand dort legen den **Strom** lahm: der Motor steht (keine Fahrt, also halten die Tiefenruder ein schweres Boot nicht), Trimmpumpen, Kompressor und elektrische Lenzpumpen stehen still. **Schotten schließen** hält Wasser, Brand und Gas in der Abteilung und erstickt einen Brand dort in 3 min. Zwei **Leckwehrtrupps** gehen durchs Boot (8 s je Abteilung) und **dichten ein Leck ab** (ein volles in 60 s), **lenzen** (30 kg/s, ohne Strom ein Viertel von Hand) oder **löschen einen Brand** (einen Vollbrand in 60 s); im Gas arbeiten sie halb so schnell, und in einer zu 90 % vollen Abteilung können sie nur lenzen. Eine Abteilung, die zur Hälfte voll Wasser ist, halb brennt oder halb vergast ist, legt ihre Station lahm: der Bugraum die Torpedorohre, die Zentrale Mast und Sehrohr, der Maschinenraum die Diesel, der Heckraum die halbe Höchstfahrt. Das Wasser ist Gewicht und Moment für den Trimm (siehe oben); ein Boot, das unter die 1,5-fache Testtiefe sinkt, wird zerdrückt. Das Log meldet Lecks, Brände, abgedichtete Lecks, gelöschte Brände, vollgelaufene Abteilungen, Chlorgas und den Strom. - **Lagebild:** ein gehörter Aktivping oder Torpedo wird mit der Peilung protokolliert, die das Boot selbst gemessen hat (einige Grad ungenau), und mit seinem Alter in den Alarmen angezeigt. Auf Sehrohrtiefe lässt sich der **Mast** ausfahren; sein ESM meldet dann die Radare, die das Boot überstreichen, mit Peilung (Log und ESM-Liste), und beim Tieferkommen fährt der Mast selbst ein. Mit ausgefahrenem Mast zeigt die Seite **Sehrohr** (Führung Seite 3, Mast & ESM Seite 2; `P` fährt an beiden den Mast aus) das Okular: Himmel und See im Licht der Stunde, den mit der See bewegten Horizont, eine Skala rechtweisender Peilungen und ein Fadenkreuz; das Rohr schwenkt in 2°-Schritten (`←`/`→`, `Umschalt`: 10°). Alles, was die Optik im Kontrastmodell des Fregattenausgucks bei 2,5 m Augenhöhe ausmacht (Tag/Nacht, Mond, Sicht, Seegang, Land im Weg), erscheint als Silhouette und als reine Peilungs-**Sichtung** mit grober Klasse (Kriegsschiff, Handelsschiff, Fahrzeug, Luftfahrzeug, Torpedolaufbahn) und scheinbarer Länge; das Log meldet jede neue Sichtung. `Enter` liest das **Stadimeter** an der Sichtung unter dem Fadenkreuz ab: die Entfernung folgt aus der scheinbaren Länge und der angenommenen Rumpflänge der Klasse (130 m für ein Kriegsschiff oder ein nicht erkanntes Fahrzeug, 150 m für ein Handelsschiff), ein nicht erkanntes oder bugwärts stehendes Ziel misst sich also zu weit; die Ablesung ist ±25 % und wird für 120 s zu einem VISUAL-Fix am Sonarkontakt des Boots auf dieses Ziel, für einen Schuss nutzbar wie ein Ping-Fix. Luftfahrzeuge und Laufbahnen lassen sich nicht messen. Die kartierte Küste steht auf dem Horizont des Sehrohrs, so weit seine niedrige Optik Land sieht (Hügel mit 25 bis 70 m angenommen). Die Führung kann auch ohne Sonarbediener pingen und eine BT-Messung nehmen. Die Karte zeigt das Schussfeld der Rohre, wo sie nicht rundum schießen, und das vom Sonar zugewiesene Ziel ist für den Schuss vorausgewählt. - **Mast & ESM:** mit ausgefahrenem Mast auf Sehrohrtiefe hört die ESM-Antenne des Boots (3 m über Wasser) einmal pro Sekunde die Radare ringsum: das der Fregatte, anderer Schiffe und von Flugzeugen innerhalb des Radarhorizonts, über Land nur, wo die Küste die Linie nicht verdeckt. Jede Erfassung trägt die gemessene Peilung (±4°), Band, Trägerfrequenz, PRF, Modulation und Empfangspegel, nie die Identität oder Position des Senders. Die Crew führt eine **Emitterliste** (`E1`, `E2` …) über mehrere Mastperioden: eine Erfassung gehört zu einem Emitter, wenn Peilung, Band und Signalform passen (ein frequenzagiles Radar nur nach Peilung und Band), und die Liste vergisst einen Emitter 30 Minuten nach seiner letzten Erfassung. Die **Einstufung** ist die Annotation der Crew aus der Bibliothek: die Emitter, deren veröffentlichte Frequenz- und PRF-Bereiche die Messung enthalten, ungewichtet, wie an der ELOKA der Fregatte ohne Assistenz; die Wahl legt die Leistungsklasse für die **Entfernungsschätzung** aus dem Pegel fest (ohne Einstufung die kürzeste Entfernung, die die Bibliothek zulässt). Alle 30 s behält jeder Emitter eine **Peilung** von der eigenen Position des Boots (20 Minuten); die Karte zeigt die letzten Peillinien, und sobald die eigene Fahrt die Peilung um mindestens 8° gedreht hat, ist die **Kreuzpeilung** ihr bester Schnittpunkt mit einer 95-%-Fehlerellipse, die einen seit jeder Linie bis zu 8 kn versetzten Sender einrechnet (eine schnelle Fregatte ergibt meist keine; eine Kreuzpeilung, deren Linien nicht zusammenpassen, wird markiert). Der **Stärketrend** zeigt steigend, gleichbleibend oder fallend über fünf Minuten. Die **Mastwarnung** („Radar kann Mast sehen“) kommt, wenn die geschätzte Entfernung eines erfassten Suchradars innerhalb der Entfernung liegt, auf der ein Seeraumradar bei diesem Seegang und Regen einen ausgefahrenen Mast sieht (der Wert der Wetterseite); die **empfohlene Mastzeit** ist 60 s bei ruhiger See, bis zu 300 s, wenn die Seegangsechos den Mast verbergen, und 20 s unter dieser Warnung, und das Log meldet, wenn sie überschritten ist. Ab Seegang 3 überspülen Wellen die Antenne, und manche Durchläufe hören nichts. Die Karte Mast & ESM im Browser hat die Rose, die Emittertabelle und die Auswertung des gewählten Emitters; **In den Plot übernehmen** trägt die Kreuzpeilung (Markierung und Fehlerkreis) oder sonst die letzte Peillinie in den Plot des Boots ein. Auf der Seite Mast & ESM der uConsole wählen `↑`/`↓` einen Emitter, `←`/`→` schalten seine Einstufung aus der Bibliothek weiter und `Enter` übernimmt ihn in den Plot. - **Navigation und Plot:** die Maschine hat Maschinentelegrafen-Knöpfe, und Führung und Navigation teilen den eigenen Fettstift-Plot des Boots (Markierungen, Lineale, Peillinien, Kreise, Koppellinien); die Fregatte sieht ihn nie, und der Plot des Boots wird nicht gespeichert. Die Navigation zeigt das Wasser unter dem Kiel und prüft die Seekarte entlang des Sollkurses bis 5 sm: Land oder ein Grund flacher als das Boot wird als Hindernis voraus gemeldet, im Log und als Warnung. Es zählt nur die kartierte Geografie; andere Fahrzeuge sind nicht Teil der Prüfung. @@ -121,14 +122,14 @@ Eine zweite Crew kann den Gegner spielen. Das Boot hat sechs Stationen: Führung Jedes neue Spiel fragt zuerst **Welche Einheit spielst du?**: *Fregatte F-217* oder *Feindliches U-Boot* (`Auf`/`Ab` oder `1`/`2`, `Enter`; die letzte Wahl ist vorausgewählt, `--play-sub` wählt das U-Boot vor). Außerhalb einer Mission ändert auch Optionen (`F10`) Seite 2 **uConsole spielt** die Wahl, etwa vor dem Laden eines Spielstands. Mit dem U-Boot führt der uConsole das feindliche Boot statt der Fregatte. Die Fregatte wird dann über Remote Crew (`F9`) aus den Browsern besetzt oder fährt mit Autocrew. Der uConsole zeigt nur das Lagebild des Boots; Banner, Ereignislog, Soundeffekte, Plot und Tooltips der Fregatte erscheinen nie, und Trackball- und Telegraphenbedienung der Fregatte sind gesperrt. Die Seite lässt sich nur außerhalb einer Mission wechseln; die Wahl gilt nur für diesen Programmstart und wird nie gespeichert, jeder Start beginnt also mit der Fregatte. -Die obere Leiste zeigt die sechs Stationen des Boots als Reiter: `1` Führung, `2` Sonar, `3` Waffen, `4` Maschine, `5` Mast & ESM, `6` Navigation (`Tab` oder ein Klick auf den Reiter wechselt). Jede Befehlstaste wirkt nur an der Station, zu der der Befehl gehört, wie im Browser; sonst nennt ein Banner die richtige Station. Browser können gleichzeitig die übrigen Stationen des Boots besetzen; eine Station, die ein Browser hält, ist in der oberen Leiste markiert und wird nicht vom uConsole bedient. Jede Station außer dem Sonarraum ist aufgebaut wie die Brücke: links die Seekarte (bekannte Geografie, der eigene Plot des Boots, die ESM-Peillinien und Kreuzpeilungen, das eigene Boot mit Sollkurs und Fahrtvektor, die Peilstriche der eigenen Sonarkontakte bzw. ihr Symbol bei aktuellem Ping- oder TMA-Fix, die eigenen Torpedos `T1`…, ein begrenztes Schussfeld der Rohre), rechts die Station mit Bedrohungsleiste (Torpedoalarm und gehörtes Aktivsonar mit gemessener Peilung, Rumpfschaden, Kavitation, schwache Batterie, ESM-Radarerfassung) und die Seite der Station. Die **Führung** und die **Maschine** haben drei Seiten, **Mast & ESM** zwei (die Taste der Station erneut oder `Bild auf`/`Bild ab`). Die zweite Seite der Maschine, **Vorräte**, zeigt Energie, Ausdauer und Luft; `R` wechselt die Laderate, `A` setzt einen Absorbersatz ein und `O` zündet eine O2-Kerze. Ihre dritte Seite **Zellen** zeigt das Schnittbild, Hauptzellen und Pressluft, die Zellen mit ihren Sollwerten, Gewicht, Trimmwinkel, Drift ohne Tiefenruder, Wassereinbruch und Pumpen; `↑`/`↓` lenzen oder fluten die Regelzelle, `←`/`→` pumpen Trimmwasser nach achtern oder vorn und `Z` schaltet die Trimmautomatik. **Navigation** (Seite und Station) zeigt Kurs und Tiefe, das Wasser unter dem Kiel und ein kartiertes Hindernis voraus, Fahrt, Eigenlärm, Batterie und die aktiven Betriebsarten sowie die Wassersäule unter dem Boot: Bootstiefe, befohlene Tiefe, sichere Tiefe und Grund; die Sprungschicht erscheint dort erst nach einer eigenen BT-Messung (`E` am U-Boot-Sonar). **Waffen & Kontakte** (Seite und Station Waffen) zeigt Feuerbereitschaft, Torpedos, klare Rohre, Nachladen, Täuschkörper, Notanblasen und die eigenen Sonarkontakte (Peilung, Entfernung falls bekannt, und Güte in Prozent: der bessere Wert aus Signalgüte und Spurvertrauen, 100 % ist ein sicherer Kontakt). Die **Maschine** zeigt Fahrt, Eigenlärm, Batterie, die Betriebsarten und die Telegrafenstufen; **Mast & ESM** zeigt die Mastzeit, die Rose, die Emitterliste und den gewählten Emitter (Signal, Pegel und Trend, Kreuzpeilung, Einstufung); ihre zweite Seite und die dritte der Führung ist das **Sehrohr** (Okular, Sichtlinie, Licht und die Sichtungsliste; `←`/`→` schwenken, `Enter` Stadimeter). Unten stehen Bootslog und Telemetrie des Boots, als Leiste oder Statuszeile wie in den Optionen eingestellt; Befehle, Schüsse und Täuschkörper werden dort protokolliert. +Die obere Leiste zeigt die sechs Stationen des Boots als Reiter: `1` Führung, `2` Sonar, `3` Waffen, `4` Maschine, `5` Mast & ESM, `6` Navigation (`Tab` oder ein Klick auf den Reiter wechselt). Jede Befehlstaste wirkt nur an der Station, zu der der Befehl gehört, wie im Browser; sonst nennt ein Banner die richtige Station. Browser können gleichzeitig die übrigen Stationen des Boots besetzen; eine Station, die ein Browser hält, ist in der oberen Leiste markiert und wird nicht vom uConsole bedient. Jede Station außer dem Sonarraum ist aufgebaut wie die Brücke: links die Seekarte (bekannte Geografie, der eigene Plot des Boots, die ESM-Peillinien und Kreuzpeilungen, das eigene Boot mit Sollkurs und Fahrtvektor, die Peilstriche der eigenen Sonarkontakte bzw. ihr Symbol bei aktuellem Ping- oder TMA-Fix, die eigenen Torpedos `T1`…, ein begrenztes Schussfeld der Rohre), rechts die Station mit Bedrohungsleiste (Torpedoalarm und gehörtes Aktivsonar mit gemessener Peilung, Rumpfschaden, Kavitation, schwache Batterie, ESM-Radarerfassung) und die Seite der Station. Die **Führung** hat drei Seiten, die **Maschine** vier, **Mast & ESM** zwei (die Taste der Station erneut oder `Bild auf`/`Bild ab`). Die zweite Seite der Maschine, **Vorräte**, zeigt Energie, Ausdauer und Luft; `R` wechselt die Laderate, `A` setzt einen Absorbersatz ein und `O` zündet eine O2-Kerze. Ihre dritte Seite **Zellen** zeigt das Schnittbild, Hauptzellen und Pressluft, die Zellen mit ihren Sollwerten, Gewicht, Trimmwinkel, Drift ohne Tiefenruder, Wassereinbruch und Pumpen; `↑`/`↓` lenzen oder fluten die Regelzelle, `←`/`→` pumpen Trimmwasser nach achtern oder vorn und `Z` schaltet die Trimmautomatik. Ihre vierte Seite **Leckwehr** zeigt die Abteilungen (Wasser, Leck, Brand, Gas, geschlossene Schotten, Trupps), die Tabelle der Abteilungen, den Strom und beide Trupps; `↑`/`↓` wählen eine Abteilung, `←`/`→` eine Aufgabe, `Enter` schickt Trupp 1 und `Umschalt+Enter` Trupp 2 mit dieser Aufgabe dorthin, und `I` schließt oder öffnet die Schotten der Abteilung. **Navigation** (Seite und Station) zeigt Kurs und Tiefe, das Wasser unter dem Kiel und ein kartiertes Hindernis voraus, Fahrt, Eigenlärm, Batterie und die aktiven Betriebsarten sowie die Wassersäule unter dem Boot: Bootstiefe, befohlene Tiefe, sichere Tiefe und Grund; die Sprungschicht erscheint dort erst nach einer eigenen BT-Messung (`E` am U-Boot-Sonar). **Waffen & Kontakte** (Seite und Station Waffen) zeigt Feuerbereitschaft, Torpedos, klare Rohre, Nachladen, Täuschkörper, Notanblasen und die eigenen Sonarkontakte (Peilung, Entfernung falls bekannt, und Güte in Prozent: der bessere Wert aus Signalgüte und Spurvertrauen, 100 % ist ein sicherer Kontakt). Die **Maschine** zeigt Fahrt, Eigenlärm, Batterie, die Betriebsarten und die Telegrafenstufen; **Mast & ESM** zeigt die Mastzeit, die Rose, die Emitterliste und den gewählten Emitter (Signal, Pegel und Trend, Kreuzpeilung, Einstufung); ihre zweite Seite und die dritte der Führung ist das **Sehrohr** (Okular, Sichtlinie, Licht und die Sichtungsliste; `←`/`→` schwenken, `Enter` Stadimeter). Unten stehen Bootslog und Telemetrie des Boots, als Leiste oder Statuszeile wie in den Optionen eingestellt; Befehle, Schüsse und Täuschkörper werden dort protokolliert. ### Nicht modelliert {#ref-opfor-limits} - Das besetzte Boot funkt nicht und empfängt nichts; es gibt keine Kontaktmeldung von der Führung an Land. -- Keine Leckwehr- oder Schadensteams an Bord; Schäden summieren sich nur. +- Die Leckwehr kennt sechs Abteilungen und zwei Trupps: keine getrennten Schäden an Druck- und Außenhülle, keine Verletzten, keine Ausbreitung von Rauch oder Hitze, kein Brand in den Luftvorräten und kein Sauerstoffverbrauch durch Feuer; der Gesamtschaden des Boots (Lärm, Höchstfahrt, Untergang bei 100 %) summiert sich weiter aus Treffern, und die KI-Boote haben nur diesen Wert. - Das Trimmmodell kennt ein Gewicht und ein Moment: keinen Effekt freier Oberflächen, keine Kompressibilität des Druckkörpers mit der Tiefe und keine eigene Schnelltauchzelle; das Boot taucht nicht ganz auf. Proviant und Frischwasser gehen nicht aus. - Ein ausgefahrener Mast oder Schnorchelkopf erscheint auf dem Fregattenradar nur als bloßer Punkt (siehe Kapitel OPZ). - Das ESM des Boots hört keine Radare anderer U-Boote und keine Flugkörpersucher; es hat keine gewichtete Bibliotheksanalyse, keine Messung der Umlaufzeit und keine Bewegungsanalyse eines Senders (die Kreuzpeilung nimmt einen langsamen Sender an). diff --git a/data/manual/10-reference.en.md b/data/manual/10-reference.en.md index 76d022f0..0c4ae914 100644 --- a/data/manual/10-reference.en.md +++ b/data/manual/10-reference.en.md @@ -108,7 +108,8 @@ A second crew can play the enemy. The boat has six stations: Command, Sonar, Wea - **Orders and weapons:** the boat follows course, speed and depth orders within its turn, depth and acceleration limits; telegraph steps (stop, 3, 6, 10, 15 kn, maximum) set the speed quickly. Fires a torpedo down a sonar contact's measured bearing, with its ping fix or TMA solution while current, or down a free bearing with an optional range; firing needs a ready tube and the target inside the tube arc. The crew sets the run depth (5-300 m, otherwise a shallow default) and fires one torpedo or two in a ±4° spread, each with its own datum. Every crew torpedo runs on a wire: the crew can move its datum (bearing and distance from the boat) and the wire turns it onto the new datum until its seeker acquires; faster than 10 kn or turning harder than 1.5°/s for 5 s breaks the wire, as does running out of either spool, and the crew can cut it. Launches a decoy and blows main ballast in an emergency (three times on a full air store). - **Plant and boat modes:** a crewed boat never goes up, snorkels or calls home by itself. The battery drains with speed and hotel load; below 20 % the log warns, and an empty battery limits the speed to what the plant can serve (an AIP plant still takes over the load by itself). **Snorkel** runs the diesels at snorkel depth and charges the battery, at most 6 kn; diving deeper shuts the head valve. The running diesels are loud: +12 dB radiated level, a lower quiet factor and two firing lines at 50 and 100 Hz in the boat's LOFAR signature (AI boats too). **Silent running** limits the boat to 5 kn and makes it as quiet as a lurking AI boat. **Lie on bottom** stops the boat 3 m above the seabed where the water is no deeper than test depth: silent and no drift; any speed or depth order lifts off. The boat stops short of land or a seamount instead of turning away, and the log warns in shallow water. - **Energy and stores:** the engine room's **Energy & stores** (browser card, uConsole Engine room page 2 **Stores**) shows the energy balance at the present speed (load, supply and net kW, the time until the battery is empty or full), the battery and AIP oxygen, the diesel bunkers and a table of how long the battery lasts dived at each telegraph step and how far that carries the boat. **Diesel:** the bunkers hold 300 hours of the generators' full output and a patrol starts with 65 %; only the running diesels burn it (0.27 l per kWh), the log warns at 10 %, and with dry bunkers snorkelling no longer charges. The **charge rate** sets what snorkelling does: *full* (the whole generator output, +12 dB and both diesel lines), *half* (half the output, +9 dB, weaker lines) or *air only* (the fans without diesels, +4 dB, no lines). **Air:** dived, the crew uses oxygen and breathes out carbon dioxide (about 0.45 % per hour each); a CO2 absorber set takes CO2 out until it is spent (8 spare sets), an oxygen candle adds 1 % O2 over 15 minutes (12 aboard, one at a time), and snorkelling flushes the boat toward fresh air within minutes. From 3 % CO2 or below 18 % O2 the air is stale, from 5 % CO2 or below 16 % O2 it is foul; the log warns at each step. Stale air slows the crew (down to 30 % performance), and the torpedo gang reloads accordingly slower. AI boats manage their air by themselves and come up to air the boat when it turns foul. A nuclear boat has none of these stores. -- **Tanks, trim and air:** the engine room's **Tanks & trim** (browser card with a cross-section of the boat, uConsole Engine room page 3 **Tanks**) shows the main ballast, the regulating tank, the trim tanks, the high-pressure air and the trim the boat is in. Every weight change moves the boat off neutral: a torpedo leaving a bow tube makes it 1.5 t lighter and bow light, water through a holed hull (above 30 % damage, up to 30 t at 100 %) makes it heavier. With the **automatic trim** on, the engineer pumps the regulating tank (±8 t, 25 kg/s) and the trim tanks (±3 t fore and aft, 15 kg/s) back to neutral; by hand, each order moves the regulating tank 0.5 t or the trim water 0.25 t (and switches the automatic off). Running trim pumps are audible (+3 dB and a 120 Hz line). Whatever the tanks cannot take up sinks or lifts the boat by 0.03 m/s per tonne, and a trim angle (1° per tonne of moment, + bow down) drives it down or up with speed; the hydroplanes hold that only with way on, so a heavy boat hovering at low speed sinks below its ordered depth; the log warns from 2 t and from 3°. The **high-pressure air** (200 bar) holds three emergency blows of 60 bar each; a blow empties the main ballast in 20 s and the boat rises to 10 m and stays there, the ordered depth reset to 10 m. The next order below 12 m opens the vents: the main ballast floods in 40 s before the boat can dive. Snorkelling on the diesels runs the compressor (0.05 bar/s); with the air only on the fans it does not. The AI's boats keep themselves trimmed and keep their one legacy blow. +- **Tanks, trim and air:** the engine room's **Tanks & trim** (browser card with a cross-section of the boat, uConsole Engine room page 3 **Tanks**) shows the main ballast, the regulating tank, the trim tanks, the high-pressure air and the trim the boat is in. Every weight change moves the boat off neutral: a torpedo leaving a bow tube makes it 1.5 t lighter and bow light, water in flooded compartments (see damage control) makes it heavier and trims it toward the flooded end; the automatic trim takes up what its tanks can of that weight and moment. With the **automatic trim** on, the engineer pumps the regulating tank (±8 t, 25 kg/s) and the trim tanks (±3 t fore and aft, 15 kg/s) back to neutral; by hand, each order moves the regulating tank 0.5 t or the trim water 0.25 t (and switches the automatic off). Running trim pumps are audible (+3 dB and a 120 Hz line). Whatever the tanks cannot take up sinks or lifts the boat by 0.03 m/s per tonne, and a trim angle (1° per tonne of moment, + bow down) drives it down or up with speed; the hydroplanes hold that only with way on, so a heavy boat hovering at low speed sinks below its ordered depth; the log warns from 2 t and from 3°. The **high-pressure air** (200 bar) holds three emergency blows of 60 bar each; a blow empties the main ballast in 20 s and the boat rises to 10 m and stays there, the ordered depth reset to 10 m. The next order below 12 m opens the vents: the main ballast floods in 40 s before the boat can dive. Snorkelling on the diesels runs the compressor (0.05 bar/s); with the air only on the fans it does not. Without power neither the trim pumps nor the compressor run. The AI's boats keep themselves trimmed and keep their one legacy blow. +- **Damage control:** the engine room's **Damage control** (browser card with the compartments and a table, uConsole Engine room page 4 **Damage**) divides the pressure hull into six compartments: bow room, control room, quarters, battery room, engine room and stern room. A hit on the crewed boat holes the compartment it strikes (a leak of 1.5 % per % of hit damage, up to a full hole; from 50 % damage the neighbour too, with half the leak) and may start a fire there (chance = damage / 150); a fatigue crack below test depth opens a small leak. Water comes in at 40 kg/s through a full hole at 100 m, growing with the square root of depth; above half a compartment it spills into open neighbours (20 kg/s) and smothers a fire. A fire grows to full in 2 min and then spreads through open bulkheads; seawater in the battery room (from 2 t) gives off chlorine gas that drifts through open bulkheads and clears slowly once the battery is dry. Water in the battery room (from 5 t) or a fire there cuts the **power**: the motor stops (no way on, so the hydroplanes do not hold a heavy boat), and the trim pumps, compressor and electric bilge pumps stand still. **Shutting the bulkheads** of a compartment keeps water, fire and gas in it and starves a fire there in 3 min. Two **damage-control teams** walk the boat (8 s per compartment) and **seal a leak** (a full hole in 60 s), **pump out** (30 kg/s, a quarter by hand without power) or **fight a fire** (a full fire in 60 s); in gas they work at half rate, and in a compartment 90 % full they can only pump. A compartment half full of water, half on fire or half gassed takes its station out: the bow room the torpedo tubes, the control room the mast and periscope, the engine room the diesels, the stern room half the top speed. The floodwater is weight and moment for the trim (see above); a boat that sinks below 1.5 x test depth is crushed. The log reports leaks, fires, sealed leaks, fires out, flooded compartments, chlorine and power. - **Situation picture:** an intercepted active ping or torpedo is logged with the bearing the boat's own ears measured (a few degrees off) and shown with its age in the alarms. At periscope depth the **mast** can be raised; its ESM then reports the radars sweeping the boat with bearing (log and ESM list), and the mast lowers by itself when the boat goes deeper. With the mast up the **periscope** page (Command page 3, Mast & ESM page 2; `P` raises the mast at both) shows the eyepiece: sky and sea in the light of the hour, the horizon moving with the sea, a true-bearing scale and a crosshair; the scope trains in 2° steps (`←`/`→`, `Shift`: 10°). Everything the optics make out within the frigate lookout's contrast model at 2.5 m eye height (day/night, moon, visibility, sea state, land in the way) appears as a silhouette and as a bearing-only **sighting** with a coarse class (warship, merchant ship, vessel, aircraft, torpedo wake) and its apparent length; the log reports each new sighting. `Enter` reads the **stadimeter** on the sighting under the crosshair: the range follows from its apparent length and the assumed hull length of the class (130 m for a warship or an unrecognized vessel, 150 m for a merchant), so an unrecognized or bow-on target reads long; the reading is ±25 % and becomes a VISUAL fix on the boat's sonar contact of that target for 120 s, usable for a shot like a ping fix. Aircraft and wakes cannot be ranged. The charted coast stands on the periscope's horizon as far as its low optics see land (hills assumed 25 to 70 m). Command can also ping and take a BT without a sonar operator. The chart shows the tube firing arc where the tubes cannot fire all round, and the sonar room's assigned target is preselected for the shot. - **Mast & ESM:** with the mast up at periscope depth the boat's own ESM antenna (3 m above the water) hears the radars around it once a second: the frigate's, other ships' and aircraft radars inside the radar horizon, over land only where the coast does not block the line. Each intercept carries the measured bearing (±4°), band, carrier frequency, PRF, modulation and received level, never the emitter's identity or position. The crew keeps an **emitter list** (`E1`, `E2` …) across mast periods: an intercept joins an emitter when bearing, band and waveform agree (a frequency-agile radar by bearing and band only), and the list forgets an emitter 30 minutes after its last intercept. **Classification** is the crew's annotation from the library: the emitters whose published frequency and PRF ranges hold the measurement, unranked, as at the frigate's ELOKA without assistance; the choice sets the power class for the **range estimate** from the level (unclassified: the shortest range the library allows). Every 30 s each emitter keeps a **bearing** from the boat's own position (20 minutes); the chart shows the latest bearing lines, and once the boat's own motion has swung the bearing by at least 8°, the **cross-fix** is their best crossing with a 95 % error ellipse that allows for an emitter drifting up to 8 kn since each line (a fast frigate usually gives none; a fix whose lines disagree is marked). The **level trend** reads rising, steady or falling over five minutes. The **mast warning** ("radar can see the mast") comes when a live search radar's estimated range is inside the range at which a surface radar sees a raised mast in this sea and rain (the weather page's value); the **recommended mast time** is 60 s in a calm sea, up to 300 s when sea clutter hides the mast and 20 s under that warning, and the log reports when it is exceeded. From sea state 3 waves wash over the antenna and some scans hear nothing. The browser's Mast & ESM card has the rose, the emitter table and the selected emitter's evaluation; **Transfer to plot** puts the cross-fix (mark and error circle) or else the latest bearing line into the boat's plot. On the uConsole's Mast & ESM page `↑`/`↓` select an emitter, `←`/`→` step through its library classification and `Enter` transfers it to the plot. - **Navigation and plot:** the engine room has telegraph buttons, and Command and Navigation share the boat's own grease-pencil plot (marks, rulers, bearing lines, circles, DR lines); the frigate never sees it, and the boat's plot is not saved. The navigation display shows the water under the keel and checks the chart along the ordered course up to 5 NM: land or a seabed shallower than the boat is reported as an obstacle ahead, in the log and as a warning. Only charted geography counts; other vessels are not in the check. @@ -121,14 +122,14 @@ A second crew can play the enemy. The boat has six stations: Command, Sonar, Wea Every new game first asks **Which unit do you play?**: *Frigate F-217* or *Hostile submarine* (`Up`/`Down` or `1`/`2`, `Enter`; the last choice is preselected, `--play-sub` preselects the submarine). Outside a mission, Options (`F10`) page 2 **uConsole plays** changes it as well, for example before loading a game. With the submarine the uConsole commands the hostile boat instead of the frigate. The frigate is then crewed from the browsers through Remote Crew (`F9`) or runs on autocrew. The uConsole shows only the boat's own picture; the frigate's banners, event log, sound cues, plot and tooltips never appear, and its trackball and telegraph controls are disabled. The side can only be changed outside a mission; it lasts for this launch and is never saved, so every launch starts with the frigate. -The top bar shows the boat's six stations as tabs: `1` Command, `2` Sonar, `3` Weapons, `4` Engine room, `5` Mast & ESM, `6` Navigation (`Tab` or a click on a tab switches). Each order key works only at the station that owns it, as in the browser; elsewhere a banner names the right station. Browsers can crew the boat's other stations at the same time; a station a browser holds is marked in the top bar and is not operated from the uConsole. Every station but the sonar room is laid out like the Bridge: the chart on the left (known geography, the boat's own plot, the ESM bearing lines and cross-fixes, the boat with its ordered course and motion vector, the bearing lines of its own sonar contacts or their symbol while a ping or TMA fix is current, its own torpedoes `T1`…, a limited tube firing arc), the station on the right with a threat bar (torpedo alarm and active sonar heard with measured bearing, hull damage, cavitation, low battery, ESM radar intercept) and the station's page. **Command** and the **Engine room** have three pages, **Mast & ESM** two (the station's key again or `PgUp`/`PgDn`). The Engine room's second page **Stores** shows energy, endurance and air; `R` cycles the charge rate, `A` fits an absorber set and `O` lights an oxygen candle. Its third page **Tanks** shows the cross-section, main ballast and air, the tanks with their orders, weight, trim angle, drift without planes, flooding and pumps; `↑`/`↓` pump out or flood the regulating tank, `←`/`→` move trim water aft or forward and `Z` switches the automatic trim. **Navigation** (page and station) shows course and depth, water under the keel and any charted obstacle ahead, speed, own noise, battery and the active modes, and the water column under the boat: boat depth, ordered depth, safe depth and seabed; the layer appears there only after the boat's own BT measurement (`E` at the submarine sonar). **Weapons & contacts** (page and Weapons station) shows fire readiness, torpedoes, tubes ready, reload, decoys, emergency blow and the boat's own sonar contacts (bearing, range where known, and quality in percent: the better of the signal quality and the track confidence, 100 % being a firm contact). The **Engine room** shows speed, own noise, battery, the modes and the telegraph steps; **Mast & ESM** shows the mast time, the rose, the emitter list and the selected emitter (signal, level and trend, cross-fix, classification); its second page and Command's third are the **Periscope** (eyepiece, line of sight, light and the sightings list; `←`/`→` train, `Enter` stadimeter). Below are the boat log and the boat's telemetry, as a band or a status ticker as set in the options; orders, shots and decoys are logged there. +The top bar shows the boat's six stations as tabs: `1` Command, `2` Sonar, `3` Weapons, `4` Engine room, `5` Mast & ESM, `6` Navigation (`Tab` or a click on a tab switches). Each order key works only at the station that owns it, as in the browser; elsewhere a banner names the right station. Browsers can crew the boat's other stations at the same time; a station a browser holds is marked in the top bar and is not operated from the uConsole. Every station but the sonar room is laid out like the Bridge: the chart on the left (known geography, the boat's own plot, the ESM bearing lines and cross-fixes, the boat with its ordered course and motion vector, the bearing lines of its own sonar contacts or their symbol while a ping or TMA fix is current, its own torpedoes `T1`…, a limited tube firing arc), the station on the right with a threat bar (torpedo alarm and active sonar heard with measured bearing, hull damage, cavitation, low battery, ESM radar intercept) and the station's page. **Command** has three pages, the **Engine room** four, **Mast & ESM** two (the station's key again or `PgUp`/`PgDn`). The Engine room's second page **Stores** shows energy, endurance and air; `R` cycles the charge rate, `A` fits an absorber set and `O` lights an oxygen candle. Its third page **Tanks** shows the cross-section, main ballast and air, the tanks with their orders, weight, trim angle, drift without planes, flooding and pumps; `↑`/`↓` pump out or flood the regulating tank, `←`/`→` move trim water aft or forward and `Z` switches the automatic trim. Its fourth page **Damage** shows the compartments (water, leak, fire, gas, shut bulkheads, teams), the table of compartments, the power and both teams; `↑`/`↓` pick a compartment, `←`/`→` a task, `Enter` sends team 1 and `Shift+Enter` team 2 there with that task, and `I` shuts or opens the compartment's bulkheads. **Navigation** (page and station) shows course and depth, water under the keel and any charted obstacle ahead, speed, own noise, battery and the active modes, and the water column under the boat: boat depth, ordered depth, safe depth and seabed; the layer appears there only after the boat's own BT measurement (`E` at the submarine sonar). **Weapons & contacts** (page and Weapons station) shows fire readiness, torpedoes, tubes ready, reload, decoys, emergency blow and the boat's own sonar contacts (bearing, range where known, and quality in percent: the better of the signal quality and the track confidence, 100 % being a firm contact). The **Engine room** shows speed, own noise, battery, the modes and the telegraph steps; **Mast & ESM** shows the mast time, the rose, the emitter list and the selected emitter (signal, level and trend, cross-fix, classification); its second page and Command's third are the **Periscope** (eyepiece, line of sight, light and the sightings list; `←`/`→` train, `Enter` stadimeter). Below are the boat log and the boat's telemetry, as a band or a status ticker as set in the options; orders, shots and decoys are logged there. ### Not modelled {#ref-opfor-limits} - The crewed boat sends no radio traffic and receives none; there is no contact report from home. -- No damage-control teams aboard the boat; damage only accumulates. +- Damage control is six compartments and two teams: no separate pressure-hull and outer-hull damage, no casualties, no smoke or heat spreading, no fire in the air stores and no fire consuming oxygen; the boat's overall damage (noise, top speed, sinking at 100 %) still adds up from hits, and the AI's boats keep only that value. - The trim model is one weight and one moment: no free-surface effect, no compressibility of the hull with depth and no separate negative tank; the boat does not surface fully. Food and fresh water do not run out. - A raised mast or snorkel head is seen by the frigate's radar only as a bare blip (see the OPZ chapter). - The boat's ESM hears no other submarine's radar and no missile seeker; it has no scored library analysis, no scan-period measurement and no target motion analysis of an emitter (the cross-fix assumes a slow emitter). diff --git a/docs/manual/manual.de.md b/docs/manual/manual.de.md index e4b0bf62..adbc4bab 100644 --- a/docs/manual/manual.de.md +++ b/docs/manual/manual.de.md @@ -1054,7 +1054,8 @@ Eine zweite Crew kann den Gegner spielen. Das Boot hat sechs Stationen: Führung - **Befehle und Waffen:** das Boot folgt Kurs-, Fahrt- und Tiefenbefehlen im Rahmen seiner Wende-, Tiefen- und Beschleunigungsgrenzen; Fahrtstufen (Stopp, 3, 6, 10, 15 kn, Maximum) setzen die Fahrt schnell. Schießt einen Torpedo auf die gemessene Peilung eines Sonarkontakts, mit Ping-Fix oder TMA-Lösung, solange aktuell, oder auf eine freie Peilung mit optionaler Entfernung; der Schuss braucht ein klares Rohr und das Ziel im Schussfeld der Rohre. Die Crew stellt die Lauftiefe ein (5-300 m, sonst eine flache Voreinstellung) und schießt einen Torpedo oder zwei im Fächer von ±4°, jeder mit eigenem Datum. Jeder Crew-Torpedo läuft am Draht: die Crew kann sein Datum versetzen (Peilung und Entfernung vom Boot), und der Draht dreht ihn darauf ein, bis sein Suchkopf erfasst; schneller als 10 kn oder stärker als 1,5°/s drehen für 5 s lässt den Draht reißen, ebenso eine abgelaufene Spule, und die Crew kann ihn kappen. Stößt einen Täuschkörper aus und bläst im Notfall die Hauptzellen an (mit voller Pressluft dreimal). - **Anlage und Bootsbetrieb:** ein besetztes Boot taucht nie von selbst auf, schnorchelt nicht und funkt nicht von selbst. Die Batterie entlädt sich mit Fahrt und Bordnetz; unter 20 % warnt das Bootslog, eine leere Batterie begrenzt die Fahrt auf das, was die Anlage noch liefert (eine AIP-Anlage übernimmt die Last weiterhin selbst). **Schnorcheln** betreibt die Diesel auf Schnorcheltiefe und lädt die Batterie, höchstens 6 kn; tieferes Tauchen schließt das Kopfventil. Die laufenden Diesel sind laut: +12 dB abgestrahlter Pegel, ein niedrigerer Stillefaktor und zwei Zündlinien bei 50 und 100 Hz in der LOFAR-Signatur des Boots (auch bei KI-Booten). **Schleichfahrt** begrenzt das Boot auf 5 kn und macht es so leise wie ein lauerndes KI-Boot. **Auf Grund legen** stoppt das Boot 3 m über dem Grund, wo das Wasser nicht tiefer als die Tauchtiefe ist: leise und ohne Drift; jeder Fahrt- oder Tiefenbefehl hebt ab. Vor Land oder einer Untiefe stoppt das Boot, statt auszuweichen, und das Log warnt bei wenig Wasser unter dem Kiel. - **Energie und Vorräte:** die Maschine zeigt unter **Energie & Vorräte** (Karte im Browser, auf der uConsole Maschine Seite 2 **Vorräte**) die Energiebilanz bei der aktuellen Fahrt (Verbrauch, Erzeugung und Bilanz in kW, die Zeit bis die Batterie leer oder voll ist), Batterie und AIP-Sauerstoff, die Dieselbunker und eine Tabelle, wie lange die Batterie getaucht bei jeder Telegrafenstufe reicht und wie weit das Boot damit kommt. **Diesel:** die Bunker fassen 300 Stunden volle Generatorleistung, eine Fahrt beginnt mit 65 %; nur laufende Diesel verbrauchen (0,27 l je kWh), das Log warnt bei 10 %, und mit leeren Bunkern lädt Schnorcheln nicht mehr. Die **Laderate** bestimmt, was Schnorcheln tut: *voll* (die ganze Generatorleistung, +12 dB und beide Diesellinien), *halb* (die halbe Leistung, +9 dB, schwächere Linien) oder *nur lüften* (die Lüfter ohne Diesel, +4 dB, keine Linien). **Luft:** getaucht verbraucht die Crew Sauerstoff und atmet Kohlendioxid aus (je etwa 0,45 % pro Stunde); ein CO2-Absorbersatz nimmt CO2 auf, bis er verbraucht ist (8 Ersatzsätze), eine O2-Kerze setzt in 15 Minuten 1 % O2 zu (12 an Bord, eine zur Zeit), und Schnorcheln lüftet das Boot in wenigen Minuten Richtung Frischluft. Ab 3 % CO2 oder unter 18 % O2 ist die Luft verbraucht, ab 5 % CO2 oder unter 16 % O2 gefährlich; das Log warnt bei jeder Stufe. Schlechte Luft macht die Crew langsamer (bis 30 % Leistung), und die Torpedomannschaft lädt entsprechend langsamer nach. KI-Boote versorgen ihre Luft selbst und tauchen zum Lüften auf, wenn sie gefährlich wird. Ein Atom-U-Boot hat keine dieser Vorräte. -- **Tauchzellen, Trimm und Pressluft:** die Maschine zeigt unter **Tauchzellen & Trimm** (Karte im Browser mit Schnittbild des Boots, auf der uConsole Maschine Seite 3 **Zellen**) die Hauptzellen, die Regelzelle, die Trimmzellen, die Pressluft und den Trimmzustand des Boots. Jede Gewichtsänderung bringt das Boot aus dem Gleichgewicht: ein Torpedo aus einem Bugrohr macht es 1,5 t leichter und achterlastig, Wasser durch den beschädigten Druckkörper (über 30 % Schaden, bis 30 t bei 100 %) schwerer. Mit der **Trimmautomatik** pumpt der LI die Regelzelle (±8 t, 25 kg/s) und die Trimmzellen (±3 t vorn und achtern, 15 kg/s) zurück ins Gleichgewicht; von Hand verschiebt jeder Befehl die Regelzelle um 0,5 t oder das Trimmwasser um 0,25 t (und schaltet die Automatik aus). Laufende Trimmpumpen sind hörbar (+3 dB und eine Linie bei 120 Hz). Was die Zellen nicht aufnehmen, lässt das Boot mit 0,03 m/s je Tonne sinken oder steigen, und ein Trimmwinkel (1° je Tonne Moment, + vorlastig) drückt es mit Fahrt nach unten oder oben; die Tiefenruder halten das nur mit Fahrt, ein schweres Boot sinkt bei wenig Fahrt unter seine befohlene Tiefe; das Log warnt ab 2 t und ab 3°. Die **Pressluft** (200 bar) reicht für drei Notanblasungen zu je 60 bar; Anblasen leert die Hauptzellen in 20 s, das Boot steigt auf 10 m und bleibt dort, die befohlene Tiefe steht dann auf 10 m. Der nächste Befehl unter 12 m öffnet die Entlüftung: die Hauptzellen fluten in 40 s, erst dann kann das Boot tauchen. Schnorcheln auf Diesel betreibt den Kompressor (0,05 bar/s); mit nur lüften läuft er nicht. Die KI-Boote halten sich selbst im Trimm und behalten ihr eines Notanblasen. +- **Tauchzellen, Trimm und Pressluft:** die Maschine zeigt unter **Tauchzellen & Trimm** (Karte im Browser mit Schnittbild des Boots, auf der uConsole Maschine Seite 3 **Zellen**) die Hauptzellen, die Regelzelle, die Trimmzellen, die Pressluft und den Trimmzustand des Boots. Jede Gewichtsänderung bringt das Boot aus dem Gleichgewicht: ein Torpedo aus einem Bugrohr macht es 1,5 t leichter und achterlastig, Wasser in vollgelaufenen Abteilungen (siehe Leckwehr) macht es schwerer und trimmt es zum gefluteten Ende; die Trimmautomatik gleicht davon aus, was ihre Zellen fassen. Mit der **Trimmautomatik** pumpt der LI die Regelzelle (±8 t, 25 kg/s) und die Trimmzellen (±3 t vorn und achtern, 15 kg/s) zurück ins Gleichgewicht; von Hand verschiebt jeder Befehl die Regelzelle um 0,5 t oder das Trimmwasser um 0,25 t (und schaltet die Automatik aus). Laufende Trimmpumpen sind hörbar (+3 dB und eine Linie bei 120 Hz). Was die Zellen nicht aufnehmen, lässt das Boot mit 0,03 m/s je Tonne sinken oder steigen, und ein Trimmwinkel (1° je Tonne Moment, + vorlastig) drückt es mit Fahrt nach unten oder oben; die Tiefenruder halten das nur mit Fahrt, ein schweres Boot sinkt bei wenig Fahrt unter seine befohlene Tiefe; das Log warnt ab 2 t und ab 3°. Die **Pressluft** (200 bar) reicht für drei Notanblasungen zu je 60 bar; Anblasen leert die Hauptzellen in 20 s, das Boot steigt auf 10 m und bleibt dort, die befohlene Tiefe steht dann auf 10 m. Der nächste Befehl unter 12 m öffnet die Entlüftung: die Hauptzellen fluten in 40 s, erst dann kann das Boot tauchen. Schnorcheln auf Diesel betreibt den Kompressor (0,05 bar/s); mit nur lüften läuft er nicht. Ohne Strom laufen weder Trimmpumpen noch Kompressor. Die KI-Boote halten sich selbst im Trimm und behalten ihr eines Notanblasen. +- **Leckwehr:** die Maschine zeigt unter **Leckwehr** (Karte im Browser mit den Abteilungen und einer Tabelle, auf der uConsole Maschine Seite 4 **Leckwehr**) den Druckkörper in sechs Abteilungen: Bugraum, Zentrale, Wohnraum, Batterieraum, Maschinenraum und Heckraum. Ein Treffer auf das besetzte Boot schlägt ein Leck in die getroffene Abteilung (1,5 % Leck je % Trefferschaden, höchstens ein volles Leck; ab 50 % Schaden auch in die Nachbarabteilung mit halbem Leck) und kann dort einen Brand auslösen (Wahrscheinlichkeit = Schaden / 150); ein Ermüdungsriss unter der Testtiefe öffnet ein kleines Leck. Durch ein volles Leck dringen in 100 m Tiefe 40 kg/s ein, mit der Wurzel der Tiefe mehr; über halbvoll läuft das Wasser in offene Nachbarabteilungen über (20 kg/s) und erstickt einen Brand. Ein Brand wächst in 2 min zum Vollbrand und greift dann durch offene Schotten über; Seewasser im Batterieraum (ab 2 t) setzt Chlorgas frei, das durch offene Schotten zieht und erst langsam abzieht, wenn die Batterie trocken ist. Wasser im Batterieraum (ab 5 t) oder ein Brand dort legen den **Strom** lahm: der Motor steht (keine Fahrt, also halten die Tiefenruder ein schweres Boot nicht), Trimmpumpen, Kompressor und elektrische Lenzpumpen stehen still. **Schotten schließen** hält Wasser, Brand und Gas in der Abteilung und erstickt einen Brand dort in 3 min. Zwei **Leckwehrtrupps** gehen durchs Boot (8 s je Abteilung) und **dichten ein Leck ab** (ein volles in 60 s), **lenzen** (30 kg/s, ohne Strom ein Viertel von Hand) oder **löschen einen Brand** (einen Vollbrand in 60 s); im Gas arbeiten sie halb so schnell, und in einer zu 90 % vollen Abteilung können sie nur lenzen. Eine Abteilung, die zur Hälfte voll Wasser ist, halb brennt oder halb vergast ist, legt ihre Station lahm: der Bugraum die Torpedorohre, die Zentrale Mast und Sehrohr, der Maschinenraum die Diesel, der Heckraum die halbe Höchstfahrt. Das Wasser ist Gewicht und Moment für den Trimm (siehe oben); ein Boot, das unter die 1,5-fache Testtiefe sinkt, wird zerdrückt. Das Log meldet Lecks, Brände, abgedichtete Lecks, gelöschte Brände, vollgelaufene Abteilungen, Chlorgas und den Strom. - **Lagebild:** ein gehörter Aktivping oder Torpedo wird mit der Peilung protokolliert, die das Boot selbst gemessen hat (einige Grad ungenau), und mit seinem Alter in den Alarmen angezeigt. Auf Sehrohrtiefe lässt sich der **Mast** ausfahren; sein ESM meldet dann die Radare, die das Boot überstreichen, mit Peilung (Log und ESM-Liste), und beim Tieferkommen fährt der Mast selbst ein. Mit ausgefahrenem Mast zeigt die Seite **Sehrohr** (Führung Seite 3, Mast & ESM Seite 2; `P` fährt an beiden den Mast aus) das Okular: Himmel und See im Licht der Stunde, den mit der See bewegten Horizont, eine Skala rechtweisender Peilungen und ein Fadenkreuz; das Rohr schwenkt in 2°-Schritten (`←`/`→`, `Umschalt`: 10°). Alles, was die Optik im Kontrastmodell des Fregattenausgucks bei 2,5 m Augenhöhe ausmacht (Tag/Nacht, Mond, Sicht, Seegang, Land im Weg), erscheint als Silhouette und als reine Peilungs-**Sichtung** mit grober Klasse (Kriegsschiff, Handelsschiff, Fahrzeug, Luftfahrzeug, Torpedolaufbahn) und scheinbarer Länge; das Log meldet jede neue Sichtung. `Enter` liest das **Stadimeter** an der Sichtung unter dem Fadenkreuz ab: die Entfernung folgt aus der scheinbaren Länge und der angenommenen Rumpflänge der Klasse (130 m für ein Kriegsschiff oder ein nicht erkanntes Fahrzeug, 150 m für ein Handelsschiff), ein nicht erkanntes oder bugwärts stehendes Ziel misst sich also zu weit; die Ablesung ist ±25 % und wird für 120 s zu einem VISUAL-Fix am Sonarkontakt des Boots auf dieses Ziel, für einen Schuss nutzbar wie ein Ping-Fix. Luftfahrzeuge und Laufbahnen lassen sich nicht messen. Die kartierte Küste steht auf dem Horizont des Sehrohrs, so weit seine niedrige Optik Land sieht (Hügel mit 25 bis 70 m angenommen). Die Führung kann auch ohne Sonarbediener pingen und eine BT-Messung nehmen. Die Karte zeigt das Schussfeld der Rohre, wo sie nicht rundum schießen, und das vom Sonar zugewiesene Ziel ist für den Schuss vorausgewählt. - **Mast & ESM:** mit ausgefahrenem Mast auf Sehrohrtiefe hört die ESM-Antenne des Boots (3 m über Wasser) einmal pro Sekunde die Radare ringsum: das der Fregatte, anderer Schiffe und von Flugzeugen innerhalb des Radarhorizonts, über Land nur, wo die Küste die Linie nicht verdeckt. Jede Erfassung trägt die gemessene Peilung (±4°), Band, Trägerfrequenz, PRF, Modulation und Empfangspegel, nie die Identität oder Position des Senders. Die Crew führt eine **Emitterliste** (`E1`, `E2` …) über mehrere Mastperioden: eine Erfassung gehört zu einem Emitter, wenn Peilung, Band und Signalform passen (ein frequenzagiles Radar nur nach Peilung und Band), und die Liste vergisst einen Emitter 30 Minuten nach seiner letzten Erfassung. Die **Einstufung** ist die Annotation der Crew aus der Bibliothek: die Emitter, deren veröffentlichte Frequenz- und PRF-Bereiche die Messung enthalten, ungewichtet, wie an der ELOKA der Fregatte ohne Assistenz; die Wahl legt die Leistungsklasse für die **Entfernungsschätzung** aus dem Pegel fest (ohne Einstufung die kürzeste Entfernung, die die Bibliothek zulässt). Alle 30 s behält jeder Emitter eine **Peilung** von der eigenen Position des Boots (20 Minuten); die Karte zeigt die letzten Peillinien, und sobald die eigene Fahrt die Peilung um mindestens 8° gedreht hat, ist die **Kreuzpeilung** ihr bester Schnittpunkt mit einer 95-%-Fehlerellipse, die einen seit jeder Linie bis zu 8 kn versetzten Sender einrechnet (eine schnelle Fregatte ergibt meist keine; eine Kreuzpeilung, deren Linien nicht zusammenpassen, wird markiert). Der **Stärketrend** zeigt steigend, gleichbleibend oder fallend über fünf Minuten. Die **Mastwarnung** („Radar kann Mast sehen“) kommt, wenn die geschätzte Entfernung eines erfassten Suchradars innerhalb der Entfernung liegt, auf der ein Seeraumradar bei diesem Seegang und Regen einen ausgefahrenen Mast sieht (der Wert der Wetterseite); die **empfohlene Mastzeit** ist 60 s bei ruhiger See, bis zu 300 s, wenn die Seegangsechos den Mast verbergen, und 20 s unter dieser Warnung, und das Log meldet, wenn sie überschritten ist. Ab Seegang 3 überspülen Wellen die Antenne, und manche Durchläufe hören nichts. Die Karte Mast & ESM im Browser hat die Rose, die Emittertabelle und die Auswertung des gewählten Emitters; **In den Plot übernehmen** trägt die Kreuzpeilung (Markierung und Fehlerkreis) oder sonst die letzte Peillinie in den Plot des Boots ein. Auf der Seite Mast & ESM der uConsole wählen `↑`/`↓` einen Emitter, `←`/`→` schalten seine Einstufung aus der Bibliothek weiter und `Enter` übernimmt ihn in den Plot. - **Navigation und Plot:** die Maschine hat Maschinentelegrafen-Knöpfe, und Führung und Navigation teilen den eigenen Fettstift-Plot des Boots (Markierungen, Lineale, Peillinien, Kreise, Koppellinien); die Fregatte sieht ihn nie, und der Plot des Boots wird nicht gespeichert. Die Navigation zeigt das Wasser unter dem Kiel und prüft die Seekarte entlang des Sollkurses bis 5 sm: Land oder ein Grund flacher als das Boot wird als Hindernis voraus gemeldet, im Log und als Warnung. Es zählt nur die kartierte Geografie; andere Fahrzeuge sind nicht Teil der Prüfung. @@ -1067,7 +1068,7 @@ Eine zweite Crew kann den Gegner spielen. Das Boot hat sechs Stationen: Führung Jedes neue Spiel fragt zuerst **Welche Einheit spielst du?**: *Fregatte F-217* oder *Feindliches U-Boot* (`Auf`/`Ab` oder `1`/`2`, `Enter`; die letzte Wahl ist vorausgewählt, `--play-sub` wählt das U-Boot vor). Außerhalb einer Mission ändert auch Optionen (`F10`) Seite 2 **uConsole spielt** die Wahl, etwa vor dem Laden eines Spielstands. Mit dem U-Boot führt der uConsole das feindliche Boot statt der Fregatte. Die Fregatte wird dann über Remote Crew (`F9`) aus den Browsern besetzt oder fährt mit Autocrew. Der uConsole zeigt nur das Lagebild des Boots; Banner, Ereignislog, Soundeffekte, Plot und Tooltips der Fregatte erscheinen nie, und Trackball- und Telegraphenbedienung der Fregatte sind gesperrt. Die Seite lässt sich nur außerhalb einer Mission wechseln; die Wahl gilt nur für diesen Programmstart und wird nie gespeichert, jeder Start beginnt also mit der Fregatte. -Die obere Leiste zeigt die sechs Stationen des Boots als Reiter: `1` Führung, `2` Sonar, `3` Waffen, `4` Maschine, `5` Mast & ESM, `6` Navigation (`Tab` oder ein Klick auf den Reiter wechselt). Jede Befehlstaste wirkt nur an der Station, zu der der Befehl gehört, wie im Browser; sonst nennt ein Banner die richtige Station. Browser können gleichzeitig die übrigen Stationen des Boots besetzen; eine Station, die ein Browser hält, ist in der oberen Leiste markiert und wird nicht vom uConsole bedient. Jede Station außer dem Sonarraum ist aufgebaut wie die Brücke: links die Seekarte (bekannte Geografie, der eigene Plot des Boots, die ESM-Peillinien und Kreuzpeilungen, das eigene Boot mit Sollkurs und Fahrtvektor, die Peilstriche der eigenen Sonarkontakte bzw. ihr Symbol bei aktuellem Ping- oder TMA-Fix, die eigenen Torpedos `T1`…, ein begrenztes Schussfeld der Rohre), rechts die Station mit Bedrohungsleiste (Torpedoalarm und gehörtes Aktivsonar mit gemessener Peilung, Rumpfschaden, Kavitation, schwache Batterie, ESM-Radarerfassung) und die Seite der Station. Die **Führung** und die **Maschine** haben drei Seiten, **Mast & ESM** zwei (die Taste der Station erneut oder `Bild auf`/`Bild ab`). Die zweite Seite der Maschine, **Vorräte**, zeigt Energie, Ausdauer und Luft; `R` wechselt die Laderate, `A` setzt einen Absorbersatz ein und `O` zündet eine O2-Kerze. Ihre dritte Seite **Zellen** zeigt das Schnittbild, Hauptzellen und Pressluft, die Zellen mit ihren Sollwerten, Gewicht, Trimmwinkel, Drift ohne Tiefenruder, Wassereinbruch und Pumpen; `↑`/`↓` lenzen oder fluten die Regelzelle, `←`/`→` pumpen Trimmwasser nach achtern oder vorn und `Z` schaltet die Trimmautomatik. **Navigation** (Seite und Station) zeigt Kurs und Tiefe, das Wasser unter dem Kiel und ein kartiertes Hindernis voraus, Fahrt, Eigenlärm, Batterie und die aktiven Betriebsarten sowie die Wassersäule unter dem Boot: Bootstiefe, befohlene Tiefe, sichere Tiefe und Grund; die Sprungschicht erscheint dort erst nach einer eigenen BT-Messung (`E` am U-Boot-Sonar). **Waffen & Kontakte** (Seite und Station Waffen) zeigt Feuerbereitschaft, Torpedos, klare Rohre, Nachladen, Täuschkörper, Notanblasen und die eigenen Sonarkontakte (Peilung, Entfernung falls bekannt, und Güte in Prozent: der bessere Wert aus Signalgüte und Spurvertrauen, 100 % ist ein sicherer Kontakt). Die **Maschine** zeigt Fahrt, Eigenlärm, Batterie, die Betriebsarten und die Telegrafenstufen; **Mast & ESM** zeigt die Mastzeit, die Rose, die Emitterliste und den gewählten Emitter (Signal, Pegel und Trend, Kreuzpeilung, Einstufung); ihre zweite Seite und die dritte der Führung ist das **Sehrohr** (Okular, Sichtlinie, Licht und die Sichtungsliste; `←`/`→` schwenken, `Enter` Stadimeter). Unten stehen Bootslog und Telemetrie des Boots, als Leiste oder Statuszeile wie in den Optionen eingestellt; Befehle, Schüsse und Täuschkörper werden dort protokolliert. +Die obere Leiste zeigt die sechs Stationen des Boots als Reiter: `1` Führung, `2` Sonar, `3` Waffen, `4` Maschine, `5` Mast & ESM, `6` Navigation (`Tab` oder ein Klick auf den Reiter wechselt). Jede Befehlstaste wirkt nur an der Station, zu der der Befehl gehört, wie im Browser; sonst nennt ein Banner die richtige Station. Browser können gleichzeitig die übrigen Stationen des Boots besetzen; eine Station, die ein Browser hält, ist in der oberen Leiste markiert und wird nicht vom uConsole bedient. Jede Station außer dem Sonarraum ist aufgebaut wie die Brücke: links die Seekarte (bekannte Geografie, der eigene Plot des Boots, die ESM-Peillinien und Kreuzpeilungen, das eigene Boot mit Sollkurs und Fahrtvektor, die Peilstriche der eigenen Sonarkontakte bzw. ihr Symbol bei aktuellem Ping- oder TMA-Fix, die eigenen Torpedos `T1`…, ein begrenztes Schussfeld der Rohre), rechts die Station mit Bedrohungsleiste (Torpedoalarm und gehörtes Aktivsonar mit gemessener Peilung, Rumpfschaden, Kavitation, schwache Batterie, ESM-Radarerfassung) und die Seite der Station. Die **Führung** hat drei Seiten, die **Maschine** vier, **Mast & ESM** zwei (die Taste der Station erneut oder `Bild auf`/`Bild ab`). Die zweite Seite der Maschine, **Vorräte**, zeigt Energie, Ausdauer und Luft; `R` wechselt die Laderate, `A` setzt einen Absorbersatz ein und `O` zündet eine O2-Kerze. Ihre dritte Seite **Zellen** zeigt das Schnittbild, Hauptzellen und Pressluft, die Zellen mit ihren Sollwerten, Gewicht, Trimmwinkel, Drift ohne Tiefenruder, Wassereinbruch und Pumpen; `↑`/`↓` lenzen oder fluten die Regelzelle, `←`/`→` pumpen Trimmwasser nach achtern oder vorn und `Z` schaltet die Trimmautomatik. Ihre vierte Seite **Leckwehr** zeigt die Abteilungen (Wasser, Leck, Brand, Gas, geschlossene Schotten, Trupps), die Tabelle der Abteilungen, den Strom und beide Trupps; `↑`/`↓` wählen eine Abteilung, `←`/`→` eine Aufgabe, `Enter` schickt Trupp 1 und `Umschalt+Enter` Trupp 2 mit dieser Aufgabe dorthin, und `I` schließt oder öffnet die Schotten der Abteilung. **Navigation** (Seite und Station) zeigt Kurs und Tiefe, das Wasser unter dem Kiel und ein kartiertes Hindernis voraus, Fahrt, Eigenlärm, Batterie und die aktiven Betriebsarten sowie die Wassersäule unter dem Boot: Bootstiefe, befohlene Tiefe, sichere Tiefe und Grund; die Sprungschicht erscheint dort erst nach einer eigenen BT-Messung (`E` am U-Boot-Sonar). **Waffen & Kontakte** (Seite und Station Waffen) zeigt Feuerbereitschaft, Torpedos, klare Rohre, Nachladen, Täuschkörper, Notanblasen und die eigenen Sonarkontakte (Peilung, Entfernung falls bekannt, und Güte in Prozent: der bessere Wert aus Signalgüte und Spurvertrauen, 100 % ist ein sicherer Kontakt). Die **Maschine** zeigt Fahrt, Eigenlärm, Batterie, die Betriebsarten und die Telegrafenstufen; **Mast & ESM** zeigt die Mastzeit, die Rose, die Emitterliste und den gewählten Emitter (Signal, Pegel und Trend, Kreuzpeilung, Einstufung); ihre zweite Seite und die dritte der Führung ist das **Sehrohr** (Okular, Sichtlinie, Licht und die Sichtungsliste; `←`/`→` schwenken, `Enter` Stadimeter). Unten stehen Bootslog und Telemetrie des Boots, als Leiste oder Statuszeile wie in den Optionen eingestellt; Befehle, Schüsse und Täuschkörper werden dort protokolliert. | Taste | Funktion | |---|---| @@ -1104,13 +1105,16 @@ Die obere Leiste zeigt die sechs Stationen des Boots als Reiter: `1` Führung, ` | `Pfeiltasten` | Maschine, Seite Zellen: Regelzelle fluten (ab) oder lenzen (auf) | | `← / →` | Maschine, Seite Zellen: Trimmwasser nach vorn (rechts) oder achtern (links) | | `Z` | Maschine: Trimmautomatik an/aus | +| `Pfeiltasten` | Maschine, Seite Leckwehr: Abteilung wählen (auf/ab) und Aufgabe (links/rechts) | +| `Eingabe` | Maschine, Seite Leckwehr: Trupp 1 (Umschalt: Trupp 2) mit der Aufgabe schicken | +| `I` | Maschine, Seite Leckwehr: Schotten der Abteilung schließen oder öffnen | | `0` | Wetterseite des Boots (0 oder Esc schließt) | | `S / L / F9` | Speichern / Laden / Remote Crew (die Fregatten-Crew) | #### Nicht modelliert - Das besetzte Boot funkt nicht und empfängt nichts; es gibt keine Kontaktmeldung von der Führung an Land. -- Keine Leckwehr- oder Schadensteams an Bord; Schäden summieren sich nur. +- Die Leckwehr kennt sechs Abteilungen und zwei Trupps: keine getrennten Schäden an Druck- und Außenhülle, keine Verletzten, keine Ausbreitung von Rauch oder Hitze, kein Brand in den Luftvorräten und kein Sauerstoffverbrauch durch Feuer; der Gesamtschaden des Boots (Lärm, Höchstfahrt, Untergang bei 100 %) summiert sich weiter aus Treffern, und die KI-Boote haben nur diesen Wert. - Das Trimmmodell kennt ein Gewicht und ein Moment: keinen Effekt freier Oberflächen, keine Kompressibilität des Druckkörpers mit der Tiefe und keine eigene Schnelltauchzelle; das Boot taucht nicht ganz auf. Proviant und Frischwasser gehen nicht aus. - Ein ausgefahrener Mast oder Schnorchelkopf erscheint auf dem Fregattenradar nur als bloßer Punkt (siehe Kapitel OPZ). - Das ESM des Boots hört keine Radare anderer U-Boote und keine Flugkörpersucher; es hat keine gewichtete Bibliotheksanalyse, keine Messung der Umlaufzeit und keine Bewegungsanalyse eines Senders (die Kreuzpeilung nimmt einen langsamen Sender an). diff --git a/docs/manual/manual.en.md b/docs/manual/manual.en.md index 721bb02d..0d90230e 100644 --- a/docs/manual/manual.en.md +++ b/docs/manual/manual.en.md @@ -1053,7 +1053,8 @@ A second crew can play the enemy. The boat has six stations: Command, Sonar, Wea - **Orders and weapons:** the boat follows course, speed and depth orders within its turn, depth and acceleration limits; telegraph steps (stop, 3, 6, 10, 15 kn, maximum) set the speed quickly. Fires a torpedo down a sonar contact's measured bearing, with its ping fix or TMA solution while current, or down a free bearing with an optional range; firing needs a ready tube and the target inside the tube arc. The crew sets the run depth (5-300 m, otherwise a shallow default) and fires one torpedo or two in a ±4° spread, each with its own datum. Every crew torpedo runs on a wire: the crew can move its datum (bearing and distance from the boat) and the wire turns it onto the new datum until its seeker acquires; faster than 10 kn or turning harder than 1.5°/s for 5 s breaks the wire, as does running out of either spool, and the crew can cut it. Launches a decoy and blows main ballast in an emergency (three times on a full air store). - **Plant and boat modes:** a crewed boat never goes up, snorkels or calls home by itself. The battery drains with speed and hotel load; below 20 % the log warns, and an empty battery limits the speed to what the plant can serve (an AIP plant still takes over the load by itself). **Snorkel** runs the diesels at snorkel depth and charges the battery, at most 6 kn; diving deeper shuts the head valve. The running diesels are loud: +12 dB radiated level, a lower quiet factor and two firing lines at 50 and 100 Hz in the boat's LOFAR signature (AI boats too). **Silent running** limits the boat to 5 kn and makes it as quiet as a lurking AI boat. **Lie on bottom** stops the boat 3 m above the seabed where the water is no deeper than test depth: silent and no drift; any speed or depth order lifts off. The boat stops short of land or a seamount instead of turning away, and the log warns in shallow water. - **Energy and stores:** the engine room's **Energy & stores** (browser card, uConsole Engine room page 2 **Stores**) shows the energy balance at the present speed (load, supply and net kW, the time until the battery is empty or full), the battery and AIP oxygen, the diesel bunkers and a table of how long the battery lasts dived at each telegraph step and how far that carries the boat. **Diesel:** the bunkers hold 300 hours of the generators' full output and a patrol starts with 65 %; only the running diesels burn it (0.27 l per kWh), the log warns at 10 %, and with dry bunkers snorkelling no longer charges. The **charge rate** sets what snorkelling does: *full* (the whole generator output, +12 dB and both diesel lines), *half* (half the output, +9 dB, weaker lines) or *air only* (the fans without diesels, +4 dB, no lines). **Air:** dived, the crew uses oxygen and breathes out carbon dioxide (about 0.45 % per hour each); a CO2 absorber set takes CO2 out until it is spent (8 spare sets), an oxygen candle adds 1 % O2 over 15 minutes (12 aboard, one at a time), and snorkelling flushes the boat toward fresh air within minutes. From 3 % CO2 or below 18 % O2 the air is stale, from 5 % CO2 or below 16 % O2 it is foul; the log warns at each step. Stale air slows the crew (down to 30 % performance), and the torpedo gang reloads accordingly slower. AI boats manage their air by themselves and come up to air the boat when it turns foul. A nuclear boat has none of these stores. -- **Tanks, trim and air:** the engine room's **Tanks & trim** (browser card with a cross-section of the boat, uConsole Engine room page 3 **Tanks**) shows the main ballast, the regulating tank, the trim tanks, the high-pressure air and the trim the boat is in. Every weight change moves the boat off neutral: a torpedo leaving a bow tube makes it 1.5 t lighter and bow light, water through a holed hull (above 30 % damage, up to 30 t at 100 %) makes it heavier. With the **automatic trim** on, the engineer pumps the regulating tank (±8 t, 25 kg/s) and the trim tanks (±3 t fore and aft, 15 kg/s) back to neutral; by hand, each order moves the regulating tank 0.5 t or the trim water 0.25 t (and switches the automatic off). Running trim pumps are audible (+3 dB and a 120 Hz line). Whatever the tanks cannot take up sinks or lifts the boat by 0.03 m/s per tonne, and a trim angle (1° per tonne of moment, + bow down) drives it down or up with speed; the hydroplanes hold that only with way on, so a heavy boat hovering at low speed sinks below its ordered depth; the log warns from 2 t and from 3°. The **high-pressure air** (200 bar) holds three emergency blows of 60 bar each; a blow empties the main ballast in 20 s and the boat rises to 10 m and stays there, the ordered depth reset to 10 m. The next order below 12 m opens the vents: the main ballast floods in 40 s before the boat can dive. Snorkelling on the diesels runs the compressor (0.05 bar/s); with the air only on the fans it does not. The AI's boats keep themselves trimmed and keep their one legacy blow. +- **Tanks, trim and air:** the engine room's **Tanks & trim** (browser card with a cross-section of the boat, uConsole Engine room page 3 **Tanks**) shows the main ballast, the regulating tank, the trim tanks, the high-pressure air and the trim the boat is in. Every weight change moves the boat off neutral: a torpedo leaving a bow tube makes it 1.5 t lighter and bow light, water in flooded compartments (see damage control) makes it heavier and trims it toward the flooded end; the automatic trim takes up what its tanks can of that weight and moment. With the **automatic trim** on, the engineer pumps the regulating tank (±8 t, 25 kg/s) and the trim tanks (±3 t fore and aft, 15 kg/s) back to neutral; by hand, each order moves the regulating tank 0.5 t or the trim water 0.25 t (and switches the automatic off). Running trim pumps are audible (+3 dB and a 120 Hz line). Whatever the tanks cannot take up sinks or lifts the boat by 0.03 m/s per tonne, and a trim angle (1° per tonne of moment, + bow down) drives it down or up with speed; the hydroplanes hold that only with way on, so a heavy boat hovering at low speed sinks below its ordered depth; the log warns from 2 t and from 3°. The **high-pressure air** (200 bar) holds three emergency blows of 60 bar each; a blow empties the main ballast in 20 s and the boat rises to 10 m and stays there, the ordered depth reset to 10 m. The next order below 12 m opens the vents: the main ballast floods in 40 s before the boat can dive. Snorkelling on the diesels runs the compressor (0.05 bar/s); with the air only on the fans it does not. Without power neither the trim pumps nor the compressor run. The AI's boats keep themselves trimmed and keep their one legacy blow. +- **Damage control:** the engine room's **Damage control** (browser card with the compartments and a table, uConsole Engine room page 4 **Damage**) divides the pressure hull into six compartments: bow room, control room, quarters, battery room, engine room and stern room. A hit on the crewed boat holes the compartment it strikes (a leak of 1.5 % per % of hit damage, up to a full hole; from 50 % damage the neighbour too, with half the leak) and may start a fire there (chance = damage / 150); a fatigue crack below test depth opens a small leak. Water comes in at 40 kg/s through a full hole at 100 m, growing with the square root of depth; above half a compartment it spills into open neighbours (20 kg/s) and smothers a fire. A fire grows to full in 2 min and then spreads through open bulkheads; seawater in the battery room (from 2 t) gives off chlorine gas that drifts through open bulkheads and clears slowly once the battery is dry. Water in the battery room (from 5 t) or a fire there cuts the **power**: the motor stops (no way on, so the hydroplanes do not hold a heavy boat), and the trim pumps, compressor and electric bilge pumps stand still. **Shutting the bulkheads** of a compartment keeps water, fire and gas in it and starves a fire there in 3 min. Two **damage-control teams** walk the boat (8 s per compartment) and **seal a leak** (a full hole in 60 s), **pump out** (30 kg/s, a quarter by hand without power) or **fight a fire** (a full fire in 60 s); in gas they work at half rate, and in a compartment 90 % full they can only pump. A compartment half full of water, half on fire or half gassed takes its station out: the bow room the torpedo tubes, the control room the mast and periscope, the engine room the diesels, the stern room half the top speed. The floodwater is weight and moment for the trim (see above); a boat that sinks below 1.5 x test depth is crushed. The log reports leaks, fires, sealed leaks, fires out, flooded compartments, chlorine and power. - **Situation picture:** an intercepted active ping or torpedo is logged with the bearing the boat's own ears measured (a few degrees off) and shown with its age in the alarms. At periscope depth the **mast** can be raised; its ESM then reports the radars sweeping the boat with bearing (log and ESM list), and the mast lowers by itself when the boat goes deeper. With the mast up the **periscope** page (Command page 3, Mast & ESM page 2; `P` raises the mast at both) shows the eyepiece: sky and sea in the light of the hour, the horizon moving with the sea, a true-bearing scale and a crosshair; the scope trains in 2° steps (`←`/`→`, `Shift`: 10°). Everything the optics make out within the frigate lookout's contrast model at 2.5 m eye height (day/night, moon, visibility, sea state, land in the way) appears as a silhouette and as a bearing-only **sighting** with a coarse class (warship, merchant ship, vessel, aircraft, torpedo wake) and its apparent length; the log reports each new sighting. `Enter` reads the **stadimeter** on the sighting under the crosshair: the range follows from its apparent length and the assumed hull length of the class (130 m for a warship or an unrecognized vessel, 150 m for a merchant), so an unrecognized or bow-on target reads long; the reading is ±25 % and becomes a VISUAL fix on the boat's sonar contact of that target for 120 s, usable for a shot like a ping fix. Aircraft and wakes cannot be ranged. The charted coast stands on the periscope's horizon as far as its low optics see land (hills assumed 25 to 70 m). Command can also ping and take a BT without a sonar operator. The chart shows the tube firing arc where the tubes cannot fire all round, and the sonar room's assigned target is preselected for the shot. - **Mast & ESM:** with the mast up at periscope depth the boat's own ESM antenna (3 m above the water) hears the radars around it once a second: the frigate's, other ships' and aircraft radars inside the radar horizon, over land only where the coast does not block the line. Each intercept carries the measured bearing (±4°), band, carrier frequency, PRF, modulation and received level, never the emitter's identity or position. The crew keeps an **emitter list** (`E1`, `E2` …) across mast periods: an intercept joins an emitter when bearing, band and waveform agree (a frequency-agile radar by bearing and band only), and the list forgets an emitter 30 minutes after its last intercept. **Classification** is the crew's annotation from the library: the emitters whose published frequency and PRF ranges hold the measurement, unranked, as at the frigate's ELOKA without assistance; the choice sets the power class for the **range estimate** from the level (unclassified: the shortest range the library allows). Every 30 s each emitter keeps a **bearing** from the boat's own position (20 minutes); the chart shows the latest bearing lines, and once the boat's own motion has swung the bearing by at least 8°, the **cross-fix** is their best crossing with a 95 % error ellipse that allows for an emitter drifting up to 8 kn since each line (a fast frigate usually gives none; a fix whose lines disagree is marked). The **level trend** reads rising, steady or falling over five minutes. The **mast warning** ("radar can see the mast") comes when a live search radar's estimated range is inside the range at which a surface radar sees a raised mast in this sea and rain (the weather page's value); the **recommended mast time** is 60 s in a calm sea, up to 300 s when sea clutter hides the mast and 20 s under that warning, and the log reports when it is exceeded. From sea state 3 waves wash over the antenna and some scans hear nothing. The browser's Mast & ESM card has the rose, the emitter table and the selected emitter's evaluation; **Transfer to plot** puts the cross-fix (mark and error circle) or else the latest bearing line into the boat's plot. On the uConsole's Mast & ESM page `↑`/`↓` select an emitter, `←`/`→` step through its library classification and `Enter` transfers it to the plot. - **Navigation and plot:** the engine room has telegraph buttons, and Command and Navigation share the boat's own grease-pencil plot (marks, rulers, bearing lines, circles, DR lines); the frigate never sees it, and the boat's plot is not saved. The navigation display shows the water under the keel and checks the chart along the ordered course up to 5 NM: land or a seabed shallower than the boat is reported as an obstacle ahead, in the log and as a warning. Only charted geography counts; other vessels are not in the check. @@ -1066,7 +1067,7 @@ A second crew can play the enemy. The boat has six stations: Command, Sonar, Wea Every new game first asks **Which unit do you play?**: *Frigate F-217* or *Hostile submarine* (`Up`/`Down` or `1`/`2`, `Enter`; the last choice is preselected, `--play-sub` preselects the submarine). Outside a mission, Options (`F10`) page 2 **uConsole plays** changes it as well, for example before loading a game. With the submarine the uConsole commands the hostile boat instead of the frigate. The frigate is then crewed from the browsers through Remote Crew (`F9`) or runs on autocrew. The uConsole shows only the boat's own picture; the frigate's banners, event log, sound cues, plot and tooltips never appear, and its trackball and telegraph controls are disabled. The side can only be changed outside a mission; it lasts for this launch and is never saved, so every launch starts with the frigate. -The top bar shows the boat's six stations as tabs: `1` Command, `2` Sonar, `3` Weapons, `4` Engine room, `5` Mast & ESM, `6` Navigation (`Tab` or a click on a tab switches). Each order key works only at the station that owns it, as in the browser; elsewhere a banner names the right station. Browsers can crew the boat's other stations at the same time; a station a browser holds is marked in the top bar and is not operated from the uConsole. Every station but the sonar room is laid out like the Bridge: the chart on the left (known geography, the boat's own plot, the ESM bearing lines and cross-fixes, the boat with its ordered course and motion vector, the bearing lines of its own sonar contacts or their symbol while a ping or TMA fix is current, its own torpedoes `T1`…, a limited tube firing arc), the station on the right with a threat bar (torpedo alarm and active sonar heard with measured bearing, hull damage, cavitation, low battery, ESM radar intercept) and the station's page. **Command** and the **Engine room** have three pages, **Mast & ESM** two (the station's key again or `PgUp`/`PgDn`). The Engine room's second page **Stores** shows energy, endurance and air; `R` cycles the charge rate, `A` fits an absorber set and `O` lights an oxygen candle. Its third page **Tanks** shows the cross-section, main ballast and air, the tanks with their orders, weight, trim angle, drift without planes, flooding and pumps; `↑`/`↓` pump out or flood the regulating tank, `←`/`→` move trim water aft or forward and `Z` switches the automatic trim. **Navigation** (page and station) shows course and depth, water under the keel and any charted obstacle ahead, speed, own noise, battery and the active modes, and the water column under the boat: boat depth, ordered depth, safe depth and seabed; the layer appears there only after the boat's own BT measurement (`E` at the submarine sonar). **Weapons & contacts** (page and Weapons station) shows fire readiness, torpedoes, tubes ready, reload, decoys, emergency blow and the boat's own sonar contacts (bearing, range where known, and quality in percent: the better of the signal quality and the track confidence, 100 % being a firm contact). The **Engine room** shows speed, own noise, battery, the modes and the telegraph steps; **Mast & ESM** shows the mast time, the rose, the emitter list and the selected emitter (signal, level and trend, cross-fix, classification); its second page and Command's third are the **Periscope** (eyepiece, line of sight, light and the sightings list; `←`/`→` train, `Enter` stadimeter). Below are the boat log and the boat's telemetry, as a band or a status ticker as set in the options; orders, shots and decoys are logged there. +The top bar shows the boat's six stations as tabs: `1` Command, `2` Sonar, `3` Weapons, `4` Engine room, `5` Mast & ESM, `6` Navigation (`Tab` or a click on a tab switches). Each order key works only at the station that owns it, as in the browser; elsewhere a banner names the right station. Browsers can crew the boat's other stations at the same time; a station a browser holds is marked in the top bar and is not operated from the uConsole. Every station but the sonar room is laid out like the Bridge: the chart on the left (known geography, the boat's own plot, the ESM bearing lines and cross-fixes, the boat with its ordered course and motion vector, the bearing lines of its own sonar contacts or their symbol while a ping or TMA fix is current, its own torpedoes `T1`…, a limited tube firing arc), the station on the right with a threat bar (torpedo alarm and active sonar heard with measured bearing, hull damage, cavitation, low battery, ESM radar intercept) and the station's page. **Command** has three pages, the **Engine room** four, **Mast & ESM** two (the station's key again or `PgUp`/`PgDn`). The Engine room's second page **Stores** shows energy, endurance and air; `R` cycles the charge rate, `A` fits an absorber set and `O` lights an oxygen candle. Its third page **Tanks** shows the cross-section, main ballast and air, the tanks with their orders, weight, trim angle, drift without planes, flooding and pumps; `↑`/`↓` pump out or flood the regulating tank, `←`/`→` move trim water aft or forward and `Z` switches the automatic trim. Its fourth page **Damage** shows the compartments (water, leak, fire, gas, shut bulkheads, teams), the table of compartments, the power and both teams; `↑`/`↓` pick a compartment, `←`/`→` a task, `Enter` sends team 1 and `Shift+Enter` team 2 there with that task, and `I` shuts or opens the compartment's bulkheads. **Navigation** (page and station) shows course and depth, water under the keel and any charted obstacle ahead, speed, own noise, battery and the active modes, and the water column under the boat: boat depth, ordered depth, safe depth and seabed; the layer appears there only after the boat's own BT measurement (`E` at the submarine sonar). **Weapons & contacts** (page and Weapons station) shows fire readiness, torpedoes, tubes ready, reload, decoys, emergency blow and the boat's own sonar contacts (bearing, range where known, and quality in percent: the better of the signal quality and the track confidence, 100 % being a firm contact). The **Engine room** shows speed, own noise, battery, the modes and the telegraph steps; **Mast & ESM** shows the mast time, the rose, the emitter list and the selected emitter (signal, level and trend, cross-fix, classification); its second page and Command's third are the **Periscope** (eyepiece, line of sight, light and the sightings list; `←`/`→` train, `Enter` stadimeter). Below are the boat log and the boat's telemetry, as a band or a status ticker as set in the options; orders, shots and decoys are logged there. | Key | Action | |---|---| @@ -1103,13 +1104,16 @@ The top bar shows the boat's six stations as tabs: `1` Command, `2` Sonar, `3` W | `Arrow keys` | Engine room, tanks page: flood (down) or pump out (up) the regulating tank | | `← / →` | Engine room, tanks page: trim water forward (right) or aft (left) | | `Z` | Engine room: automatic trim on/off | +| `Arrow keys` | Engine room, damage page: pick a compartment (up/down) and a task (left/right) | +| `Enter` | Engine room, damage page: send team 1 (Shift: team 2) with the task | +| `I` | Engine room, damage page: shut or open the compartment's bulkheads | | `0` | Weather panel of the boat (0 or Esc closes) | | `S / L / F9` | Save / load / Remote Crew (the frigate's crew) | #### Not modelled - The crewed boat sends no radio traffic and receives none; there is no contact report from home. -- No damage-control teams aboard the boat; damage only accumulates. +- Damage control is six compartments and two teams: no separate pressure-hull and outer-hull damage, no casualties, no smoke or heat spreading, no fire in the air stores and no fire consuming oxygen; the boat's overall damage (noise, top speed, sinking at 100 %) still adds up from hits, and the AI's boats keep only that value. - The trim model is one weight and one moment: no free-surface effect, no compressibility of the hull with depth and no separate negative tank; the boat does not surface fully. Food and fresh water do not run out. - A raised mast or snorkel head is seen by the frigate's radar only as a bare blip (see the OPZ chapter). - The boat's ESM hears no other submarine's radar and no missile seeker; it has no scored library analysis, no scan-period measurement and no target motion analysis of an emitter (the cross-fix assumes a slow emitter). diff --git a/src/commander/bridge.py b/src/commander/bridge.py index 0c49c98b..0412aa28 100644 --- a/src/commander/bridge.py +++ b/src/commander/bridge.py @@ -635,6 +635,15 @@ def _uboot_ballast(game, boat, params, _bindings): return _uboot_result(boat.sub.command_ballast(params["tank"], params["direction"])) +def _uboot_dc_team(game, boat, params, _bindings): + return _uboot_result(boat.sub.command_dc_team(params["team"], params["compartment"], + params["task"])) + + +def _uboot_bulkhead(game, boat, params, _bindings): + return _uboot_result(boat.sub.command_bulkhead(params["compartment"], params["closed"])) + + def _uboot_mast(game, boat, params, _bindings): return _uboot_result(boat.sub.command_mast(params["enabled"])) @@ -685,6 +694,8 @@ _UBOOT_ACTION_HANDLERS = { "uboot_absorber": _uboot_absorber, "uboot_trim_auto": _uboot_trim_auto, "uboot_ballast": _uboot_ballast, + "uboot_dc_team": _uboot_dc_team, + "uboot_bulkhead": _uboot_bulkhead, "uboot_o2_candle": _uboot_o2_candle, "uboot_mast": _uboot_mast, "uboot_silent": _uboot_silent, diff --git a/src/commander/projections.py b/src/commander/projections.py index 31e6c76b..4644b239 100644 --- a/src/commander/projections.py +++ b/src/commander/projections.py @@ -12,7 +12,7 @@ import weakref from src.core import boat_esm, config, opfor, plot from src.commander.v2 import schema as web_schema from src.core.autocrew import AUTOCREW_STATIONS -from src.enemies.ballast import flooding_kg +from src.enemies.damage_control import COMPARTMENTS, capacity_kg from src.sonar import analysis_tools from src.core.i18n import localize from src.core.version import APP_VERSION @@ -1296,10 +1296,12 @@ def _uboot_plant(sub): def _uboot_ballast(sub): """The boat's own tanks, trim and air bottles (own-ship truth).""" ballast = sub.ballast + flooding, moment = sub.flooding_kg(), sub.flood_moment_kg() return dict( blowing=bool(ballast.blowing), venting=bool(ballast.venting), auto=bool(ballast.auto), pumping=bool(ballast.pumping), compressor=bool(sub.snorkeling and sub.snorkel_rate != "vent" + and sub.damage_control.power() and ballast.hp_air_bar < config.UBOOT_HP_AIR_MAX_BAR), hp_air_bar=_number(ballast.hp_air_bar), hp_air_max_bar=_number(config.UBOOT_HP_AIR_MAX_BAR), @@ -1309,10 +1311,26 @@ def _uboot_ballast(sub): regulating_capacity_kg=_number(config.UBOOT_REGULATING_KG), trim_kg=_number(ballast.trim_kg), trim_order_kg=_number(ballast.trim_order_kg), trim_capacity_kg=_number(config.UBOOT_TRIM_TANK_KG), - load_kg=_number(ballast.load_kg), flooding_kg=_number(flooding_kg(sub.damage)), - residual_kg=_number(ballast.residual_kg(sub.damage)), - trim_deg=_number(ballast.trim_deg()), - drift_mps=_number(ballast.vertical_drift_mps(sub.damage, sub.speed))) + load_kg=_number(ballast.load_kg), flooding_kg=_number(flooding), + residual_kg=_number(ballast.residual_kg(flooding)), + trim_deg=_number(ballast.trim_deg(moment)), + drift_mps=_number(ballast.vertical_drift_mps(flooding, sub.speed, moment))) + + +def _uboot_damage(sub): + """The boat's own compartments and damage-control teams (own-ship truth).""" + control = sub.damage_control + return dict( + power=bool(control.power()), pumping=bool(control.pumping), + compartments=[dict( + name=name, water_kg=_number(c.water_kg), capacity_kg=_number(capacity_kg(index)), + leak_pct=_number(c.leak * 100.0), fire_pct=_number(c.fire * 100.0), + chlorine_pct=_number(c.chlorine * 100.0), closed=bool(c.closed), + down=bool(control.down(name))) + for index, (name, c) in enumerate(zip(COMPARTMENTS, control.compartments))], + teams=[dict(team=index, compartment=str(team["compartment"]), task=str(team["task"]), + transit_s=_number(team["transit_s"])) + for index, team in enumerate(control.teams)]) # Library suggestions per emitter in the browser (the crew picks by index). @@ -1446,6 +1464,7 @@ def _uboot(game, boat, rows, target_ref, asset_refs): plant=_uboot_plant(sub), esm=_uboot_esm(game, boat), ballast=_uboot_ballast(sub), + damage_control=_uboot_damage(sub), feed=[dict(seq=int(row["seq"]), age_s=_age(game.sim_t, row["t"]), message=str(localize(row["text"], game.tr))[:256]) for row in list(boat.feed)[-16:]]) diff --git a/src/commander/v2/commands.py b/src/commander/v2/commands.py index 6052f022..75a657da 100644 --- a/src/commander/v2/commands.py +++ b/src/commander/v2/commands.py @@ -132,7 +132,7 @@ UBOOT_REASONS = frozenset(( "uboot_too_deep", "uboot_no_snorkel", "uboot_no_wire", "uboot_mast_depth", "uboot_mast_down", "uboot_no_sighting", "uboot_no_stadimeter", "uboot_no_absorbers", "uboot_no_candles", "uboot_candle_burning", - "uboot_no_air_stores", "uboot_no_hp_air")) + "uboot_no_air_stores", "uboot_no_hp_air", "uboot_compartment_down")) def _uboot_ballast_params(params): @@ -141,6 +141,25 @@ def _uboot_ballast_params(params): and type(params["direction"]) is int and params["direction"] in (-1, 1)) +_UBOOT_COMPARTMENTS = ("bow", "control", "quarters", "battery", "engine", "stern") + + +def _uboot_dc_team_params(params): + return (type(params) is dict and set(params) == {"team", "compartment", "task"} + and type(params["team"]) is int and params["team"] in (0, 1) + and type(params["compartment"]) is str + and params["compartment"] in _UBOOT_COMPARTMENTS + and type(params["task"]) is str + and params["task"] in ("idle", "seal", "pump", "fire")) + + +def _uboot_bulkhead_params(params): + return (type(params) is dict and set(params) == {"compartment", "closed"} + and type(params["compartment"]) is str + and params["compartment"] in _UBOOT_COMPARTMENTS + and type(params["closed"]) is bool) + + def _bool_params(name): return lambda params: (type(params) is dict and set(params) == {name} and type(params[name]) is bool) @@ -582,6 +601,9 @@ V2_ACTION_REGISTRY = { # ... and trims the boat (the engineer's automatic trim, or by hand). "uboot_trim_auto": V2Action(frozenset({"uboot", "uboot_engine"}), _bool_params("enabled")), "uboot_ballast": V2Action(frozenset({"uboot", "uboot_engine"}), _uboot_ballast_params), + # ... and runs damage control: two teams, the bulkheads. + "uboot_dc_team": V2Action(frozenset({"uboot", "uboot_engine"}), _uboot_dc_team_params), + "uboot_bulkhead": V2Action(frozenset({"uboot", "uboot_engine"}), _uboot_bulkhead_params), "uboot_mast": V2Action(frozenset({"uboot", "uboot_esm"}), _bool_params("enabled")), "uboot_wire_steer": V2Action(frozenset({"uboot_weapons"}), _uboot_wire_params), "uboot_wire_cut": V2Action(frozenset({"uboot_weapons"}), _single_ref_params), diff --git a/src/commander/v2/schema.py b/src/commander/v2/schema.py index c5bce49f..cca2e550 100644 --- a/src/commander/v2/schema.py +++ b/src/commander/v2/schema.py @@ -39,7 +39,7 @@ WEATHER_BOAT_FIELDS = ( _UBOOT_COMMAND_SHAPE = ("navigation", "status", "weapons", "alarms", "contacts", "own_weapons", "designated_target_ref", "feed", "scope", "plant", - "esm", "ballast") + "esm", "ballast", "damage_control") # The boat's plant and stores (``plant``): numbers, then the air block. UBOOT_PLANT_FIELDS = ( "propulsion", "phase", "battery_kwh", "battery_capacity_kwh", "aip_kwh", @@ -55,6 +55,13 @@ UBOOT_BALLAST_FIELDS = UBOOT_BALLAST_FLAGS + ( "hp_air_bar", "hp_air_max_bar", "blows_left", "mbt_pct", "regulating_kg", "regulating_order_kg", "regulating_capacity_kg", "trim_kg", "trim_order_kg", "trim_capacity_kg", "load_kg", "flooding_kg", "residual_kg", "trim_deg", "drift_mps") +# The boat's compartments and damage-control teams (``damage_control``). +UBOOT_DAMAGE_FIELDS = ("power", "pumping", "compartments", "teams") +UBOOT_COMPARTMENT_FIELDS = ("name", "water_kg", "capacity_kg", "leak_pct", "fire_pct", + "chlorine_pct", "closed", "down") +UBOOT_DC_TEAM_FIELDS = ("team", "compartment", "task", "transit_s") +UBOOT_COMPARTMENTS = ("bow", "control", "quarters", "battery", "engine", "stern") +UBOOT_DC_TASKS = ("idle", "seal", "pump", "fire") # The boat's own ESM picture (``esm``): mast state, then one row per emitter # with its bearing history (own positions) and the crew's cross-fix. UBOOT_ESM_FIELDS = ("mast_up", "mast_s", "mast_time_s", "mast_threat", "mast_radar_nm", diff --git a/src/core/config.py b/src/core/config.py index 66d2ac8d..011fbd4e 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -319,7 +319,6 @@ UBOOT_REGULATING_STEP_KG = 500.0 # one crew order to the regulating tank UBOOT_TRIM_STEP_KG = 250.0 # one crew order to the trim tanks UBOOT_TORPEDO_KG = 1500.0 # a torpedo out of a bow tube UBOOT_LOAD_MAX_KG = 60000.0 -UBOOT_FLOOD_MAX_KG = 30000.0 # water in the boat at 100 % damage UBOOT_BUOYANCY_MPS_PER_T = 0.03 # sink/rise rate per tonne out of trim UBOOT_BUOYANCY_MAX_MPS = 2.0 UBOOT_TRIM_DEG_PER_T = 1.0 # trim angle per tonne of moment @@ -329,6 +328,35 @@ UBOOT_HEAVY_WARN_KG = 2000.0 # boat heavy/light beyond this: log it UBOOT_PUMP_NOISE_DB = 3.0 # trim pumps running UBOOT_PUMP_QUIET_LOSS = 0.05 UBOOT_PUMP_LINE = (120.0, 0.35, 3.0) # (Hz, amp, width) +# Damage control of the crewed boat (stage D, fictional): six compartments +# bow to stern (bow, control, quarters, battery, engine, stern). +UBOOT_DC_CAPACITY_KG = (40000.0, 40000.0, 30000.0, 30000.0, 40000.0, 30000.0) +UBOOT_DC_ARM = (1.0, 0.5, 0.15, -0.15, -0.6, -1.0) # moment arm, + forward +UBOOT_DC_LEAK_KG_S = 40.0 # full reference hole at 100 m +UBOOT_DC_LEAK_PER_PCT = 0.015 # hole size per % of hit damage +UBOOT_DC_SECOND_HIT_PCT = 50.0 # a hit this heavy holes a neighbour too +UBOOT_DC_FIRE_CHANCE_PCT = 150.0 # fire chance = damage / this +UBOOT_DC_FIRE_START = 0.2 +UBOOT_DC_FATIGUE_LEAK = 0.3 # hull fatigue crack beyond test depth +UBOOT_DC_SPILL_FRACTION = 0.5 # water above this spills (and smothers fire) +UBOOT_DC_SPILL_KG_S = 20.0 +UBOOT_DC_FIRE_GROW_S = 120.0 +UBOOT_DC_FIRE_SPREAD_S = 90.0 +UBOOT_DC_FIRE_STARVE_S = 180.0 # a fire behind closed bulkheads dies +UBOOT_DC_CHLORINE_WATER_KG = 2000.0 +UBOOT_DC_CHLORINE_RISE_S = 120.0 +UBOOT_DC_CHLORINE_DECAY_S = 600.0 +UBOOT_DC_POWER_WATER_KG = 5000.0 # battery room water that cuts the power +UBOOT_DC_DOWN_WATER = 0.5 # fraction of a compartment: station out +UBOOT_DC_DOWN_FIRE = 0.5 +UBOOT_DC_DOWN_GAS = 0.5 +UBOOT_DC_TRANSIT_S = 8.0 # per compartment walked +UBOOT_DC_SEAL_S = 60.0 # one team seals a full hole +UBOOT_DC_FIRE_FIGHT_S = 60.0 # one team puts out a full fire +UBOOT_DC_PUMP_KG_S = 30.0 +UBOOT_DC_HAND_PUMP = 0.25 # pump rate without power +UBOOT_DC_GAS_FACTOR = 0.5 # work rate in gas masks +UBOOT_DC_STERN_SPEED_FACTOR = 0.5 # shaft and motor room flooded # Periscope of the crewed boat (plan 1.3, phase 9). UBOOT_SCOPE_EYE_HEIGHT_M = 2.5 # optics just above the surface UBOOT_SCOPE_FOV_DEG = 32.0 # field of view of the low-power optics diff --git a/src/core/game_save.py b/src/core/game_save.py index f9506f79..1714af85 100644 --- a/src/core/game_save.py +++ b/src/core/game_save.py @@ -30,6 +30,7 @@ from src.enemies.animal import Animal from src.enemies.decoy import Decoy from src.enemies.sub import Sub from src.enemies.ballast import BoatBallast +from src.enemies.damage_control import BoatDamageControl from src.enemies.endurance import SubmarineEndurance from src.enemies.surface import SurfaceShip from src.sensors.tracks import TrackPicture @@ -671,6 +672,7 @@ class SaveMixin: last_bottom_m=s.last_bottom_m, manual_ping_pending=s._manual_ping_pending, ballast=s.ballast.serialize(), + damage_control=s.damage_control.serialize(), decision_reason=s.decision_reason, endurance=(s.endurance.serialize() if s.endurance is not None else None), @@ -1260,6 +1262,7 @@ class SaveMixin: s.last_bottom_m = sd["last_bottom_m"] s._manual_ping_pending = sd["manual_ping_pending"] s.ballast = BoatBallast.restore(sd["ballast"]) + s.damage_control = BoatDamageControl.restore(sd["damage_control"]) endurance_profile = self.runtime_catalog.endurances.get( f"endurance.{sd['stype']}") s.endurance = (None if endurance_profile is None else diff --git a/src/core/help.py b/src/core/help.py index 4ca563e6..4bb1713e 100644 --- a/src/core/help.py +++ b/src/core/help.py @@ -250,6 +250,9 @@ _UBOOT_HELP = ( ("help.key.arrows", "help.uboot.regulating"), ("help.key.left_right", "help.uboot.trim"), ("Z", "help.uboot.trim_auto"), + ("help.key.arrows", "help.uboot.dc_select"), + ("help.key.enter", "help.uboot.dc_team"), + ("I", "help.uboot.dc_bulkhead"), ("0", "help.uboot.weather"), ("S / L / F9", "help.uboot.admin"), ], diff --git a/src/core/i18n.py b/src/core/i18n.py index 247c11c0..94673a40 100644 --- a/src/core/i18n.py +++ b/src/core/i18n.py @@ -132,6 +132,7 @@ DISPLAY_KEYS = { "UBOOT_ENGINE": "station.page.uboot_engine", "UBOOT_SUPPLY": "station.page.uboot_supply", "UBOOT_BALLAST": "station.page.uboot_ballast", + "UBOOT_DAMAGE": "station.page.uboot_damage", "UBOOT_ESM": "station.page.uboot_esm", "UBOOT_SCOPE": "station.page.uboot_scope", "WEAPONS_TARGET": "station.page.weapons_target", diff --git a/src/core/opfor.py b/src/core/opfor.py index 95dc7280..99368e2e 100644 --- a/src/core/opfor.py +++ b/src/core/opfor.py @@ -73,7 +73,10 @@ class CrewOrders: "mast_overtime": "navigation", "tanks_venting": "navigation", "tanks_flooded": "navigation", "boat_heavy": "navigation", "boat_light": "navigation", "trim_angle": "navigation", - "hp_air_low": "navigation"} + "hp_air_low": "navigation", "dc_leak": "schaden", "dc_fire": "schaden", + "dc_fire_out": "schaden", "dc_leak_sealed": "schaden", + "dc_flooded": "schaden", "dc_chlorine": "schaden", + "dc_power_lost": "schaden", "dc_power_restored": "schaden"} def __init__(self): self.silent = False @@ -219,6 +222,9 @@ class CrewedBoat: # operator has selected on the ESM page (display only). self.esm = BoatESM() self.esm_selected = None + # Damage-control page: the compartment and task picked (display only). + self.dc_selected = 0 + self.dc_task = "seal" # Local command-station UI (display only): chart camera and page. self.chart_view = None self.chart_follow = True @@ -497,6 +503,9 @@ def update_crew(game, boat: CrewedBoat) -> None: orders.esm = boat.esm.bearings(game.sim_t) if orders.mast else [] update_sightings(game, boat) for key, values in orders.drain_events(): + if "compartment" in values: + values = dict(values, compartment=message( + f"uboot.compartment.{values['compartment']}")) boat.notice(game.sim_t, CrewOrders.EVENTS[key], message(f"uboot.event.{key}", **values), stamp=game.world.format_time()) diff --git a/src/core/save_schema.py b/src/core/save_schema.py index 005ae97a..659f57b9 100644 --- a/src/core/save_schema.py +++ b/src/core/save_schema.py @@ -1,4 +1,4 @@ -"""Declarative exact key sets for the ``u-jagd-save-v19`` document. +"""Declarative exact key sets for the ``u-jagd-save-v20`` 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, @@ -64,7 +64,7 @@ CREW_STATION_FIELDS = frozenset({ SUB_AI_FIELDS = frozenset({"solution_threshold"}) SUB_CREW_FIELDS = frozenset({ "manual", "order_course", "order_speed", "order_depth", "last_bottom_m", - "manual_ping_pending", "ballast", + "manual_ping_pending", "ballast", "damage_control", }) RNG_STREAMS = frozenset({ diff --git a/src/core/save_validate.py b/src/core/save_validate.py index f24a721c..4cded5c9 100644 --- a/src/core/save_validate.py +++ b/src/core/save_validate.py @@ -33,6 +33,7 @@ from src.core.save_schema import ( SUB_CREW_FIELDS, WORLD_FIELDS) from src.data.catalog import CATALOG, catalog_from_runtime_snapshot from src.enemies.ballast import BoatBallast +from src.enemies.damage_control import BoatDamageControl from src.enemies.endurance import SubmarineEndurance from src.sensors.esm import valid_esm_state from src.sensors.platform import validate_suite_state @@ -991,6 +992,7 @@ def valid_save_document(data, runtime_catalog=None) -> bool: return False try: BoatBallast.restore(entry["ballast"]) + BoatDamageControl.restore(entry["damage_control"]) except (TypeError, ValueError): return False if not bounded(entry.get("active_ping_cd"), 0.0, diff --git a/src/core/uboot_local.py b/src/core/uboot_local.py index adaa0cf9..c3ec1b6b 100644 --- a/src/core/uboot_local.py +++ b/src/core/uboot_local.py @@ -23,6 +23,7 @@ from src.commander.server import OPFOR_ROLES, V2_ACTION_REGISTRY from src.core import boat_esm, config, opfor from src.core.i18n import display_value, message from src.core.station import Station +from src.enemies import damage_control LOCAL_SIDES = ("frigate", "uboot") # Sonar-room keys the boat's operator may use. Everything that would reach @@ -41,7 +42,7 @@ UBOOT_INPUT_MODES = ("uboot_course", "uboot_speed", "uboot_depth", "uboot_bearin # Rejections of boat-mode orders that have their own local text. UBOOT_LOCAL_REASONS = ("not_ready", "uboot_too_deep", "uboot_no_snorkel", "uboot_mast_depth", "uboot_no_absorbers", "uboot_no_candles", "uboot_candle_burning", - "uboot_no_air_stores", "uboot_no_hp_air") + "uboot_no_air_stores", "uboot_no_hp_air", "uboot_compartment_down") def playing(game) -> bool: @@ -186,7 +187,8 @@ def _fire_notice(game, result) -> None: reason=message(f"uboot.reason.{result}") if result in ("not_ready", "no_torpedoes", "reloading", "out_of_arc", "stale_ref", "unknown_ref", - "uboot_no_wire", "invalid_value") + "uboot_no_wire", "invalid_value", + "uboot_compartment_down") else message("uboot.reason.not_ready")), 2.5) @@ -490,6 +492,13 @@ def _ballast_notice(game, sub, tank, result) -> None: order=f"{order / 1000.0:+.1f}"), 1.5) +def _dc_notice(game, key, result, **values) -> None: + if result is not True: + game.flash(message("uboot.local.dc_unavailable"), 2.0) + return + _announce(game, "schaden", message(key, **values), 1.5) + + def _key_action(key, mods): if key == pygame.K_g: return "uboot_bottom" if mods & pygame.KMOD_SHIFT else "uboot_silent" @@ -537,6 +546,32 @@ def _command_key(game, current, key, mods) -> None: tank = "regulating" if key in (pygame.K_UP, pygame.K_DOWN) else "trim" direction = 1 if key in (pygame.K_DOWN, pygame.K_RIGHT) else -1 _ballast_notice(game, sub, tank, sub.command_ballast(tank, direction)) + elif page == "UBOOT_DAMAGE" and key in (pygame.K_UP, pygame.K_DOWN): + current.dc_selected = (current.dc_selected + (1 if key == pygame.K_DOWN else -1)) \ + % len(damage_control.COMPARTMENTS) + elif page == "UBOOT_DAMAGE" and key in (pygame.K_LEFT, pygame.K_RIGHT): + tasks = damage_control.TASKS + index = tasks.index(current.dc_task) if current.dc_task in tasks else 0 + current.dc_task = tasks[(index + (1 if key == pygame.K_RIGHT else -1)) % len(tasks)] + elif page == "UBOOT_DAMAGE" and key in (pygame.K_RETURN, pygame.K_KP_ENTER) \ + and not mods & pygame.KMOD_CTRL: + if order_allowed(game, "uboot_dc_team"): + team = 1 if mods & pygame.KMOD_SHIFT else 0 + compartment = damage_control.COMPARTMENTS[current.dc_selected + % len(damage_control.COMPARTMENTS)] + _dc_notice(game, "uboot.local.dc_team", sub.command_dc_team( + team, compartment, current.dc_task), team=team + 1, + compartment=message(f"uboot.compartment.{compartment}"), + task=message(f"uboot.dc.task.{current.dc_task}")) + elif page == "UBOOT_DAMAGE" and key == pygame.K_i: + if order_allowed(game, "uboot_bulkhead"): + compartment = damage_control.COMPARTMENTS[current.dc_selected + % len(damage_control.COMPARTMENTS)] + index = damage_control.COMPARTMENTS.index(compartment) + closed = not sub.damage_control.compartments[index].closed + _dc_notice(game, "uboot.local.dc_bulkhead_" + ("closed" if closed else "open"), + sub.command_bulkhead(compartment, closed), + compartment=message(f"uboot.compartment.{compartment}")) elif key in (pygame.K_q, pygame.K_e): _chart_zoom(game, current, (1.0 / config.MAP_ZOOM_WHEEL_FACTOR if key == pygame.K_q else config.MAP_ZOOM_WHEEL_FACTOR)) diff --git a/src/core/version.py b/src/core/version.py index b56f8fcb..22f03499 100644 --- a/src/core/version.py +++ b/src/core/version.py @@ -5,8 +5,8 @@ version while building the project. """ APP_VERSION = "1.3.0" -SAVE_VERSION = 19 -SAVE_SCHEMA = "u-jagd-save-v19" +SAVE_VERSION = 20 +SAVE_SCHEMA = "u-jagd-save-v20" SPLASH_TEXT = ( "Anti Sub Marine Warfare on uConsole by Dominik Bornhäußer " f"Version {APP_VERSION}" diff --git a/src/enemies/ballast.py b/src/enemies/ballast.py index 7b9600e4..7353ba32 100644 --- a/src/enemies/ballast.py +++ b/src/enemies/ballast.py @@ -10,8 +10,10 @@ against the moment of the same loads. With the automatic trim on, the engineer pumps both toward a neutral boat; a crew may also order the set points itself. Pumping is audible. Whatever the tanks do not take up is a residual weight and a trim angle that push the boat off its ordered depth -unless the hydroplanes (with speed) hold it. The compressor refills the air -bottles while the boat snorkels with the diesels running. +unless the hydroplanes (with speed) hold it. Floodwater in the +compartments (``damage_control.py``) counts as weight and moment the same +way. The compressor refills the air bottles while the boat snorkels with +the diesels running; without power neither pumps nor compressor run. The AI's boats keep their tanks trimmed without this model; only a crewed boat carries its effects. @@ -29,11 +31,6 @@ STATE_FIELDS = frozenset({ TANKS = ("regulating", "trim") -def flooding_kg(damage: float) -> float: - """Water taken in through a holed pressure hull (damage above 30 %).""" - return max(0.0, min(damage, 100.0) - 30.0) / 70.0 * config.UBOOT_FLOOD_MAX_KG - - class BoatBallast: VERSION = 1 @@ -53,21 +50,23 @@ class BoatBallast: # --- derived ----------------------------------------------------------- - def residual_kg(self, damage: float) -> float: - """Weight the tanks do not take up (+ heavy, - light).""" - return self.regulating_kg + self.load_kg + flooding_kg(damage) + def residual_kg(self, flooding_kg: float = 0.0) -> float: + """Weight the tanks do not take up (+ heavy, - light); ``flooding_kg`` + is the water in the compartments (``damage_control.py``).""" + return self.regulating_kg + self.load_kg + flooding_kg - def trim_deg(self) -> float: + def trim_deg(self, flood_moment_kg: float = 0.0) -> float: """Trim angle from the uncompensated moment (+ bow down).""" - moment_t = (self.trim_kg + self.load_trim_kg) / 1000.0 + moment_t = (self.trim_kg + self.load_trim_kg + flood_moment_kg) / 1000.0 return config.clamp(moment_t * config.UBOOT_TRIM_DEG_PER_T, -config.UBOOT_TRIM_MAX_DEG, config.UBOOT_TRIM_MAX_DEG) - def vertical_drift_mps(self, damage: float, speed_kn: float) -> float: + def vertical_drift_mps(self, flooding_kg: float, speed_kn: float, + flood_moment_kg: float = 0.0) -> float: """Depth change the tanks cause (+ down) before the planes act.""" - heavy = self.residual_kg(damage) / 1000.0 * config.UBOOT_BUOYANCY_MPS_PER_T + heavy = self.residual_kg(flooding_kg) / 1000.0 * config.UBOOT_BUOYANCY_MPS_PER_T angle = (config.kn_to_nm_per_s(max(speed_kn, 0.0)) * 1852.0 - * math.sin(math.radians(self.trim_deg()))) + * math.sin(math.radians(self.trim_deg(flood_moment_kg)))) return config.clamp(heavy + angle, -config.UBOOT_BUOYANCY_MAX_MPS, config.UBOOT_BUOYANCY_MAX_MPS) @@ -80,26 +79,28 @@ class BoatBallast: def dived(self) -> bool: return self.mbt >= 1.0 - def neutral_targets(self, damage: float) -> tuple: + def neutral_targets(self, flooding_kg: float = 0.0, flood_moment_kg: float = 0.0) -> tuple: """Set points that make the boat neutral, within tank capacity.""" - regulating = config.clamp(-(self.load_kg + flooding_kg(damage)), + regulating = config.clamp(-(self.load_kg + flooding_kg), -config.UBOOT_REGULATING_KG, config.UBOOT_REGULATING_KG) - trim = config.clamp(-self.load_trim_kg, -config.UBOOT_TRIM_TANK_KG, + trim = config.clamp(-(self.load_trim_kg + flood_moment_kg), -config.UBOOT_TRIM_TANK_KG, config.UBOOT_TRIM_TANK_KG) return regulating, trim # --- model ------------------------------------------------------------- - def update(self, dt: float, *, damage: float, compressor: bool, - vent_ordered: bool) -> list: - """Advance pumps, tanks and air by ``dt`` seconds; return notice keys.""" + def update(self, dt: float, *, flooding_kg: float = 0.0, flood_moment_kg: float = 0.0, + compressor: bool, vent_ordered: bool, power: bool = True) -> list: + """Advance pumps, tanks and air by ``dt`` seconds; return notice keys. + Without power the trim pumps and the compressor stand still.""" if not math.isfinite(dt) or dt < 0.0: raise ValueError("ballast dt must be finite and non-negative") notices = [] if self.auto: - self.regulating_order_kg, self.trim_order_kg = self.neutral_targets(damage) + self.regulating_order_kg, self.trim_order_kg = self.neutral_targets( + flooding_kg, flood_moment_kg) moved = 0.0 - for field, order, rate in ( + for field, order, rate in () if not power else ( ("regulating_kg", self.regulating_order_kg, config.UBOOT_REGULATING_PUMP_KG_S), ("trim_kg", self.trim_order_kg, config.UBOOT_TRIM_PUMP_KG_S)): value = getattr(self, field) @@ -124,7 +125,7 @@ class BoatBallast: if self.mbt >= 1.0: self.venting = False notices.append("tanks_flooded") - if compressor and self.hp_air_bar < config.UBOOT_HP_AIR_MAX_BAR: + if compressor and power and self.hp_air_bar < config.UBOOT_HP_AIR_MAX_BAR: self.hp_air_bar = min(config.UBOOT_HP_AIR_MAX_BAR, self.hp_air_bar + config.UBOOT_HP_COMPRESSOR_BAR_S * dt) return notices diff --git a/src/enemies/damage_control.py b/src/enemies/damage_control.py new file mode 100644 index 00000000..64674460 --- /dev/null +++ b/src/enemies/damage_control.py @@ -0,0 +1,322 @@ +"""Damage control of a crewed submarine (fictional, deterministic). + +Six compartments from bow to stern. A hit holes one or two of them (leak +0..1) and may start a fire. Water comes in through a hole with the square +root of the depth (orifice law), spills into open neighbours once a +compartment is half full, and puts out a fire it covers. Seawater in the +battery room makes chlorine gas; a flooded or burning battery room cuts the +power (no motor, no electric pumps). A closed bulkhead keeps water, fire and +gas in its compartment and starves a fire there. + +Two damage-control teams walk the boat (transit per compartment) and seal a +leak, pump a compartment (hand pumps without power) or fight a fire; gas +halves their work. What the teams do not stop is water in the boat: its +weight and its moment fore and aft go into the trim (``ballast.py``), and a +compartment that is flooded, burning or gassed takes its station down. + +Only a crewed boat carries this model; the AI keeps its single damage value. +New random draws (where a hit lands, whether it burns) use ``detrand``. +""" + +import math + +from src.core import config, detrand + +COMPARTMENTS = ("bow", "control", "quarters", "battery", "engine", "stern") +TASKS = ("seal", "pump", "fire", "idle") +TEAMS = 2 +COMPARTMENT_FIELDS = frozenset({"water_kg", "leak", "fire", "chlorine", "closed"}) +TEAM_FIELDS = frozenset({"compartment", "task", "transit_s"}) +STATE_FIELDS = frozenset({"version", "compartments", "teams", "hits"}) + + +def capacity_kg(index: int) -> float: + return float(config.UBOOT_DC_CAPACITY_KG[index]) + + +class _Compartment: + __slots__ = ("water_kg", "leak", "fire", "chlorine", "closed") + + def __init__(self): + self.water_kg = 0.0 + self.leak = 0.0 # hole size (1 = the reference hole) + self.fire = 0.0 # intensity 0..1 + self.chlorine = 0.0 # gas concentration 0..1 + self.closed = False # bulkheads shut + + +class BoatDamageControl: + VERSION = 1 + + def __init__(self): + self.compartments = [_Compartment() for _ in COMPARTMENTS] + self.teams = [dict(compartment="quarters", task="idle", transit_s=0.0) + for _ in range(TEAMS)] + self.hits = 0 # counter for the hit draws + self.pumping = False # this step (display) + + # --- derived ----------------------------------------------------------- + + def total_water_kg(self) -> float: + return sum(c.water_kg for c in self.compartments) + + def water_moment_kg(self) -> float: + """Floodwater moment fore (+) and aft (-), in kg at the tank arm.""" + return sum(c.water_kg * arm for c, arm in + zip(self.compartments, config.UBOOT_DC_ARM)) + + def power(self) -> bool: + battery = self.compartments[COMPARTMENTS.index("battery")] + return (battery.water_kg < config.UBOOT_DC_POWER_WATER_KG + and battery.fire < config.UBOOT_DC_DOWN_FIRE) + + def down(self, name: str) -> bool: + """The compartment is flooded, burning or gassed: its station is out.""" + index = COMPARTMENTS.index(name) + c = self.compartments[index] + return (c.water_kg >= config.UBOOT_DC_DOWN_WATER * capacity_kg(index) + or c.fire >= config.UBOOT_DC_DOWN_FIRE + or c.chlorine >= config.UBOOT_DC_DOWN_GAS) + + def any_damage(self) -> bool: + return any(c.leak > 0.0 or c.fire > 0.0 or c.chlorine > 0.0 or c.water_kg > 0.0 + for c in self.compartments) + + def teams_in(self, name: str) -> list: + return [index for index, team in enumerate(self.teams) + if team["compartment"] == name] + + # --- hits -------------------------------------------------------------- + + def apply_hit(self, amount: float, seed: int) -> list: + """Hole the compartment where a hit of ``amount`` % lands (a heavy + one its neighbour too) and maybe start a fire; returns notices.""" + if not math.isfinite(amount) or amount <= 0.0: + return [] + self.hits += 1 + index = min(len(COMPARTMENTS) - 1, + int(detrand.u01(seed, "dc-hit", self.hits) * len(COMPARTMENTS))) + leak = min(1.0, amount * config.UBOOT_DC_LEAK_PER_PCT) + struck = [(index, leak)] + if amount >= config.UBOOT_DC_SECOND_HIT_PCT: + side = -1 if detrand.u01(seed, "dc-side", self.hits) < 0.5 else 1 + other = index + side if 0 <= index + side < len(COMPARTMENTS) else index - side + struck.append((other, leak * 0.5)) + notices = [] + for number, (where, size) in enumerate(struck): + c = self.compartments[where] + c.leak = min(1.0, c.leak + size) + notices.append(("dc_leak", dict(compartment=COMPARTMENTS[where]))) + if detrand.u01(seed, "dc-fire", self.hits, number) < min( + 1.0, amount / config.UBOOT_DC_FIRE_CHANCE_PCT): + if c.fire <= 0.0: + notices.append(("dc_fire", dict(compartment=COMPARTMENTS[where]))) + c.fire = max(c.fire, config.UBOOT_DC_FIRE_START) + return notices + + # --- model ------------------------------------------------------------- + + def update(self, dt: float, *, depth_m: float) -> list: + """Advance leaks, spill, fire, gas and the teams; return notices.""" + if not math.isfinite(dt) or dt < 0.0 or not math.isfinite(depth_m): + raise ValueError("damage control inputs must be finite") + notices = [] + was_power = self.power() + was_gas = self.compartments[COMPARTMENTS.index("battery")].chlorine > 0.0 + before = [(c.leak > 0.0, c.fire > 0.0, + c.water_kg >= capacity_kg(index) * 0.999) + for index, c in enumerate(self.compartments)] + head = math.sqrt(max(depth_m, 1.0) / 100.0) + for index, c in enumerate(self.compartments): + if c.leak > 0.0: + c.water_kg = min(capacity_kg(index), c.water_kg + + config.UBOOT_DC_LEAK_KG_S * c.leak * head * dt) + self._spill(dt) + self._burn(dt) + self._gas(dt) + self.pumping = False + power = self.power() + for team in self.teams: + self._work(team, dt, power) + for index, c in enumerate(self.compartments): + leaking, burning, full = before[index] + name = COMPARTMENTS[index] + if leaking and c.leak <= 0.0: + notices.append(("dc_leak_sealed", dict(compartment=name))) + if burning and c.fire <= 0.0: + notices.append(("dc_fire_out", dict(compartment=name))) + elif not burning and c.fire > 0.0: + notices.append(("dc_fire", dict(compartment=name))) + if not full and c.water_kg >= capacity_kg(index) * 0.999: + notices.append(("dc_flooded", dict(compartment=name))) + if not was_gas and self.compartments[COMPARTMENTS.index("battery")].chlorine > 0.0: + notices.append(("dc_chlorine", {})) + if was_power != self.power(): + notices.append(("dc_power_restored" if self.power() else "dc_power_lost", {})) + return notices + + def _neighbours(self, index: int): + for other in (index - 1, index + 1): + if 0 <= other < len(COMPARTMENTS): + yield other + + def _spill(self, dt: float) -> None: + """Water above half a compartment runs into open neighbours.""" + moves = [0.0] * len(COMPARTMENTS) + for index, c in enumerate(self.compartments): + spare = c.water_kg - config.UBOOT_DC_SPILL_FRACTION * capacity_kg(index) + if c.closed or spare <= 0.0: + continue + for other in self._neighbours(index): + target = self.compartments[other] + if target.closed or target.water_kg >= capacity_kg(other): + continue + amount = min(config.UBOOT_DC_SPILL_KG_S * dt, spare / 2.0) + moves[index] -= amount + moves[other] += amount + for index, c in enumerate(self.compartments): + c.water_kg = config.clamp(c.water_kg + moves[index], 0.0, capacity_kg(index)) + + def _burn(self, dt: float) -> None: + """Fires grow, spread to open neighbours, die under water or behind + closed bulkheads; a team fighting one keeps it from growing.""" + spread = [0.0] * len(COMPARTMENTS) + for index, c in enumerate(self.compartments): + if c.fire <= 0.0: + continue + if c.water_kg >= config.UBOOT_DC_SPILL_FRACTION * capacity_kg(index): + c.fire = 0.0 # smothered by the water + continue + if c.closed: + c.fire = max(0.0, c.fire - dt / config.UBOOT_DC_FIRE_STARVE_S) + continue + if not self._fought(index): + c.fire = min(1.0, c.fire + dt / config.UBOOT_DC_FIRE_GROW_S) + if c.fire >= 1.0: + for other in self._neighbours(index): + if not self.compartments[other].closed: + spread[other] += dt / config.UBOOT_DC_FIRE_SPREAD_S + for index, c in enumerate(self.compartments): + if spread[index] > 0.0 and c.water_kg < ( + config.UBOOT_DC_SPILL_FRACTION * capacity_kg(index)): + c.fire = min(1.0, c.fire + spread[index]) + + def _fought(self, index: int) -> bool: + """A team on the spot keeps the fire from growing.""" + return any(team["compartment"] == COMPARTMENTS[index] and team["task"] == "fire" + and team["transit_s"] <= 0.0 for team in self.teams) + + def _gas(self, dt: float) -> None: + """Seawater on the battery makes chlorine; it drifts through open + bulkheads and clears slowly once the battery is dry.""" + battery_index = COMPARTMENTS.index("battery") + battery = self.compartments[battery_index] + if battery.water_kg >= config.UBOOT_DC_CHLORINE_WATER_KG: + battery.chlorine = min(1.0, battery.chlorine + dt / config.UBOOT_DC_CHLORINE_RISE_S) + drift = [0.0] * len(COMPARTMENTS) + for index, c in enumerate(self.compartments): + if c.chlorine >= 0.5 and not c.closed: + for other in self._neighbours(index): + if not self.compartments[other].closed: + drift[other] += 0.5 * dt / config.UBOOT_DC_CHLORINE_RISE_S + for index, c in enumerate(self.compartments): + rising = index == battery_index and ( + battery.water_kg >= config.UBOOT_DC_CHLORINE_WATER_KG) + if drift[index] > 0.0: + c.chlorine = min(c.chlorine + drift[index], + max(c.chlorine, battery.chlorine)) + elif not rising and c.chlorine > 0.0: + c.chlorine = max(0.0, c.chlorine - dt / config.UBOOT_DC_CHLORINE_DECAY_S) + + def _work(self, team: dict, dt: float, power: bool) -> None: + if team["transit_s"] > 0.0: + team["transit_s"] = max(0.0, team["transit_s"] - dt) + return + index = COMPARTMENTS.index(team["compartment"]) + c = self.compartments[index] + rate = config.UBOOT_DC_GAS_FACTOR if c.chlorine >= 0.5 else 1.0 + swamped = c.water_kg >= 0.9 * capacity_kg(index) + task = team["task"] + if task == "seal" and not swamped: + c.leak = max(0.0, c.leak - rate * dt / config.UBOOT_DC_SEAL_S) + elif task == "fire" and not swamped: + c.fire = max(0.0, c.fire - rate * dt / config.UBOOT_DC_FIRE_FIGHT_S) + elif task == "pump" and c.water_kg > 0.0: + pump = config.UBOOT_DC_PUMP_KG_S * (1.0 if power else config.UBOOT_DC_HAND_PUMP) + c.water_kg = max(0.0, c.water_kg - rate * pump * dt) + self.pumping = self.pumping or power + + # --- crew orders ------------------------------------------------------- + + def order_team(self, team, compartment, task): + """Send a team to a compartment with a task (transit per bulkhead).""" + if (type(team) is not int or not 0 <= team < TEAMS + or compartment not in COMPARTMENTS or task not in TASKS): + return "invalid_value" + row = self.teams[team] + if row["compartment"] != compartment: + hops = abs(COMPARTMENTS.index(row["compartment"]) - COMPARTMENTS.index(compartment)) + row["transit_s"] = hops * config.UBOOT_DC_TRANSIT_S + row["compartment"] = compartment + row["task"] = task + return True + + def set_bulkhead(self, compartment, closed): + if compartment not in COMPARTMENTS or type(closed) is not bool: + return "invalid_value" + self.compartments[COMPARTMENTS.index(compartment)].closed = closed + return True + + # --- persistence ------------------------------------------------------- + + def serialize(self) -> dict: + return dict( + version=self.VERSION, hits=self.hits, + compartments={name: dict(water_kg=c.water_kg, leak=c.leak, fire=c.fire, + chlorine=c.chlorine, closed=c.closed) + for name, c in zip(COMPARTMENTS, self.compartments)}, + teams=[dict(team) for team in self.teams]) + + @classmethod + def restore(cls, state) -> "BoatDamageControl": + if not isinstance(state, dict) or set(state) != STATE_FIELDS: + raise ValueError("invalid damage control fields") + if type(state["version"]) is not int or state["version"] != cls.VERSION: + raise ValueError("unsupported damage control version") + if type(state["hits"]) is not int or not 0 <= state["hits"] <= 1_000_000: + raise ValueError("invalid damage control hits") + compartments, teams = state["compartments"], state["teams"] + if not isinstance(compartments, dict) or set(compartments) != set(COMPARTMENTS): + raise ValueError("invalid damage control compartments") + if not isinstance(teams, list) or len(teams) != TEAMS: + raise ValueError("invalid damage control teams") + result = cls() + result.hits = state["hits"] + for index, name in enumerate(COMPARTMENTS): + row = compartments[name] + if not isinstance(row, dict) or set(row) != COMPARTMENT_FIELDS: + raise ValueError("invalid compartment fields") + if type(row["closed"]) is not bool: + raise ValueError("invalid compartment bulkhead") + for field, high in (("water_kg", capacity_kg(index)), ("leak", 1.0), + ("fire", 1.0), ("chlorine", 1.0)): + value = row[field] + if (type(value) not in (int, float) or isinstance(value, bool) + or not math.isfinite(value) or not 0.0 <= value <= high): + raise ValueError(f"invalid compartment {field}") + c = result.compartments[index] + c.water_kg, c.leak = float(row["water_kg"]), float(row["leak"]) + c.fire, c.chlorine = float(row["fire"]), float(row["chlorine"]) + c.closed = row["closed"] + for index, row in enumerate(teams): + if (not isinstance(row, dict) or set(row) != TEAM_FIELDS + or row["compartment"] not in COMPARTMENTS or row["task"] not in TASKS): + raise ValueError("invalid team") + transit = row["transit_s"] + if (type(transit) not in (int, float) or isinstance(transit, bool) + or not math.isfinite(transit) + or not 0.0 <= transit <= config.UBOOT_DC_TRANSIT_S * len(COMPARTMENTS)): + raise ValueError("invalid team transit") + result.teams[index] = dict(compartment=row["compartment"], task=row["task"], + transit_s=float(transit)) + return result diff --git a/src/enemies/sub.py b/src/enemies/sub.py index 07b16e1e..6ba2652f 100644 --- a/src/enemies/sub.py +++ b/src/enemies/sub.py @@ -25,6 +25,7 @@ from src.sensors.platform import ( from src.weapons.torpedo import underwater_path_blocked from src.weapons.asw import ConsumableStore, WeaponBattery from src.enemies.ballast import BoatBallast +from src.enemies.damage_control import BoatDamageControl from src.enemies.endurance import SubmarineEndurance CATALOG = catalog.CATALOG @@ -185,6 +186,9 @@ class Sub: # Tanks, trim and air bottles; only a crewed boat feels them (the # AI keeps itself trimmed and keeps its one legacy blow). self.ballast = BoatBallast() + # Compartments, leaks, fire, gas and the two damage-control teams; + # likewise only a crewed boat's (the AI keeps one damage value). + self.damage_control = BoatDamageControl() # Own passive TMA on one bearing-only contact and crew reaction. self.tma_track = BearingTrack() self.tma_track_id = None @@ -361,6 +365,7 @@ class Sub: if amount is None: amount = self.rng.uniform(60.0, 100.0) self.damage = min(100.0, self.damage + amount) + self._compartment_hit(amount) if self.damage >= 100.0: self.state = "SINKING" self.sink_left = 20.0 @@ -558,6 +563,7 @@ class Sub: if self.hull_fatigue >= 1.0: self.hull_fatigue -= 1.0 self.damage = min(100.0, self.damage + 20.0) + self._compartment_hit(config.UBOOT_DC_FATIGUE_LEAK / config.UBOOT_DC_LEAK_PER_PCT) if self.damage >= 100.0 and self.state != "SINKING": self.state = "SINKING" self.sink_left = 20.0 @@ -590,8 +596,8 @@ class Sub: @property def pumping(self) -> bool: - """A crewed boat's trim pumps are running.""" - return bool(self.manual and self.ballast.pumping) + """A crewed boat's trim or bilge pumps are running.""" + return bool(self.manual and (self.ballast.pumping or self.damage_control.pumping)) def _advance_depth(self, target_depth: float, max_rate: float, dt: float) -> None: """Acceleration-limited depth approach (closed-form, no overshoot). @@ -713,8 +719,9 @@ class Sub: return self.speed = config.clamp(self.speed, 0.0, self.motion.maximum_speed_kn) - if 30.0 < self.damage < 100.0 and not self.emergency_ascent: - # Holed pressure hull: progressive flooding until blown or lost. + if 30.0 < self.damage < 100.0 and not self.emergency_ascent and not self.manual: + # Holed pressure hull: progressive flooding until blown or lost + # (a crewed boat floods compartment by compartment instead). self.damage = min(100.0, self.damage + 0.01 * dt * (self.damage - 30.0) / 70.0) self._update_hull_stress(dt) @@ -1213,6 +1220,16 @@ class Sub: ceiling = min(ceiling, config.UBOOT_SILENT_MAX_KN) if self.snorkeling: ceiling = min(ceiling, config.UBOOT_SNORKEL_MAX_KN) + control = self.damage_control + if not control.power(): + ceiling = 0.0 # no power: the motor stops + elif control.down("stern"): + ceiling *= config.UBOOT_DC_STERN_SPEED_FACTOR + if self.snorkeling and control.down("engine"): + # Diesel room flooded, burning or gassed: the diesels stop. + self.endurance.stop_snorkel() + if crew is not None: + crew.event("snorkel_stopped") self.target_depth = config.clamp(order_depth, 0.0, safe_depth) if not self.ballast.dived(): # Main ballast blown: the boat stays up until the vents flood it. @@ -1220,7 +1237,8 @@ class Sub: self._advance_depth(self.target_depth, self.motion.depth_rate_m_s, dt) self.speed = config.clamp(self.order_speed, 0.0, ceiling) self._update_ballast(dt) - if crew is not None and crew.mast and self.depth > MAST_DEPTH_M + 1.0: + if crew is not None and crew.mast and (self.depth > MAST_DEPTH_M + 1.0 + or control.down("control")): crew.mast = False # masts come down when diving crew.event("mast_lowered") if self.snorkeling and self.depth > self.endurance.profile.snorkel_depth_m + 1.0: @@ -1229,16 +1247,36 @@ class Sub: if crew is not None: crew.event("snorkel_stopped") + def flooding_kg(self) -> float: + """Floodwater in the compartments (a crewed boat's only).""" + return self.damage_control.total_water_kg() + + def flood_moment_kg(self) -> float: + return self.damage_control.water_moment_kg() + + def _compartment_hit(self, amount: float) -> None: + """A crewed boat feels a hit compartment by compartment.""" + if not self.manual or self.sunk or self.state == "SINKING": + return + notices = self.damage_control.apply_hit(amount, self.sensor_seed) + if self.crew is not None: + for key, values in notices: + self.crew.event(key, **values) + def _update_ballast(self, dt: float) -> None: - """Pumps, vents and compressor; the residual weight and trim move - the boat off its ordered depth where the planes cannot hold it.""" + """Compartments, pumps, vents and compressor; the residual weight + and trim move the boat off its ordered depth where the planes cannot + hold it.""" ballast = self.ballast + dc_notices = self.damage_control.update(dt, depth_m=self.depth) + flooding, moment = self.flooding_kg(), self.flood_moment_kg() + power = self.damage_control.power() compressor = self.snorkeling and self.snorkel_rate != "vent" vent = self.order_depth > config.UBOOT_MBT_SURFACE_DEPTH_M + 2.0 - notices = ballast.update(dt, damage=self.damage, compressor=compressor, - vent_ordered=vent) + notices = ballast.update(dt, flooding_kg=flooding, flood_moment_kg=moment, + compressor=compressor, vent_ordered=vent, power=power) if ballast.dived() and not self.emergency_ascent: - drift = ballast.vertical_drift_mps(self.damage, self.speed) + drift = ballast.vertical_drift_mps(flooding, self.speed, moment) bottom = self.last_bottom_m if self.last_bottom_m is not None else float("inf") self.depth = config.clamp(self.depth + drift * dt, 0.0, max(0.0, bottom)) self.blow_available = ballast.can_blow() and not self.emergency_ascent @@ -1247,17 +1285,20 @@ class Sub: return for key in notices: crew.event(key) + for key, values in dc_notices: + crew.event(key, **values) # Out-of-trim warnings on the edge (display state, not saved: a loaded # boat starts from its current trim and so announces nothing). - residual = ballast.residual_kg(self.damage) + residual = ballast.residual_kg(flooding) heavy = ("heavy" if residual > config.UBOOT_HEAVY_WARN_KG else "light" if residual < -config.UBOOT_HEAVY_WARN_KG else None) if heavy is not None and heavy != getattr(self, "_trim_seen", heavy): crew.event(f"boat_{heavy}", weight=f"{abs(residual) / 1000.0:.1f}") self._trim_seen = heavy - angle = abs(ballast.trim_deg()) > config.UBOOT_TRIM_WARN_DEG + trim = ballast.trim_deg(moment) + angle = abs(trim) > config.UBOOT_TRIM_WARN_DEG if angle and not getattr(self, "_trim_angle_seen", True): - crew.event("trim_angle", angle=f"{ballast.trim_deg():+.1f}") + crew.event("trim_angle", angle=f"{trim:+.1f}") self._trim_angle_seen = angle def command_trim_auto(self, enabled): @@ -1273,10 +1314,24 @@ class Sub: return "not_ready" return self.ballast.step(tank, direction) + def command_dc_team(self, team, compartment, task): + """Crew: send a damage-control team to a compartment with a task.""" + if not self._crew_ready(): + return "not_ready" + return self.damage_control.order_team(team, compartment, task) + + def command_bulkhead(self, compartment, closed): + """Crew: shut (or open) a compartment's bulkheads.""" + if not self._crew_ready(): + return "not_ready" + return self.damage_control.set_bulkhead(compartment, closed) + def fire_readiness(self, bearing=None, salvo: int = 1): """Why a crew torpedo shot is impossible now, or None when ready.""" if not self.manual or self.sunk or self.state in ("SINKING", "SUNK"): return "not_ready" + if self.damage_control.down("bow"): + return "uboot_compartment_down" # torpedo room flooded or burning if self.torpedoes_left <= 0: return "no_torpedoes" if self.torpedoes_left < salvo: @@ -1488,6 +1543,8 @@ class Sub: if not on: self.endurance.stop_snorkel() return True + if self.damage_control.down("engine"): + return "uboot_compartment_down" if self.depth > self.endurance.profile.snorkel_depth_m + 1.0: return "uboot_too_deep" self.crew.bottomed = False @@ -1503,6 +1560,8 @@ class Sub: return "not_ready" if on and self.depth > MAST_DEPTH_M: return "uboot_mast_depth" + if on and self.damage_control.down("control"): + return "uboot_compartment_down" # control room out: no masts self.crew.mast = on return True diff --git a/src/ui/uboot_ballast.py b/src/ui/uboot_ballast.py index b639c53d..c69cbd4f 100644 --- a/src/ui/uboot_ballast.py +++ b/src/ui/uboot_ballast.py @@ -12,7 +12,6 @@ import pygame from src.core import config from src.core.i18n import message -from src.enemies.ballast import flooding_kg from src.ui import layout, lines @@ -39,6 +38,7 @@ def _tank(s, rect, fraction, color) -> None: def draw_cross_section(s, sub, rect) -> None: """Hull with the tanks (bow to the right) and the trim angle above it.""" ballast = sub.ballast + trim = ballast.trim_deg(sub.flood_moment_kg()) rect = pygame.Rect(rect) cx, cy = rect.centerx, rect.y + int(rect.h * 0.64) half_w, half_h = rect.w // 2 - 8, max(14, int(rect.h * 0.3)) @@ -68,9 +68,9 @@ def draw_cross_section(s, sub, rect) -> None: reach = half_w - 10 y0 = rect.y + max(10, (cy - half_h - rect.y) // 2) limit = math.degrees(math.asin(min(1.0, max(2.0, y0 - rect.y - 2) / reach))) - angle = math.radians(max(-limit, min(limit, ballast.trim_deg() * 4.0))) + angle = math.radians(max(-limit, min(limit, trim * 4.0))) lines.line(s, config.COLOR_TEXT_DIM, (cx - reach, y0), (cx + reach, y0), 1) - color = (config.COLOR_WARN if abs(ballast.trim_deg()) > config.UBOOT_TRIM_WARN_DEG + color = (config.COLOR_WARN if abs(trim) > config.UBOOT_TRIM_WARN_DEG else config.COLOR_OK) lines.line(s, color, (cx - reach * math.cos(angle), y0 - reach * math.sin(angle)), (cx + reach * math.cos(angle), y0 + reach * math.sin(angle)), 2) @@ -88,10 +88,10 @@ def draw_ballast_page(s, game, boat, x, y, w, h) -> None: """Main ballast and air, then the trim: tanks, set points and residual.""" sub = boat.sub ballast = sub.ballast - damage = sub.damage - residual = ballast.residual_kg(damage) - drift = ballast.vertical_drift_mps(damage, sub.speed) - trim = ballast.trim_deg() + flooding, moment = sub.flooding_kg(), sub.flood_moment_kg() + residual = ballast.residual_kg(flooding) + drift = ballast.vertical_drift_mps(flooding, sub.speed, moment) + trim = ballast.trim_deg(moment) out_of_trim = (abs(residual) > config.UBOOT_HEAVY_WARN_KG or abs(trim) > config.UBOOT_TRIM_WARN_DEG) section = layout.box(s, (x, y, w, 130), "uboot.panel.tanks", @@ -107,7 +107,7 @@ def draw_ballast_page(s, game, boat, x, y, w, h) -> None: color=config.COLOR_WARN if not ballast.dived() else None, size=15, label_w=150) compressor = (sub.snorkeling and sub.snorkel_rate != "vent" - and ballast.hp_air_bar < config.UBOOT_HP_AIR_MAX_BAR) + and sub.damage_control.power() and ballast.hp_air_bar < config.UBOOT_HP_AIR_MAX_BAR) layout.status_line(s, bx, by + 22, bw, "uboot.ballast.label.air", message("uboot.ballast.air_compressor" if compressor else "uboot.ballast.air", bar=_fmt(ballast.hp_air_bar), @@ -145,8 +145,8 @@ def draw_ballast_page(s, game, boat, x, y, w, h) -> None: ("uboot.ballast.label.drift", message("uboot.ballast.drift", rate=f"{drift:+.2f}"), None), ("uboot.ballast.label.flooding", message( - "uboot.ballast.weight", weight=f"{flooding_kg(damage) / 1000.0:.1f}"), - config.COLOR_DANGER if damage > 30.0 else None), + "uboot.ballast.weight", weight=f"{flooding / 1000.0:.1f}"), + config.COLOR_DANGER if flooding > config.UBOOT_HEAVY_WARN_KG else None), ("uboot.ballast.label.pumps", message("uboot.ballast.pumps_on" if ballast.pumping else "uboot.ballast.pumps_off"), config.COLOR_WARN if ballast.pumping else None), diff --git a/src/ui/uboot_damage.py b/src/ui/uboot_damage.py new file mode 100644 index 00000000..2be1520a --- /dev/null +++ b/src/ui/uboot_damage.py @@ -0,0 +1,138 @@ +"""Damage-control page of the crewed submarine's engine room (uConsole). + +Own-ship state only (``src/enemies/damage_control.py``): the six +compartments from stern (left) to bow (right) with their water, fire, gas +and bulkheads, a table of the numbers, and the two teams with the order the +operator is about to give. +""" + +import pygame + +from src.core import config +from src.core.i18n import message +from src.enemies.damage_control import COMPARTMENTS, TASKS, capacity_kg +from src.ui import layout + +_GAS = (150, 190, 60) + + +def selection(boat) -> tuple: + """The compartment and task the operator has picked (display state).""" + index = boat.dc_selected % len(COMPARTMENTS) + task = boat.dc_task if boat.dc_task in TASKS else "seal" + return index, task + + +def _alert(control, index) -> tuple: + c = control.compartments[index] + if c.fire > 0.0 or control.down(COMPARTMENTS[index]) or ( + COMPARTMENTS[index] == "battery" and not control.power()): + return config.COLOR_DANGER + if c.leak > 0.0 or c.chlorine > 0.0 or c.water_kg > 0.0: + return config.COLOR_WARN + return None + + +def draw_boat_compartments(s, control, rect, selected=None) -> None: + """The pressure hull cut into its compartments, bow to the right.""" + rect = pygame.Rect(rect) + count = len(COMPARTMENTS) + hull = rect.inflate(-16, -24) + seg_w = hull.w / count + for index in range(count): + c = control.compartments[index] + left = hull.x + int(round((count - 1 - index) * seg_w)) + right = hull.x + int(round((count - index) * seg_w)) + cell = pygame.Rect(left, hull.y, right - left, hull.h) + fraction = max(0.0, min(1.0, c.water_kg / capacity_kg(index))) + water = cell.copy() + water.h = int(round(cell.h * fraction)) + water.bottom = cell.bottom + if water.h > 0: + pygame.draw.rect(s, config.COLOR_SONAR_RING, water) + if c.chlorine > 0.0: + gas = cell.inflate(-6, -6) + pygame.draw.rect(s, _GAS, gas, max(1, int(round(3 * c.chlorine)))) + if c.fire > 0.0: + flame = pygame.Rect(cell.x + 3, cell.y + 3, max(1, int((cell.w - 6) * c.fire)), 6) + pygame.draw.rect(s, config.COLOR_DANGER, flame) + if c.leak > 0.0: + pygame.draw.circle(s, config.COLOR_WARN, (cell.centerx, cell.bottom - 6), + max(2, int(round(5 * c.leak)))) + border = config.COLOR_TEXT if selected == index else config.COLOR_TEXT_DIM + pygame.draw.rect(s, border, cell, 2 if selected == index else 1) + if c.closed: + for edge in (cell.left, cell.right - 1): + pygame.draw.line(s, config.COLOR_WARN, (edge, cell.y - 4), + (edge, cell.bottom + 3), 3) + teams = [str(team + 1) for team in control.teams_in(COMPARTMENTS[index])] + if teams: + layout.blit_line(s, " ".join(teams), (cell.x + 4, cell.y + 12, cell.w - 8, 16), + config.COLOR_OK, size=13) + # Bow and stern caps. + pygame.draw.line(s, config.COLOR_TEXT_DIM, (hull.right, hull.y), (rect.right - 2, hull.centery)) + pygame.draw.line(s, config.COLOR_TEXT_DIM, (hull.right, hull.bottom), + (rect.right - 2, hull.centery)) + pygame.draw.line(s, config.COLOR_TEXT_DIM, (hull.x, hull.y), (rect.x + 2, hull.centery)) + pygame.draw.line(s, config.COLOR_TEXT_DIM, (hull.x, hull.bottom), (rect.x + 2, hull.centery)) + + +def _pct(value: float) -> str: + return f"{value * 100.0:.0f}" + + +def draw_damage_page(s, game, boat, x, y, w, h) -> None: + """Compartment picture, the table of compartments and the two teams.""" + control = boat.sub.damage_control + selected, task = selection(boat) + alarm = any(_alert(control, index) == config.COLOR_DANGER for index in range(len(COMPARTMENTS))) + picture = layout.box(s, (x, y, w, 130), "uboot.panel.compartments", + border=config.COLOR_DANGER if alarm else config.COLOR_TEXT) + draw_boat_compartments(s, control, picture, selected) + table_y = y + 138 + table_h = 30 + 20 * (len(COMPARTMENTS) + 1) + tx, ty, tw, _th = layout.box(s, (x, table_y, w, table_h), "uboot.panel.dc_status") + name_w = max(90, int(tw * 0.24)) + columns = ("uboot.dc.col.water", "uboot.dc.col.leak", "uboot.dc.col.fire", + "uboot.dc.col.gas", "uboot.dc.col.bulkhead") + cell_w = (tw - name_w) // len(columns) + for column, key in enumerate(columns): + layout.blit_line(s, key, (tx + name_w + column * cell_w, ty, cell_w - 4, 18), + config.COLOR_TEXT_DIM, size=13) + for index, name in enumerate(COMPARTMENTS): + c = control.compartments[index] + row_y = ty + 20 * (index + 1) + color = _alert(control, index) or config.COLOR_TEXT + if index == selected: + pygame.draw.rect(s, config.COLOR_SELECT_BG, (tx - 4, row_y - 1, tw + 8, 19)) + layout.blit_line(s, f"uboot.compartment.{name}", (tx, row_y, name_w - 4, 18), + color, size=14) + values = (f"{c.water_kg / 1000.0:.1f}", _pct(c.leak), _pct(c.fire), _pct(c.chlorine), + "uboot.dc.closed" if c.closed else "uboot.dc.open") + for column, value in enumerate(values): + layout.blit_line(s, value, (tx + name_w + column * cell_w, row_y, cell_w - 4, 18), + color, size=14) + teams_y = table_y + table_h + 8 + bx, by, bw, bh = layout.box(s, (x, teams_y, w, max(60, y + h - teams_y)), + "uboot.panel.dc_teams", + border=config.COLOR_TEXT if control.power() else config.COLOR_DANGER) + rows = [("uboot.dc.label.power", + message("uboot.dc.power_on" if control.power() else "uboot.dc.power_off"), + None if control.power() else config.COLOR_DANGER)] + for number, team in enumerate(control.teams): + state = (message("uboot.dc.team_transit", compartment=message( + f"uboot.compartment.{team['compartment']}"), + seconds=f"{team['transit_s']:.0f}") + if team["transit_s"] > 0.0 else + message("uboot.dc.team_at", compartment=message( + f"uboot.compartment.{team['compartment']}"), + task=message(f"uboot.dc.task.{team['task']}"))) + rows.append((message("uboot.dc.label.team", number=number + 1), state, None)) + rows.append(("uboot.dc.label.order", message( + "uboot.dc.order", compartment=message(f"uboot.compartment.{COMPARTMENTS[selected]}"), + task=message(f"uboot.dc.task.{task}")), config.COLOR_WARN)) + for index, (label, value, color) in enumerate(rows): + if (index + 1) * 20 > bh: + break + layout.status_line(s, bx, by + index * 20, bw, label, value, color=color, + size=15, label_w=150) diff --git a/src/ui/uboot_view.py b/src/ui/uboot_view.py index 89da1e1a..5ffdbb53 100644 --- a/src/ui/uboot_view.py +++ b/src/ui/uboot_view.py @@ -26,6 +26,8 @@ from src.ui.sonar_view import draw_sonar_view from src.ui.stations_view import (_panel, _station_content_top, draw_station_page_tabs, station_page_tab_at) from src.ui.uboot_ballast import draw_ballast_page +from src.ui.uboot_damage import draw_damage_page +from src.enemies.damage_control import COMPARTMENTS from src.ui.uboot_scope import draw_scope_page from src.ui.viewport import Viewport from src.ui.weather_station import draw_weather_station @@ -33,7 +35,8 @@ from src.ui.weather_station import draw_weather_station UBOOT_PAGES = ("UBOOT_NAV", "UBOOT_WEAPONS", "UBOOT_SCOPE") # Panel pages of each boat station beside the chart (the sonar room is full screen). STATION_PAGES = {"uboot": UBOOT_PAGES, "uboot_weapons": ("UBOOT_WEAPONS",), - "uboot_engine": ("UBOOT_ENGINE", "UBOOT_SUPPLY", "UBOOT_BALLAST"), + "uboot_engine": ("UBOOT_ENGINE", "UBOOT_SUPPLY", "UBOOT_BALLAST", + "UBOOT_DAMAGE"), "uboot_esm": ("UBOOT_ESM", "UBOOT_SCOPE"), "uboot_nav": ("UBOOT_NAV",)} @@ -340,6 +343,17 @@ def threats(game, boat) -> list: rows.append((message("uboot.threat.torpedo", age=_fmt(torpedo_age)), "danger")) if sub.damage >= 50: rows.append((message("uboot.threat.damage", value=_fmt(sub.damage)), "danger")) + control = sub.damage_control + if not control.power(): + rows.append((message("uboot.threat.power"), "danger")) + burning = [name for name, c in zip(COMPARTMENTS, control.compartments) if c.fire > 0.0] + if burning: + rows.append((message("uboot.threat.fire", + compartment=message(f"uboot.compartment.{burning[0]}")), "danger")) + leaking = [name for name, c in zip(COMPARTMENTS, control.compartments) if c.leak > 0.0] + if leaking: + rows.append((message("uboot.threat.leak", + compartment=message(f"uboot.compartment.{leaking[0]}")), "warn")) ping_age = alarms["last_ping_age"] if math.isfinite(ping_age) and ping_age < ALARM_WINDOW_S: if crew is not None and crew.ping_bearing is not None: @@ -636,6 +650,9 @@ _FOOTERS = { ("uboot_engine", "UBOOT_BALLAST"): (("↑/↓", "uboot.footer.regulating"), ("←/→", "uboot.footer.trim"), ("Z", "uboot.footer.trim_auto")), + ("uboot_engine", "UBOOT_DAMAGE"): (("↑/↓ ←/→", "uboot.footer.dc_pick"), + ("help.key.enter", "uboot.footer.dc_team"), + ("I", "uboot.footer.dc_bulkhead")), } @@ -666,6 +683,7 @@ def draw_command_panel(game, boat) -> None: drawer = {"UBOOT_NAV": _draw_nav_page, "UBOOT_WEAPONS": _draw_weapons_page, "UBOOT_ENGINE": _draw_engine_page, "UBOOT_SUPPLY": _draw_supply_page, "UBOOT_ESM": _draw_esm_page, "UBOOT_BALLAST": draw_ballast_page, + "UBOOT_DAMAGE": draw_damage_page, "UBOOT_SCOPE": draw_scope_page}[name] drawer(s, game, boat, x, content_y, w, content_h) specs = tuple( diff --git a/tests/test_boat_ballast.py b/tests/test_boat_ballast.py index bf29e388..3c4f6d91 100644 --- a/tests/test_boat_ballast.py +++ b/tests/test_boat_ballast.py @@ -9,7 +9,7 @@ import pygame import pytest from src.core import config, uboot_local -from src.enemies.ballast import BoatBallast, flooding_kg +from src.enemies.ballast import BoatBallast from src.ui import layout sys.path.insert(0, str(Path(__file__).parent)) @@ -17,16 +17,16 @@ from test_opfor_sub import _crewed, _feed_texts, _run # noqa: E402 from test_uboot_scope import _key, _local_boat # noqa: E402 -def _pump(ballast, seconds, damage=0.0, dt=0.5): +def _pump(ballast, seconds, flooding=0.0, dt=0.5): for _ in range(int(seconds / dt)): - ballast.update(dt, damage=damage, compressor=False, vent_ordered=False) + ballast.update(dt, flooding_kg=flooding, compressor=False, vent_ordered=False) def test_automatic_trim_takes_up_a_torpedo_and_stops_the_pumps(): ballast = BoatBallast() ballast.torpedo_away() assert ballast.residual_kg(0.0) == -config.UBOOT_TORPEDO_KG and ballast.trim_deg() < 0.0 - ballast.update(0.5, damage=0.0, compressor=False, vent_ordered=False) + ballast.update(0.5, compressor=False, vent_ordered=False) assert ballast.pumping _pump(ballast, 200.0) assert not ballast.pumping @@ -35,13 +35,18 @@ def test_automatic_trim_takes_up_a_torpedo_and_stops_the_pumps(): def test_flooding_beyond_the_regulating_tank_leaves_the_boat_heavy(): - damage = 80.0 + flooding = 20000.0 ballast = BoatBallast() - _pump(ballast, 1000.0, damage=damage) + _pump(ballast, 1000.0, flooding=flooding) assert ballast.regulating_kg == pytest.approx(-config.UBOOT_REGULATING_KG) - assert ballast.residual_kg(damage) == pytest.approx( - flooding_kg(damage) - config.UBOOT_REGULATING_KG) - assert ballast.vertical_drift_mps(damage, 0.0) > 0.0 + assert ballast.residual_kg(flooding) == pytest.approx( + flooding - config.UBOOT_REGULATING_KG) + assert ballast.vertical_drift_mps(flooding, 0.0) > 0.0 + # Without power the pumps stand still. + idle = BoatBallast() + idle.update(10.0, flooding_kg=flooding, compressor=True, vent_ordered=False, power=False) + assert idle.regulating_kg == 0.0 and not idle.pumping + assert idle.hp_air_bar == config.UBOOT_HP_AIR_START_BAR def test_manual_orders_switch_the_automatic_off_and_stay_in_capacity(): @@ -82,7 +87,7 @@ def test_blows_use_air_the_boat_floods_again_and_the_compressor_refills(): sub.depth = sub.target_depth = 120.0 assert sub.command_blow() == "uboot_no_hp_air" and not sub.emergency_ascent before = ballast.hp_air_bar - ballast.update(10.0, damage=0.0, compressor=True, vent_ordered=False) + ballast.update(10.0, compressor=True, vent_ordered=False) assert ballast.hp_air_bar == pytest.approx(before + 10.0 * config.UBOOT_HP_COMPRESSOR_BAR_S) diff --git a/tests/test_boat_damage_control.py b/tests/test_boat_damage_control.py new file mode 100644 index 00000000..ca812fd3 --- /dev/null +++ b/tests/test_boat_damage_control.py @@ -0,0 +1,245 @@ +"""Stage D: the crewed boat's compartments, leaks, fire, gas and teams.""" + +import copy +import json +import sys +from pathlib import Path + +import pygame +import pytest + +from src.core import config, uboot_local +from src.enemies.damage_control import COMPARTMENTS, BoatDamageControl, capacity_kg +from src.ui import layout + +sys.path.insert(0, str(Path(__file__).parent)) +from test_opfor_sub import _crewed, _feed_texts, _run # noqa: E402 +from test_uboot_scope import _key, _local_boat # noqa: E402 + + +def _step(control, seconds, depth=100.0, dt=0.5): + notices = [] + for _ in range(int(seconds / dt)): + notices += control.update(dt, depth_m=depth) + return notices + + +def _index(name): + return COMPARTMENTS.index(name) + + +def test_a_leak_floods_with_depth_and_spills_into_open_neighbours(): + shallow, deep = BoatDamageControl(), BoatDamageControl() + for control in (shallow, deep): + control.compartments[_index("quarters")].leak = 1.0 + _step(shallow, 10.0, depth=25.0) + _step(deep, 10.0, depth=100.0) + assert deep.total_water_kg() == pytest.approx(2.0 * shallow.total_water_kg()) + assert deep.total_water_kg() == pytest.approx(config.UBOOT_DC_LEAK_KG_S * 10.0) + # Past half full the water runs on through open bulkheads, not shut ones. + open_boat, shut_boat = BoatDamageControl(), BoatDamageControl() + for control in (open_boat, shut_boat): + control.compartments[_index("quarters")].water_kg = capacity_kg(_index("quarters")) + shut_boat.set_bulkhead("quarters", True) + _step(open_boat, 20.0, depth=50.0) + _step(shut_boat, 20.0, depth=50.0) + assert open_boat.compartments[_index("control")].water_kg > 0.0 + assert open_boat.compartments[_index("battery")].water_kg > 0.0 + assert shut_boat.compartments[_index("control")].water_kg == 0.0 + assert shut_boat.compartments[_index("battery")].water_kg == 0.0 + # Floodwater forward trims the boat bow down. + bow = BoatDamageControl() + bow.compartments[_index("bow")].water_kg = 4000.0 + assert bow.water_moment_kg() > 0.0 + + +def test_teams_walk_seal_pump_and_fight_fire(): + control = BoatDamageControl() + engine = control.compartments[_index("engine")] + engine.leak, engine.fire = 1.0, 0.5 + assert control.order_team(0, "engine", "seal") is True + assert control.order_team(1, "engine", "fire") is True + # Two compartments from the quarters. + assert control.teams[0]["transit_s"] == 2 * config.UBOOT_DC_TRANSIT_S + notices = _step(control, 2 * config.UBOOT_DC_TRANSIT_S + config.UBOOT_DC_SEAL_S + 1.0) + keys = [key for key, _values in notices] + assert engine.leak == 0.0 and engine.fire == 0.0 + assert "dc_leak_sealed" in keys and "dc_fire_out" in keys + assert control.order_team(0, "engine", "pump") is True + water = engine.water_kg + _step(control, 10.0) + assert engine.water_kg == pytest.approx(max(0.0, water - config.UBOOT_DC_PUMP_KG_S * 10.0)) + assert control.pumping + for bad in ((2, "engine", "seal"), (0, "galley", "seal"), (0, "engine", "dance"), + (True, "engine", "seal")): + assert control.order_team(*bad) == "invalid_value" + assert control.set_bulkhead("engine", 1) == "invalid_value" + + +def test_a_fire_spreads_through_open_bulkheads_and_dies_behind_shut_ones(): + control = BoatDamageControl() + control.compartments[_index("engine")].fire = 1.0 + _step(control, 30.0) + assert control.compartments[_index("battery")].fire > 0.0 + assert control.compartments[_index("stern")].fire > 0.0 + starved = BoatDamageControl() + starved.compartments[_index("engine")].fire = 1.0 + starved.set_bulkhead("engine", True) + _step(starved, config.UBOOT_DC_FIRE_STARVE_S + 1.0) + assert starved.compartments[_index("engine")].fire == 0.0 + assert starved.compartments[_index("battery")].fire == 0.0 + # A compartment half full of water puts its fire out. + wet = BoatDamageControl() + wet.compartments[_index("bow")].fire = 1.0 + wet.compartments[_index("bow")].water_kg = capacity_kg(_index("bow")) * 0.6 + _step(wet, 1.0) + assert wet.compartments[_index("bow")].fire == 0.0 + + +def test_seawater_on_the_battery_makes_gas_and_cuts_the_power(): + control = BoatDamageControl() + battery = control.compartments[_index("battery")] + battery.water_kg = config.UBOOT_DC_POWER_WATER_KG + 100.0 + notices = _step(control, 60.0) + keys = [key for key, _values in notices] + assert not control.power() + assert battery.chlorine > 0.0 and "dc_chlorine" in keys + # Gas halves the teams' work, and without power they pump by hand. + control.order_team(0, "battery", "pump") + control.teams[0]["transit_s"] = 0.0 + before = battery.water_kg + _step(control, 10.0) + rate = config.UBOOT_DC_PUMP_KG_S * config.UBOOT_DC_HAND_PUMP * ( + config.UBOOT_DC_GAS_FACTOR if battery.chlorine >= 0.5 else 1.0) + assert before - battery.water_kg == pytest.approx(rate * 10.0, rel=0.3) + battery.water_kg = config.UBOOT_DC_POWER_WATER_KG + 1.0 + notices = _step(control, 2.0) + assert control.power() and ("dc_power_restored", {}) in notices + + +def test_hits_on_the_crewed_boat_hole_compartments_deterministically(): + first, second = BoatDamageControl(), BoatDamageControl() + for control in (first, second): + control.apply_hit(60.0, 1234) + assert first.serialize() == second.serialize() + holed = [c for c in first.compartments if c.leak > 0.0] + assert len(holed) == 2 and max(c.leak for c in holed) == pytest.approx(0.9) + game, _server, _bridge = _crewed() + sub = game.opfor.sub + sub.hit(40.0) + assert sub.damage_control.any_damage() + ai = next((s for s in game.subs if not s.manual), None) + if ai is not None: + ai.hit(40.0) + assert not ai.damage_control.any_damage() + + +def test_a_flooding_boat_gets_heavy_and_its_stations_go_down(): + game, _server, _bridge = _crewed() + sub = game.opfor.sub + game.world.depth_m = lambda x, y: 2000.0 + sub.depth = sub.target_depth = 80.0 + sub.set_orders(depth=80.0, speed=0.0) + _run(game, 1.0) + control = sub.damage_control + control.compartments[_index("bow")].water_kg = capacity_kg(_index("bow")) - 50.0 + control.compartments[_index("bow")].leak = 1.0 + _run(game, 20.0) + assert sub.ballast.residual_kg(sub.flooding_kg()) > config.UBOOT_HEAVY_WARN_KG + assert sub.ballast.trim_deg(sub.flood_moment_kg()) > 0.0 + assert sub.depth > 80.0 + assert sub.fire_readiness() == "uboot_compartment_down" + control.compartments[_index("control")].fire = 0.9 + sub.depth = 5.0 + assert sub.command_mast(True) == "uboot_compartment_down" + sub.depth = 80.0 + # No power: the motor stops. + control.compartments[_index("battery")].water_kg = config.UBOOT_DC_POWER_WATER_KG - 5.0 + control.compartments[_index("battery")].leak = 0.5 + sub.set_orders(speed=8.0) + _run(game, 5.0) + assert sub.speed_order == 0.0 # the boat only coasts down + texts = " ".join(_feed_texts(game)) + assert "Power lost" in texts and "Bow room" in texts + + +def test_damage_control_round_trips_in_saves_and_malformed_blocks_are_rejected(tmp_path): + game, _server, _bridge = _crewed() + sub = game.opfor.sub + sub.hit(30.0) + sub.command_dc_team(1, "stern", "pump") + sub.command_bulkhead("battery", True) + _run(game, 3.0) + data = game.save_state() + row = next(item for item in data["subs"] if item["id"] == sub.id) + assert row["damage_control"] == json.loads(json.dumps(row["damage_control"])) + path = tmp_path / "slot.json" + path.write_text(json.dumps(data), encoding="utf-8") + assert game.load_game(str(path)) + again = next(item for item in game.subs if item.id == sub.id) + assert again.damage_control.serialize() == row["damage_control"] + before = game.save_state() + for mutate in (lambda b: b.update(version=2), lambda b: b.update(extra=1), + lambda b: b.pop("hits"), lambda b: b["teams"].pop(), + lambda b: b["teams"][0].update(task="nap"), + lambda b: b["teams"][0].update(transit_s=-1.0), + lambda b: b["compartments"].pop("bow"), + lambda b: b["compartments"]["bow"].update(leak=1.5), + lambda b: b["compartments"]["bow"].update(water_kg=float("nan")), + lambda b: b["compartments"]["bow"].update(closed=0)): + broken = copy.deepcopy(data) + target = next(item for item in broken["subs"] if item["id"] == sub.id) + mutate(target["damage_control"]) + assert not game._load_save_data(broken) + assert game.save_state() == before + + +def test_damage_control_over_remote_crew_and_projection(): + from src.commander.projections import _uboot_damage + game, _server, bridge = _crewed() + sub = game.opfor.sub + apply = bridge._apply_opfor_action + assert apply(game, "uboot_dc_team", {"team": 1, "compartment": "bow", "task": "seal"}, + "uboot_engine") is True + assert sub.damage_control.teams[1]["compartment"] == "bow" + assert apply(game, "uboot_bulkhead", {"compartment": "engine", "closed": True}, + "uboot") is True + assert sub.damage_control.compartments[_index("engine")].closed + assert apply(game, "uboot_bulkhead", {"compartment": "engine", "closed": False}, + "uboot_nav") is False + payload = _uboot_damage(sub) + assert [row["name"] for row in payload["compartments"]] == list(COMPARTMENTS) + assert payload["teams"][1]["task"] == "seal" and payload["power"] is True + blob = json.dumps(payload) + for forbidden in ("target_id", "track_id", "kind", "signature", "seed", "rng"): + assert forbidden not in blob + + +def test_uconsole_damage_page_keys_and_draw(): + game, boat = _local_boat() + uboot_local.set_local_station(game, "uboot_engine") + boat.command_page = 3 + control = boat.sub.damage_control + control.compartments[_index("bow")].leak = 0.5 + control.compartments[_index("engine")].fire = 0.4 + control.compartments[_index("battery")].chlorine = 0.3 + control.set_bulkhead("stern", True) + with layout.capture_geometry() as boxes: + game.draw() + titles = {row["title"] for row in boxes} + assert {"uboot.panel.compartments", "uboot.panel.dc_status", + "uboot.panel.dc_teams"} <= titles + _key(game, pygame.K_DOWN) + assert boat.dc_selected == 1 + _key(game, pygame.K_RIGHT) + _key(game, pygame.K_RIGHT) + assert boat.dc_task == "fire" + _key(game, pygame.K_RETURN) + assert control.teams[0]["compartment"] == "control" and control.teams[0]["task"] == "fire" + _key(game, pygame.K_RETURN, pygame.KMOD_SHIFT) + assert control.teams[1]["compartment"] == "control" + _key(game, pygame.K_i) + assert control.compartments[_index("control")].closed + _key(game, pygame.K_i) + assert not control.compartments[_index("control")].closed + game.draw() diff --git a/tests/test_commander_assets.py b/tests/test_commander_assets.py index 167067f8..182b95e0 100644 --- a/tests/test_commander_assets.py +++ b/tests/test_commander_assets.py @@ -558,7 +558,7 @@ def test_commander_catalogs_cover_markup_and_script(): metric_keys -= {"synthetic_range_nm", "sensitivity_db", "cadence_s", "depth_uncertainty_m", "bearing_uncertainty_deg", "range_uncertainty_nm"} dynamic_keys = set(re.findall(r'"((?:aff_|class_|domain_|command_|proposal_|connection_|sound_|phase_|damage_|helo_|reason_)[a-z_]+)"', js)) - dynamic_keys -= {"damage_assign_team", "damage_unassign_team"} + dynamic_keys -= {"damage_assign_team", "damage_unassign_team", "damage_control"} dynamic_keys |= {"connection_syncing", "connection_connected", "connection_stale", "connection_unpaired"} dynamic_keys |= {"connection_lobby", "lobby_pending", "lobby_waiting", "lobby_request_cleared", "station_mutation_failed", "station_request", "station_requested", diff --git a/tests/test_save_v12_hygiene.py b/tests/test_save_v12_hygiene.py index e0a15469..f0d97451 100644 --- a/tests/test_save_v12_hygiene.py +++ b/tests/test_save_v12_hygiene.py @@ -19,11 +19,11 @@ def _game(seed=1201): return Game(seed=seed, start_menu=False, audio_enabled=False) -def test_save_is_v19_and_older_documents_are_rejected(): +def test_save_is_v20_and_older_documents_are_rejected(): game = _game() state = json.loads(json.dumps(game.save_state())) - assert (state["version"], state["save_schema"]) == (19, "u-jagd-save-v19") - assert (SAVE_VERSION, SAVE_SCHEMA) == (19, "u-jagd-save-v19") + assert (state["version"], state["save_schema"]) == (20, "u-jagd-save-v20") + assert (SAVE_VERSION, SAVE_SCHEMA) == (20, "u-jagd-save-v20") assert set(state) == SAVE_ROOT_FIELDS before = game.save_state() legacy = copy.deepcopy(state) @@ -77,7 +77,15 @@ def test_save_is_v19_and_older_documents_are_rejected(): v18["save_schema"] = "u-jagd-save-v18" for row in v18["subs"]: del row["ballast"] + del row["damage_control"] assert not game._load_save_data(v18) + # v19 differs only by the submarines' compartments (damage_control). + v19 = copy.deepcopy(state) + v19["version"] = 19 + v19["save_schema"] = "u-jagd-save-v19" + for row in v19["subs"]: + del row["damage_control"] + assert not game._load_save_data(v19) assert game.save_state() == before diff --git a/tools/gen_web_schema.py b/tools/gen_web_schema.py index 925780b5..fc5e4480 100644 --- a/tools/gen_web_schema.py +++ b/tools/gen_web_schema.py @@ -50,6 +50,11 @@ def render_block() -> str: lines.append(f" air: {_array(schema.UBOOT_AIR_FIELDS)},\n") lines.append(f" ballast: {_array(schema.UBOOT_BALLAST_FIELDS)},\n") lines.append(f" ballastFlags: {_array(schema.UBOOT_BALLAST_FLAGS)},\n") + lines.append(f" damage: {_array(schema.UBOOT_DAMAGE_FIELDS)},\n") + lines.append(f" compartment: {_array(schema.UBOOT_COMPARTMENT_FIELDS)},\n") + lines.append(f" dcTeam: {_array(schema.UBOOT_DC_TEAM_FIELDS)},\n") + lines.append(f" compartments: {_array(schema.UBOOT_COMPARTMENTS)},\n") + lines.append(f" dcTasks: {_array(schema.UBOOT_DC_TASKS)},\n") lines.append(f" esm: {_array(schema.UBOOT_ESM_FIELDS)},\n") lines.append(f" esmEmitter: {_array(schema.UBOOT_ESM_EMITTER_FIELDS)},\n") lines.append(f" esmHistory: {_array(schema.UBOOT_ESM_HISTORY_FIELDS)},\n")