Phase 10: damage, stability and repair physics

Compartments get volume, centroid, floor height, fuel and electrical load.
Flooding follows the orifice law against the outside waterline (dynamic
draft plus heel), so it slows as levels equalize and high rooms stay dry.
Floodwater mass, free-surface GM loss and transverse moment give draft and
list; the ship sinks beyond reserve buoyancy and capsizes when GM is lost
or the heel passes 35 degrees (replaces the 540-point rule).

Torpedo impact point selects the compartment and the hole area scales with
warhead stand-off; missiles hit above the waterline and mainly start fires.
Fire grows with fuel load and oxygen, is smothered by flooding, spreads
through hot bulkheads, starts from shorted switchboards and can cook off
the magazine. Repair teams walk the compartment graph (20 s per hop) and
patch holes with a limited stock of 8 kits before pumping. Station
capability degrades continuously (sonar/radar range). Hostile hulls flood
progressively and lose radar/missile launch with damage.

Save v12 carries team positions/ETAs, patch kits, holes, heat timers,
shorts, cook-off and capsize state with strict validation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 19:02:56 +02:00
1 parent f75d177e48
commit 9d8e15c8c7
16 files changed
+672 -151

No files matched your search

+2 -2
View File
@@ -1927,8 +1927,8 @@
"help.note.weapon_tactic": "Tiefe erst aus Ping, dann Schuss. Dekoys: Signatur-Nachbau \u2013 Kontakt verliert dann Eigenfrequenzen.",
"help.note.damage_states": "ZUST\u00c4NDE: OK -> BESCHAEDIGT/FLUTEND -> ZERSTOERT.",
"help.note.destroyed": "ZERSTOERT = Station unwiederbringlich verloren.",
"help.note.sinking": "Ab 60 % mittlerer Flutung \u00fcber alle R\u00e4ume sinkt die Fregatte.",
"help.note.fire": "Feuer: breitet sich aus; L\u00f6schteams reduzieren es.",
"help.note.sinking": "Die Fregatte sinkt, wenn das Flutwasser die Reserveverdr\u00e4ngung \u00fcbersteigt, und kentert, wenn freie Wasseroberfl\u00e4chen die Stabilit\u00e4t aufzehren.",
"help.note.fire": "Feuer w\u00e4chst mit der Brandlast, greift \u00fcber hei\u00dfe Schotten \u00fcber und erstickt bei Flutung; Trupps l\u00f6schen erst nach ihrer Ankunft.",
"help.note.assignment": "Zuweisung nur zu reparierbaren Schaeden; belegte Kompartimente verdr\u00e4ngen kein anderes Team.",
"help.note.damage_tactic": "Priorit\u00e4t: Maschinerie & Sonarzentrale, dann Rumpf. Feuer sofort besetzen.",
"help.note.radar": "Radar sieht Oberflaechenfahrzeuge, Luftfahrzeuge und ASMs; getauchte U-Boote bleiben unsichtbar.",
+2 -2
View File
@@ -1927,8 +1927,8 @@
"help.note.weapon_tactic": "Obtain depth by ping, then fire. Decoys imitate signatures and may make a contact lose its own frequencies.",
"help.note.damage_states": "STATES: OK -> DAMAGED/FLOODING -> DESTROYED.",
"help.note.destroyed": "DESTROYED means the station is permanently lost.",
"help.note.sinking": "The frigate sinks at 60% average flooding across all compartments.",
"help.note.fire": "Fire spreads; firefighting teams reduce it.",
"help.note.sinking": "The frigate sinks when floodwater exceeds its reserve buoyancy and capsizes when free-surface water destroys its stability.",
"help.note.fire": "Fire grows with fuel load, spreads through hot bulkheads and is smothered by flooding; teams fight it once they arrive.",
"help.note.assignment": "Teams can be assigned only to repairable damage; an occupied compartment does not displace another team.",
"help.note.damage_tactic": "Prioritize machinery and sonar, then the hull. Assign a team to fire immediately.",
"help.note.radar": "Radar sees surface vessels, aircraft, and ASMs; submerged submarines remain invisible.",
+12 -10
View File
@@ -18,14 +18,16 @@ Seite 1 ist der Schiffsplan; Seite 2 zeigt Details je Abteilung (Flutung, Brand,
Zustand: OK -> BESCHÄDIGT / FLUTEND -> ZERSTÖRT Trupps: 1 2 3
```
- **FLUTEND:** das Wasser steigt (0,10 % je Sekunde), bis ein Trupp lenzt. Bei 70 % ist die Abteilung ZERSTÖRT.
- **BESCHÄDIGT:** stabilisierte Restleckage (0,025 % je Sekunde); braucht weiterhin einen Trupp bis OK.
- **Brand:** ein Treffer entfacht mit 35 % Wahrscheinlichkeit ein Feuer. Es wächst von selbst und kann auf Nachbarräume übergreifen; bei 100 % ist die Abteilung zerstört.
- **Gesamtflutung:** das Schiff sinkt bei 540 Punkten, also 60 % mittlerer Flutung über alle neun Abteilungen.
- **Krängung:** ungleiche Flutung zwischen Backbord- und Steuerbordrumpf lässt das Schiff krängen (bis 15 Grad) und zieht es zu einer Seite.
- **FLUTEND:** durch ein Leck unter der Wasserlinie dringt Wasser ein. Der Zufluss folgt dem Wasserdruck: anfangs schnell, dann langsamer, je näher der Wasserstand innen der Wasserlinie außen kommt. Hoch liegende Räume (Brücke) fluten durch ein Leck nicht. Bei 70 % ist die Abteilung ZERSTÖRT.
- **BESCHÄDIGT:** das Leck ist abgedichtet; eine kleine Restleckage bleibt, bis ein Trupp den Raum lenzt.
- **Leckabdichtsätze:** jedes Abdichten verbraucht einen von 8 Sätzen. Ohne Sätze kann ein Trupp nur gegen das offene Leck lenzen.
- **Trefferort:** der Einschlagpunkt des Torpedos bestimmt die Abteilung; eine nahe Detonation reißt ein größeres Leck als eine entfernte. Flugkörper treffen über der Wasserlinie und verursachen vor allem Brände.
- **Brand:** wächst mit der Brandlast des Raums (Maschine, Flugdeck und Magazin brennen am stärksten) und wird von steigendem Wasser erstickt. Ein Raum, der etwa 30 s heiß bleibt, entzündet seine Nachbarn. Eine geflutete Schalttafel (Sonar, OPZ, Funk, Maschine) schließt kurz und löst einen Elektrobrand aus. Ein Brand über 90 % in der Waffenzentrale bringt das Magazin zur Explosion: der Raum ist zerstört, die Nachbarräume sind leckgeschlagen.
- **Stabilität:** Flutwasser macht das Schiff schwerer, und freie Wasseroberflächen verringern die metazentrische Höhe (GM). Das Schiff sinkt, wenn das Flutwasser die Reserveverdrängung übersteigt, und kentert, wenn GM verloren geht oder die Krängung 35 Grad überschreitet.
- **Krängung:** außermittiges Flutwasser lässt das Schiff zu dieser Seite krängen und zieht es vom Kurs.
- **Rudermaschine und Stabilisatoren:** die Rudermaschine liegt achtern unter dem Flugdeck. Ist dieser Raum zerstört, klemmt das Ruder in der letzten Lage, bis der Raum repariert ist. Ein zerstörter Rumpfraum auf einer Seite legt die Flossenstabilisatoren lahm, das Schiff rollt dann im Seegang stärker. Flutwasser macht das Schiff schwerer: es liegt tiefer und beschleunigt langsamer.
Auswirkungen auf Stationen: eine beschädigte Sonarzentrale halbiert die Sonarreichweite; eine beschädigte Maschine begrenzt die Fahrt auf 15 kn, eine zerstörte auf 8 kn; eine beschädigte oder zerstörte Waffenzentrale sperrt Torpedostarts; ein zerstörtes Flugdeck verhindert Start und Landung des Helikopters; eine zerstörte OPZ legt auch ESM lahm.
Auswirkungen auf Stationen: eine Station verliert mit Flutung und Brand in ihrem Raum stufenlos an Leistung (Sonar- und Radarreichweite sinken allmählich); ein zerstörter Raum legt sie lahm. Eine beschädigte Maschine begrenzt die Fahrt auf 15 kn, eine zerstörte auf 8 kn; eine beschädigte oder zerstörte Waffenzentrale sperrt Torpedostarts; ein zerstörtes Flugdeck verhindert Start und Landung des Helikopters; eine zerstörte OPZ legt auch ESM lahm.
## Tasten {#damage-keys}
@@ -39,12 +41,12 @@ Auf der uConsole weisen die Joystick-Tasten 1-3 Trupp 1-3 direkt der gewählten
## Tipps für Profis {#damage-tips}
- Ein Trupp lenzt 0,12 % je Sekunde, mehr als eine flutende Abteilung zunimmt. Zwei Trupps in einem Raum halbieren die Zeit.
- Unter 35 % Flutung wechselt ein Raum von FLUTEND auf BESCHÄDIGT; das ist der Moment, einen Trupp zum nächsten Notfall zu schicken.
- Trupps können keiner zerstörten Abteilung zugewiesen werden. Nicht dort verschwenden.
- Trupps starten in der OPZ und brauchen je Abteilung etwa 20 s Weg; wirksam sind sie erst nach der Ankunft. Einen Trupp nahe Maschine und Waffenzentrale halten.
- Ein Trupp dichtet zuerst das Leck ab, dann lenzt er. Leckabdichtsätze sind begrenzt: für Räume unter der Wasserlinie verwenden, nicht für Räume, die schon nicht mehr fluten.
- Zwei Trupps in einem Raum halbieren die Zeit. Trupps können keiner zerstörten Abteilung zugewiesen werden.
- Brand neben Maschine oder Waffenzentrale ist am gefährlichsten: er greift auf einsatzkritische Räume über.
## Nicht modelliert {#damage-limits}
- Keine einzelnen Besatzungsmitglieder, Verwundeten oder Munitionsexplosionen.
- Keine einzelnen Besatzungsmitglieder oder Verwundeten; keine Längstrimmung durch Flutung.
- Kein Gegenfluten; Krängung mit Reparatur und Ruder ausgleichen.
+12 -10
View File
@@ -18,14 +18,16 @@ Page 1 is the ship schematic; page 2 lists details per compartment (flooding, fi
state: OK -> DAMAGED / FLOODING -> DESTROYED teams: 1 2 3
```
- **FLOODING:** water rises (0.10 % per second) until a team pumps it down. At 70 % the compartment is DESTROYED.
- **DAMAGED:** stabilised residual leak (0.025 % per second); still needs a team to reach OK.
- **Fire:** a hit starts a fire with 35 % chance. Fire grows by itself and can spread to neighbouring rooms; at 100 % the compartment is destroyed.
- **Total flooding:** the ship sinks at 540 points, which is 60 % average flooding over all nine compartments.
- **Heel:** uneven flooding between port and starboard hull lists the ship (up to 15 degrees) and pulls it to one side.
- **FLOODING:** a hole below the waterline lets water in. The inflow follows the water pressure: fast at first, slower as the water inside rises towards the outside waterline. Rooms high in the ship (bridge) do not flood through a hole. At 70 % the compartment is DESTROYED.
- **DAMAGED:** the hole is patched; a small residual leak remains until a team pumps the room dry.
- **Patch kits:** plugging a hole uses one of 8 patch kits. Without kits a team can only pump against the open hole.
- **Hit location:** the torpedo's impact point decides the compartment; a close burst tears a bigger hole than a distant one. Missiles hit above the waterline and mostly start fires.
- **Fire:** grows with the room's fuel load (engine, flight deck and magazine burn fiercest) and is smothered by rising water. A room that stays hot for about 30 s ignites its neighbours. A flooded switchboard (sonar, operations, radio, engine) shorts and starts an electrical fire. A fire above 90 % in the weapons room cooks off the magazine: the room is destroyed and the neighbouring rooms are holed.
- **Stability:** floodwater adds weight, and loose water surfaces reduce the metacentric height (GM). The ship sinks when the floodwater exceeds its reserve buoyancy, and capsizes when GM is lost or the heel passes 35 degrees.
- **Heel:** off-centre floodwater lists the ship to that side and pulls it off course.
- **Steering gear and stabilizers:** the steering gear sits aft under the flight deck. If that compartment is destroyed, the rudder jams at its last angle until the room is repaired. A destroyed hull compartment on either side knocks out the fin stabilizers, so the ship rolls more in a seaway. Floodwater adds weight: the ship sits deeper and accelerates more slowly.
Station effects: a damaged sonar room halves sonar range; a damaged engine room caps speed at 15 kn, a destroyed one at 8 kn; a damaged or destroyed weapons room blocks torpedo launches; a destroyed flight deck prevents helicopter launch and recovery; a destroyed operations room also disables ESM.
Station effects: a station loses capability continuously with flooding and fire in its room (sonar and radar range shrink gradually); a destroyed room disables it. A damaged engine room caps speed at 15 kn, a destroyed one at 8 kn; a damaged or destroyed weapons room blocks torpedo launches; a destroyed flight deck prevents helicopter launch and recovery; a destroyed operations room also disables ESM.
## Keys {#damage-keys}
@@ -39,12 +41,12 @@ On the uConsole the joystick buttons 1-3 assign team 1-3 directly to the selecte
## Pro tips {#damage-tips}
- One team pumps 0.12 % per second, more than a flooding room gains. Two teams on one room halve the time.
- A room below 35 % flooding changes from FLOODING to DAMAGED; that is the moment to move a team to the next emergency.
- Teams cannot be assigned to a destroyed compartment. Do not waste them there.
- Teams start in the operations room and need about 20 s per compartment to walk to their job; a team is only effective once it has arrived. Keep a team near the engine and weapons rooms.
- A team first patches the hole, then pumps. Patch kits are limited: spend them on rooms below the waterline, not on rooms that already stopped flooding.
- Two teams on one room halve the time. Teams cannot be assigned to a destroyed compartment.
- Fire in a room next to the engine or the weapons room is the most dangerous: it spreads into mission-critical spaces.
## Not modelled {#damage-limits}
- No individual crew members, casualties or ammunition cook-off.
- No individual crew members or casualties; no longitudinal trim from flooding.
- No counter-flooding order; correct heel with repairs and rudder.
+1 -1
View File
@@ -50,7 +50,7 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| Modus LEISE | Lärm x0,65, max. 12 kn |
| TAS-Handhabung | 3-12 kn, ausbringen 360 s, einholen 480 s, Defekt über 20 kn |
| TAS-Tiefe | 20-260 m, minus 4 m je Knoten |
| Schaden | 9 Abteilungen, 3 Trupps; sinkt bei 60 % mittlerer Flutung |
| Schaden | 9 Abteilungen, 3 Trupps (etwa 20 s Weg je Abteilung), 8 Leckabdichtsätze; sinkt jenseits der Reserveverdrängung, kentert bei 35 Grad Krängung oder verlorenem GM |
## Umwelt {#ref-environment}
+1 -1
View File
@@ -50,7 +50,7 @@ All values are the defaults of the current game version. Custom difficulty and m
| QUIET mode | noise x0.65, max 12 kn |
| TAS handling | 3-12 kn, stream 360 s, recover 480 s, fault above 20 kn |
| TAS depth | 20-260 m, minus 4 m per knot |
| Damage | 9 compartments, 3 teams; sinks at 60 % mean flooding |
| Damage | 9 compartments, 3 teams (about 20 s walk per compartment), 8 patch kits; sinks beyond reserve buoyancy, capsizes at 35 degrees heel or lost GM |
## Environment {#ref-environment}
+15 -16
View File
@@ -88,7 +88,7 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| ~~**No active sonar use by subs**~~ | **Closed.** `Sub._maybe_active_ping` (aggressive boats, fresh contact, cooldown saved since Phase 0); the ping is heard by the frigate. | — |
| ~~**No ESM/ESB use by subs**~~ | **Closed (Phase 7).** All submarines use their `PlatformSensorSuite` (legacy snapshot gate removed); ESM works only with the mast up (<= 18 m); range from their own passive TMA with TMA legs (saved track). | — |
| ~~**No ASW coordination**~~ | **Closed (Phase 7).** Hostile red-group datalink shares tracks; a submerged boat only exchanges at mast depth or while snorkelling/transmitting, which makes the latency physical. | — |
| **Damage model is scalar** | `self.damage: float` 0-100; affects speed (`speed_for_state`), noise, and sinking | Compartment flooding on subs; loss of specific systems; trim change; rudder damage |
| ~~**Damage model is scalar**~~ | **Closed (Phases 6/10).** Shock-factor hits, progressive flooding while holed, emergency blow, fatigue; damage throttles speed and raises noise. Subs keep a lumped damage value by design (no player-visible compartments). | — |
### 2.3 Data structures / interfaces that would be touched
@@ -123,7 +123,7 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| ~~**No ship hydrodynamics**~~ | **Closed (Phase 6).** Speed lag from the catalog, Nomoto-linear turning, and added resistance in waves lowering attainable speed by hull length (small hulls lose more). | — |
| ~~**No radar horizon**~~ | **Fixed (2026-09).** Surface detection now uses `min(effective_range × aspect, radar_horizon_nm(RADAR_ANTENNA_HEIGHT_M, RADAR_SURFACE_TARGET_HEIGHT_M))` for both civilians and warships (`game.py`, `_update_air_picture`), the same formula already used for raiders. | — |
| ~~**No countermeasures**~~ | **Closed (Phase 9 / Phase 12).** Hostile combatants stream acoustic decoys (saved store of 2) when they hear a torpedo launch; missile defence (ship chaff/CIWS) is modelled on the own ship in Phase 12. | — |
| **No damage propagation** | Single scalar `damage`; one torpedo = 34 damage → 3 hits to sink | Compartment flooding, fire, loss of specific capabilities |
| ~~**No damage propagation**~~ | **Closed (Phases 8/10).** Shock-factor damage (near misses no longer sink), progressive flooding above 30 %, radar lost above 60 % and missile launch above 75 % damage. | — |
| ~~**No evasive manoeuvres**~~ | **Closed.** Combatants turn away at flank speed on a heard launch (W2, state saved in Phase 0) and stream decoys (Phase 9). | — |
| **No weapon systems modelling** | ASM/ASROC are simple projectiles; no fire-control solution error | Guidance accuracy, warhead proximity fuze, multi-target saturation |
@@ -328,26 +328,25 @@ All closed in Phase 9:
### 9.1 What is currently modeled
- 9 compartments: bridge, sonar, weapons, OPZ, radio, engine, flightdeck, hull L/R
- Torpedo hit: 1–2 compartments randomly selected (weighted by hit zone); 10-30% initial flood; 35% chance of fire start
- Flooding: 0.10%/s (flooded) or 0.025%/s (damaged); repair 0.12%/s per team
- Fire: 0.08%/s growth; 0.14%/s per team extinguish; 0.02%/s spread to adjacent; 35% start chance on hit; kill at 100%
- Compartment destroyed at 70% flood or 100% fire
- Ship sinks at 540% total flood (60% avg over 9 compartments)
- 9 compartments with volume, centroid, floor height, fuel load and electrical load
- Torpedo hit: impact point → compartment, hole area from warhead stand-off; ASM hit: above-waterline fire
- Flooding: orifice law against the outside waterline; teams patch (8 kits) then pump
- Stability: displacement, free-surface GM, heel; sinking beyond reserve buoyancy, capsize at lost GM / 35° heel
- Fire: fuel × oxygen growth, smothering, heat-timer spread, electrical shorts, magazine cook-off
- Continuous station capability; teams with walking time (20 s per compartment)
- Grounding: impact energy → localized flooding (deterministic, no RNG)
- 3 repair teams; cycle or assign
### 9.2 Gaps and simplifications
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No hit-location physics** | Torpedo zone (bow/stern/port/starboard/center) from approach bearing; random within zone | Torpedo impact point on hull → specific compartment; warhead burst → localised damage |
| **No flooding dynamics** | Compartment flood % changes linearly; no free-flood, no list, no change in centre of gravity | Compartment interconnection; free-flood moment of inertia; list → affects sonar, radar, helicopter ops |
| **No fire propagation physics** | Fire spreads to adjacent with fixed probability per second | Compartment fire based on material, fuel type; water ingress suppresses fire; electrical fire |
| **No systems degradation** | Station is binary: OK → DEGRADED → DOWN | Gradual performance loss: sonar sensitivity ↓, radar range ↓, engine power ↓, comm range ↓ |
| **No damage repair realism** | Repair rate is constant; no consumables, no time-to-repair estimate | Repair teams need time to travel; materials limited; some damage irreparable |
| **No secondary damage** | Only flooding + fire | Structural failure, magazine detonation, electrical short-circuit cascade |
| **Torpedo damage to subs** | `Sub.hit()`: +60-100% damage; at 100% → SINKING (20 s) | Compartment damage on sub; loss of specific systems; emergency blow; controlled sink |
| ~~**No hit-location physics**~~ | **Closed (Phase 10).** The torpedo's impact point on the hull (`_hull_impact`) selects the compartment; hole area scales with the warhead stand-off (20 m / distance, 0.5-3x); ASM hits above the waterline and mainly starts fires. | — |
| ~~**No flooding dynamics**~~ | **Closed (Phase 10).** Orifice inflow Q = Cd A sqrt(2 g h) against the outside waterline (dynamic draft + heel), so flooding slows as levels equalize and high rooms stay dry; floodwater mass, free-surface GM loss and transverse moment give draft and list; the ship sinks beyond reserve buoyancy and capsizes at lost GM or 35 deg heel. | — |
| ~~**No fire propagation physics**~~ | **Closed (Phase 10).** Growth from compartment fuel load x oxygen, smothered by flooding and cooled by water; deterministic spread after a bulkhead has stayed hot (heat timer, saved); flooded switchboards short and start electrical fires. | — |
| ~~**No systems degradation**~~ | **Closed (Phase 10).** Continuous `capability()` per compartment from flooding and fire scales sonar and radar range; destroyed rooms still disable their station. | — |
| ~~**No damage repair realism**~~ | **Closed (Phase 10).** Teams walk the compartment graph (20 s per hop, ETA saved) and act only on arrival; holes must be patched first with one of 8 patch kits, leaving a small leak. | — |
| ~~**No secondary damage**~~ | **Closed (Phase 10).** Magazine cook-off above 90 % fire destroys the weapons room and holes its neighbours; electrical short-circuit fires; capsize as structural stability failure. | — |
| ~~**Torpedo damage to subs**~~ | **Closed (Phases 6/8/10).** Shock-factor damage, one emergency blow, hull fatigue, and progressive flooding of a holed boat (30-100 % damage) that ends in sinking unless it surfaces. | — |
---
+76 -9
View File
@@ -40,6 +40,7 @@ from src.sonar import equation as sonar_equation
from src.sonar import propagation as sonar_propagation
from src.physics import torpedo_dyn
from src.physics import ship_dynamics
from src.ship import damage as damage_physics
from src.sensors.platform import MAST_DEPTH_M
from src.world.ocean import OceanEnvironment
from src.core.save_schema import (
@@ -3219,8 +3220,12 @@ class Game:
else config.RADAR_SURFACE_RANGE_NM)
rain_loss = (config.RADAR_RAIN_AIR_LOSS if domain == "air"
else config.RADAR_RAIN_SURFACE_LOSS)
# Damage to the operations room (radar consoles, power) degrades the
# radar continuously rather than only at destruction.
capability = (1.0 if not self.damage.station_degraded("opz")
else 0.5 + 0.5 * self.damage.capability("opz"))
return (nominal * (1.0 - loss * self.radar_weather_severity())
* (1.0 - rain_loss * self.radar_rain_severity()))
* (1.0 - rain_loss * self.radar_rain_severity()) * capability)
def radar_sweep_bearing(self) -> float:
"""Nautische Peilung: zunehmende Werte drehen Nord -> Ost rechtsherum."""
@@ -5630,8 +5635,11 @@ class Game:
# --- Update ---
def _sonar_range_factor(self) -> float:
"""Continuous sonar-room capability: an undamaged room keeps full
range, a degraded one falls to DMG_SONAR_DEGRADED_FACTOR and below."""
if self.damage.station_degraded("sonar"):
return config.DMG_SONAR_DEGRADED_FACTOR
return config.DMG_SONAR_DEGRADED_FACTOR * (
0.5 + 0.5 * self.damage.capability("sonar"))
return 1.0
def _sonar_targets(self) -> list:
@@ -5813,7 +5821,8 @@ class Game:
self.ship.steering_jammed = self.damage.station_down("flightdeck")
self.ship.stabilizers_ok = not (self.damage.station_down("hull_left")
or self.damage.station_down("hull_right"))
self.ship.flood_percent = self.damage.total
self.ship.flood_percent = (self.damage.flood_mass_kg()
/ ship_dynamics.HULL.flood_kg_per_percent)
self.ship.update_fuel(dt)
self.world.update(dt)
contact = self.ship.update(dt, self.world, self.damage.list_deg())
@@ -6030,7 +6039,7 @@ class Game:
asm.update(dt, self.ship, self.world,
ecm_effect=self._ecm_effect_against_asm(asm))
if asm.state == "TREFFER":
hit = self.damage.torpedo_hit()
hit = self.damage.missile_hit(*self._hull_impact(asm.x, asm.y))
self._emit_sound("explosion")
self.announce(message("runtime.hit.asm", compartments=", ".join(
self.damage.compartments[k].name for k in hit)),
@@ -6115,7 +6124,12 @@ class Game:
seeker_candidates=self.nixies)
for torpedo in self.enemy_torpedoes:
if torpedo.state == "HIT":
hit = self.damage.torpedo_hit(self._incoming_hit_zone(torpedo))
distance_m = max(1.0, math.hypot(torpedo.x - self.ship.x,
torpedo.y - self.ship.y) * 1852.0)
# Shock factor sets the hole size relative to a 20 m burst.
hit = self.damage.torpedo_hit(
impact=self._hull_impact(torpedo.x, torpedo.y),
hole_scale=config.clamp(20.0 / distance_m, 0.5, 3.0))
self._emit_sound("explosion")
text = ", ".join(self.damage.compartments[k].name for k in hit)
self.flash(message("runtime.hit.torpedo", compartments=text), 5.0)
@@ -6161,6 +6175,21 @@ class Game:
# A launch decision consumes this substep before flight begins.
self._drain_asrocs()
def _hull_impact(self, x_nm: float, y_nm: float) -> tuple[float, float]:
"""Impact point in hull coordinates (bow/starboard positive, -1..1)."""
dx, dy = (x_nm - self.ship.x) * 1852.0, (y_nm - self.ship.y) * 1852.0
heading = math.radians(self.ship.course)
forward = dx * math.sin(heading) - dy * math.cos(heading)
starboard = dx * math.cos(heading) + dy * math.sin(heading)
half_length = self.ship.hull_spec.length_m / 2.0
half_beam = self.ship.hull_spec.beam_m / 2.0
if math.hypot(forward, starboard) < 1e-6:
return 0.0, 0.0
# Project onto the hull outline along the approach direction.
scale = max(abs(forward) / half_length, abs(starboard) / half_beam, 1.0)
return (config.clamp(forward / scale / half_length, -1.0, 1.0),
config.clamp(starboard / scale / half_beam, -1.0, 1.0))
def _incoming_hit_zone(self, torpedo) -> str:
"""Naehert die getroffene Schiffszone aus der Angriffsrichtung an."""
source_bearing = (torpedo.course + 180.0) % 360.0
@@ -6442,7 +6471,7 @@ class Game:
def _update_damage_and_mission(self, dt: float) -> None:
"""Fortschritt von Schaden, Flugverkehr und Missionszielen."""
self.damage.update(dt)
self.damage.update(dt, draft_m=self.ship.dynamic_draft_m())
self.flights.update(dt, world=self.world,
near=(self.ship.x, self.ship.y))
self._check_mission_end()
@@ -6687,9 +6716,18 @@ class Game:
difficulty=dict(self.difficulty)),
"damage": dict(
repair_mult=self.damage.repair_mult,
compartments={k: dict(state=c.state, flood=c.flood, fire=c.fire)
compartments={k: dict(state=c.state, flood=c.flood, fire=c.fire,
hole_m2=c.hole_m2, heat_s=c.heat_s,
shorted=c.shorted)
for k, c in self.damage.compartments.items()},
teams={str(k): v for k, v in self.damage.teams.items()}),
teams={str(k): v for k, v in self.damage.teams.items()},
team_position={str(k): v for k, v
in self.damage.team_position.items()},
team_eta={str(k): v for k, v in self.damage.team_eta.items()},
patch_kits=self.damage.patch_kits,
cooked_off=self.damage.cooked_off,
capsized=self.damage.capsized,
draft_m=self.damage.draft_m),
"world": dict(hour=self.world.hour,
sea_state=self.world.sea_state,
weather_shift_timer=self.world.weather_shift_timer,
@@ -7266,9 +7304,20 @@ class Game:
self.damage.compartments[k].state = c["state"]
self.damage.compartments[k].flood = c["flood"]
self.damage.compartments[k].fire = c["fire"]
self.damage.compartments[k].hole_m2 = c["hole_m2"]
self.damage.compartments[k].heat_s = c["heat_s"]
self.damage.compartments[k].shorted = c["shorted"]
self.damage.teams.update({int(k): v for k, v in dmg["teams"].items()})
self.damage.team_position.update(
{int(k): v for k, v in dmg["team_position"].items()})
self.damage.team_eta.update({int(k): v for k, v in dmg["team_eta"].items()})
self.damage.patch_kits = dmg["patch_kits"]
self.damage.cooked_off = dmg["cooked_off"]
self.damage.capsized = dmg["capsized"]
self.damage.draft_m = dmg["draft_m"]
self.damage.total = sum(c.flood for c in self.damage.compartments.values())
self.damage.ship_sunk = self.damage.total >= config.DMG_SHIP_SINK_TOTAL
self.damage.ship_sunk = (self.damage.capsized or self.damage.flood_mass_kg()
>= damage_physics.RESERVE_BUOYANCY_KG)
# M10–M16
self.sonar_mode = data["sonar_mode"]
self.sonar_harmonic_hz = None
@@ -8282,6 +8331,21 @@ class Game:
return False
if not bounded(damage["repair_mult"], 0.1, 10.0):
return False
team_keys = {str(i) for i in range(1, DamageModel.TEAM_COUNT + 1)}
if (not isinstance(damage["team_position"], dict)
or set(damage["team_position"]) != team_keys
or any(room not in compartment_keys
for room in damage["team_position"].values())
or not isinstance(damage["team_eta"], dict)
or set(damage["team_eta"]) != team_keys
or any(not bounded(value, 0.0, 3600.0)
for value in damage["team_eta"].values())
or type(damage["patch_kits"]) is not int
or not 0 <= damage["patch_kits"] <= damage_physics.PATCH_KITS
or type(damage["cooked_off"]) is not bool
or type(damage["capsized"]) is not bool
or not bounded(damage["draft_m"], 1.0, 20.0)):
return False
if (set(teams) != {str(i) for i in range(1, DamageModel.TEAM_COUNT + 1)}
or any(room is not None and (not isinstance(room, str)
or room not in compartment_keys)
@@ -8293,6 +8357,9 @@ class Game:
or not bounded(room["flood"], 0, config.DMG_DESTROY_FLOOD)
# A lethal fire may overshoot the kill threshold by one step.
or not bounded(room["fire"], 0, config.DMG_FIRE_KILL + 5.0)
or not bounded(room["hole_m2"], 0.0, 10.0)
or not bounded(room["heat_s"], 0.0, 1e6)
or type(room["shorted"]) is not bool
for room in compartments.values()):
return False
+5 -2
View File
@@ -41,6 +41,9 @@ WORLD_FIELDS = frozenset({
"ocean",
})
DAMAGE_FIELDS = frozenset({"repair_mult", "compartments", "teams"})
COMPARTMENT_FIELDS = frozenset({"state", "flood", "fire"})
DAMAGE_FIELDS = frozenset({"repair_mult", "compartments", "teams",
"team_position", "team_eta", "patch_kits",
"cooked_off", "capsized", "draft_m"})
COMPARTMENT_FIELDS = frozenset({"state", "flood", "fire", "hole_m2", "heat_s",
"shorted"})
COMPARTMENT_STATES = ("OK", "FLUTEND", "BESCHAEDIGT", "ZERSTOERT")
+4
View File
@@ -556,6 +556,10 @@ 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.
self.damage = min(100.0, self.damage + 0.01 * dt
* (self.damage - 30.0) / 70.0)
self._update_hull_stress(dt)
if self.state == "SINKING":
return
+22 -2
View File
@@ -9,6 +9,13 @@ import random
from src.core import config
from src.physics import submarine as sub_physics
# Hostile-hull damage effects (percent): radar and missile systems are lost,
# and progressive flooding runs above the threshold.
NPC_RADAR_LOST_DAMAGE = 60.0
NPC_WEAPONS_LOST_DAMAGE = 75.0
NPC_FLOOD_THRESHOLD = 30.0
NPC_FLOOD_RATE = 0.01 # %/s at full damage
from src.data import catalog
from src.data import fingerprint as fingerprint_mod
from src.sensors.platform import (
@@ -136,7 +143,8 @@ class SurfaceShip:
@property
def radar_emitting(self) -> bool:
return not self.sunk and self.emitter
return (not self.sunk and self.emitter
and self.damage < NPC_RADAR_LOST_DAMAGE)
@property
def ais_transmitting(self) -> bool:
@@ -152,6 +160,14 @@ class SurfaceShip:
if self.damage >= 100.0:
self.sunk = True
def _progressive_flooding(self, dt: float) -> None:
"""A holed hull keeps taking water in proportion to its damage."""
if NPC_FLOOD_THRESHOLD < self.damage < 100.0:
self.damage = min(100.0, self.damage + NPC_FLOOD_RATE * dt * (
self.damage - NPC_FLOOD_THRESHOLD) / (100.0 - NPC_FLOOD_THRESHOLD))
if self.damage >= 100.0:
self.sunk = True
def alert_torpedo(self, bearing_deg: float) -> None:
"""W2: Torpedostart gehört -> Wende weg von der Bedrohung, Flankfahrt."""
if self.sunk:
@@ -162,6 +178,9 @@ class SurfaceShip:
# --- Bewegung ---
def update(self, dt: float, observation, world, asw_observation=None) -> None:
if self.sunk:
return
self._progressive_flooding(dt)
if self.sunk:
return
if self.doctrine == "surface_combatant":
@@ -343,7 +362,8 @@ class SurfaceShip:
self.y = config.clamp(self.y, 0.0, world_size)
def _maybe_asm(self, dt: float) -> None:
if self.side != "hostile" or self.profile.asm_salvo[0] <= 0:
if (self.side != "hostile" or self.profile.asm_salvo[0] <= 0
or self.damage >= NPC_WEAPONS_LOST_DAMAGE):
return
self.attack_left -= dt
if self.attack_left > 0.0:
+332 -79
View File
@@ -1,7 +1,31 @@
"""Schadensmodell: Stationsräume, Flutung, Feuer und Reparaturteams."""
"""Schadensmodell: Abteilungen mit Wassereinbruch, Stabilität, Brand und
Reparaturtrupps.
Physics (phase 10):
* Each compartment has a volume, permeability, centroid and height. A hole
(area in m^2) below the waterline floods it with the orifice law
Q = Cd A sqrt(2 g h), where h is the head between the outside waterline
(dynamic draft plus heel on that side) and the water already inside, so
flooding slows and stops as the levels equalize. Teams first patch holes
(consuming a patch kit), then pump.
* Floodwater adds displacement; free surfaces reduce GM; the transverse
moment of off-centre water gives the heel (list). The ship sinks when the
floodwater exceeds its reserve buoyancy and capsizes when GM is lost or the
heel passes the downflooding angle.
* Fire intensity grows with the compartment's fuel load and oxygen, is
smothered by flooding, spreads deterministically through hot bulkheads,
can start from flooded switchboards and can cook off the magazine.
* Teams walk the compartment graph (transit time per hop).
* Station capability degrades continuously with flooding and fire.
The legacy percentages (flood 0..70 = destroyed, fire 0..100) and state
names remain the public interface for the UI and saves.
"""
import math
import random
from collections import deque
from src.core import config
@@ -29,6 +53,71 @@ COMPARTMENT_ADJACENCY = {
"hull_right": ("sonar", "weapons", "opz", "radio", "engine", "flightdeck"),
}
# Geometry (fictional, consistent): floodable volume (m^3, after
# permeability), centroid x (m forward of midships), y (m to starboard),
# floor height above keel (m), compartment height (m), width b (m),
# fuel/fire load factor, electrical switchboard.
GEOMETRY = {
"bridge": dict(volume=140.0, x=40.0, y=0.0, floor=10.0, height=4.0,
b=10.0, fuel=0.6, electrical=True),
"sonar": dict(volume=180.0, x=50.0, y=0.0, floor=0.5, height=5.0,
b=8.0, fuel=0.5, electrical=True),
"weapons": dict(volume=260.0, x=22.0, y=0.0, floor=1.5, height=6.0,
b=11.0, fuel=1.5, electrical=False),
"opz": dict(volume=200.0, x=10.0, y=0.0, floor=4.0, height=4.0,
b=12.0, fuel=0.8, electrical=True),
"radio": dict(volume=150.0, x=-5.0, y=0.0, floor=6.0, height=4.0,
b=10.0, fuel=0.6, electrical=True),
"engine": dict(volume=520.0, x=-25.0, y=0.0, floor=0.5, height=7.0,
b=13.0, fuel=1.4, electrical=False),
"flightdeck": dict(volume=300.0, x=-45.0, y=0.0, floor=5.0, height=6.0,
b=13.0, fuel=1.2, electrical=False),
"hull_left": dict(volume=250.0, x=0.0, y=-5.5, floor=0.5, height=6.0,
b=3.0, fuel=0.3, electrical=False),
"hull_right": dict(volume=250.0, x=0.0, y=5.5, floor=0.5, height=6.0,
b=3.0, fuel=0.3, electrical=False),
}
RHO = 1025.0
G = 9.80665
ORIFICE_CD = 0.6
DESIGN_DRAFT_M = 7.5
DISPLACEMENT_KG = 3_600_000.0
GM_M = 1.2
# Reserve buoyancy calibrated to the 1.0.0 sinking rule: 60 % mean flooding.
RESERVE_BUOYANCY_KG = 0.6 * sum(g["volume"] for g in GEOMETRY.values()) * RHO
CAPSIZE_HEEL_DEG = 35.0
CAPSIZE_GM_M = 0.05
# Torpedo hole area calibrated so a fresh hit floods a mid compartment at
# the 1.0.0 rate (DMG_FLOOD_RATE); a patch leaves 25 %.
PATCH_LEAK_FRACTION = config.DMG_LEAK_RATE / config.DMG_FLOOD_RATE
PATCH_KITS = 8
PATCH_TIME_S = 20.0
TEAM_HOP_S = 20.0
TEAM_BASE = "opz" # damage-control central
FIRE_SPREAD_LEVEL = 60.0
FIRE_SPREAD_HEAT_S = 30.0
FIRE_SMOTHER_FLOOD = 60.0
FIRE_WATER_COOLING = 0.3 # %/s at the smothering level
ELECTRICAL_SHORT_FLOOD = 40.0
COOK_OFF_FIRE = 90.0
def _reference_hole_m2() -> float:
geo = GEOMETRY["weapons"]
head = DESIGN_DRAFT_M - geo["floor"]
rate = config.DMG_FLOOD_RATE / 100.0 * geo["volume"] # m^3/s
return rate / (ORIFICE_CD * math.sqrt(2.0 * G * head))
HIT_HOLE_M2 = _reference_hole_m2()
def orifice_inflow_m3_s(area_m2: float, head_m: float) -> float:
if area_m2 <= 0.0 or head_m <= 0.0:
return 0.0
return ORIFICE_CD * area_m2 * math.sqrt(2.0 * G * head_m)
class Compartment:
"""Zustand: OK -> FLUTEND/BESCHAEDIGT -> ZERSTOERT."""
@@ -37,49 +126,39 @@ class Compartment:
self.key = key
self.name = name
self.state = "OK"
self.flood = 0.0 # 0..100 %
self.flood = 0.0 # 0..100 % of floodable volume (70 = destroyed)
self.fire = 0.0 # M14: Brand 0..100 % (>100 = Kompartiment ZERSTOERT)
self.hole_m2 = 0.0 # open hull area
self.heat_s = 0.0 # time a strong fire has heated the bulkheads
self.shorted = False # switchboard already shorted by flooding
def hit(self, rng: random.Random) -> None:
@property
def geometry(self) -> dict:
return GEOMETRY[self.key]
def water_m3(self) -> float:
return self.flood / 100.0 * self.geometry["volume"]
def water_level_m(self) -> float:
"""Height of the free surface above the keel."""
geo = self.geometry
return geo["floor"] + min(1.0, self.flood / 100.0) * geo["height"]
def hit(self, rng: random.Random, hole_scale: float = 1.0) -> None:
if self.state != "ZERSTOERT":
self.state = "FLUTEND"
self.flood = max(self.flood, rng.uniform(10.0, 30.0))
self.hole_m2 = max(self.hole_m2, HIT_HOLE_M2 * hole_scale)
self.flood = max(self.flood, rng.uniform(10.0, 30.0)
if self.geometry["floor"] < DESIGN_DRAFT_M else self.flood)
if rng.random() < config.DMG_FIRE_START_CHANCE:
self.fire = max(self.fire, rng.uniform(*config.DMG_FIRE_START))
def update(self, dt: float, repaired: bool,
repair_rate: float = config.DMG_REPAIR_RATE,
fire_teams: int = 0) -> None:
def capability(self) -> float:
"""0..1 remaining function of the station in this room."""
if self.state == "ZERSTOERT":
return
if self.state == "FLUTEND":
self.flood += config.DMG_FLOOD_RATE * dt
elif self.state == "BESCHAEDIGT":
self.flood += config.DMG_LEAK_RATE * dt
if repaired:
self.flood -= repair_rate * dt
if self.state == "FLUTEND" and self.flood <= 35.0:
self.state = "BESCHAEDIGT"
if self.flood <= 0.0:
self.flood = 0.0
self.state = "OK"
if self.state in ("FLUTEND", "BESCHAEDIGT") \
and self.flood >= config.DMG_DESTROY_FLOOD:
self.state = "ZERSTOERT"
self.flood = config.DMG_DESTROY_FLOOD
# M14: Brand – breitet sich von selbst aus, wird von Löschteams gelöscht
if self.fire > 0.0 and self.state != "ZERSTOERT":
self.fire += config.DMG_FIRE_RATE * dt
self.fire -= config.DMG_FIRE_REPAIR_RATE * fire_teams * dt
if self.fire <= 0.0:
self.fire = 0.0
if self.fire >= config.DMG_FIRE_KILL and self.state != "ZERSTOERT":
self.state = "ZERSTOERT"
self.flood = max(self.flood, config.DMG_DESTROY_FLOOD)
return 0.0
return max(0.0, 1.0 - self.flood / config.DMG_DESTROY_FLOOD
- self.fire / (2.0 * config.DMG_FIRE_KILL))
class DamageModel:
@@ -92,18 +171,54 @@ class DamageModel:
self.repair_mult = repair_mult # M7: Level-Faktor Reparaturrate
self.compartments = {k: Compartment(k, n) for k, n in COMPARTMENTS}
self.teams: dict[int, str | None] = {1: None, 2: None, 3: None}
# Where each team stands and how long until it arrives (saved).
self.team_position: dict[int, str] = {1: TEAM_BASE, 2: TEAM_BASE,
3: TEAM_BASE}
self.team_eta: dict[int, float] = {1: 0.0, 2: 0.0, 3: 0.0}
self.patch_kits = PATCH_KITS
self.cooked_off = False
self.capsized = False
self.total = 0.0
self.ship_sunk = False
self.draft_m = DESIGN_DRAFT_M
# --- Ereignisse ---
def torpedo_hit(self, hit_zone: str | None = None) -> list[str]:
"""Ermittelt 1–2 getroffene Kompartimente.
def torpedo_hit(self, hit_zone: str | None = None,
impact: tuple[float, float] | None = None,
hole_scale: float = 1.0) -> list[str]:
"""Damage the compartments at the impact point.
Eine Trefferzone verschiebt die Wahrscheinlichkeit zur passenden
Abteilung, ersetzt aber nicht den Zufallsanteil eines Gefechtstreffers.
Ohne Zone bleibt das bisherige Verhalten erhalten.
``impact`` is (longitudinal, lateral) in -1..1 of the hull (bow and
starboard positive): the nearest compartment floods, and the next one
within the blast radius too. Without an impact the legacy zone
weighting chooses 1-2 compartments at random.
"""
if impact is not None:
chosen = self._impact_compartments(*impact)
else:
chosen = self._zone_compartments(hit_zone)
for key in chosen:
self.compartments[key].hit(self.rng, hole_scale)
return chosen
def _impact_compartments(self, longitudinal: float, lateral: float) -> list[str]:
x = longitudinal * 59.0
y = lateral * 7.0
ranked = sorted(
GEOMETRY, key=lambda key: (math.hypot(GEOMETRY[key]["x"] - x,
(GEOMETRY[key]["y"] - y) * 3.0),
key))
first = ranked[0]
chosen = [first]
side = "hull_right" if lateral >= 0.0 else "hull_left"
if side not in chosen and abs(lateral) >= 0.4:
chosen.append(side)
elif ranked[1] in COMPARTMENT_ADJACENCY[first]:
chosen.append(ranked[1])
return chosen[:2]
def _zone_compartments(self, hit_zone):
keys = [k for k in self.compartments]
n = self.rng.choice((1, 2))
preferred = {
@@ -119,10 +234,17 @@ class DamageModel:
remaining = [k for k in keys if k not in chosen]
if len(chosen) < n:
chosen.extend(self.rng.sample(remaining, n - len(chosen)))
for k in chosen:
self.compartments[k].hit(self.rng)
return chosen
def missile_hit(self, longitudinal: float, lateral: float) -> list[str]:
"""Above-waterline hit: fire and structural damage, no flooding."""
key = self._impact_compartments(longitudinal, lateral)[0]
room = self.compartments[key]
if room.state == "OK":
room.state = "BESCHAEDIGT"
room.fire = max(room.fire, 40.0)
return [key]
def grounding_impact(self, energy_j: float, longitudinal: float,
lateral: float) -> dict[str, float]:
"""Apply deterministic localized flooding without consuming RNG state."""
@@ -146,13 +268,43 @@ class DamageModel:
compartment.state = ("ZERSTOERT"
if compartment.flood >= config.DMG_DESTROY_FLOOD
else "FLUTEND")
# A grounding tears the shell plating open too.
compartment.hole_m2 = max(compartment.hole_m2,
HIT_HOLE_M2 * amount / 30.0)
applied[key] = compartment.flood - old
self._recompute_totals()
return applied
# --- stability -------------------------------------------------------------
def flood_mass_kg(self) -> float:
return sum(c.water_m3() for c in self.compartments.values()) * RHO
def gm_effective_m(self) -> float:
"""GM with the free-surface correction of partly flooded rooms."""
displacement = DISPLACEMENT_KG + self.flood_mass_kg()
free = 0.0
for c in self.compartments.values():
if 0.0 < c.flood < 95.0:
geo = c.geometry
length = geo["volume"] / (geo["b"] * geo["height"])
free += RHO * length * geo["b"] ** 3 / 12.0
return GM_M - free / displacement
def _heel_rad(self) -> float:
displacement = DISPLACEMENT_KG + self.flood_mass_kg()
moment = sum(c.water_m3() * RHO * c.geometry["y"]
for c in self.compartments.values())
gm = max(self.gm_effective_m(), CAPSIZE_GM_M)
return math.atan(moment / (displacement * gm))
def _recompute_totals(self) -> None:
self.total = sum(c.flood for c in self.compartments.values())
if self.total >= config.DMG_SHIP_SINK_TOTAL:
if self.flood_mass_kg() >= RESERVE_BUOYANCY_KG:
self.ship_sunk = True
if (self.gm_effective_m() <= CAPSIZE_GM_M
or abs(math.degrees(self._heel_rad())) >= CAPSIZE_HEEL_DEG):
self.capsized = True
self.ship_sunk = True
# --- Steuerung ---
@@ -161,32 +313,58 @@ class DamageModel:
return [k for k, c in self.compartments.items()
if c.state != "ZERSTOERT" and (c.state != "OK" or c.fire > 0.0)]
def _travel_s(self, start: str, destination: str) -> float:
"""Transit time along the compartment graph (hops x TEAM_HOP_S)."""
if start == destination:
return 0.0
seen = {start}
queue = deque([(start, 0)])
while queue:
key, hops = queue.popleft()
for neighbour in COMPARTMENT_ADJACENCY[key]:
if neighbour in seen:
continue
if neighbour == destination:
return (hops + 1) * TEAM_HOP_S
seen.add(neighbour)
queue.append((neighbour, hops + 1))
return TEAM_HOP_S * len(COMPARTMENTS)
def _send(self, team: int, destination: str | None) -> None:
self.teams[team] = destination
if destination is None:
self.team_eta[team] = 0.0
return
self.team_eta[team] = self._travel_s(self.team_position[team], destination)
def assign_team_cycle(self, team: int) -> str | None:
"""Team auf das nächste (oder weitere) betroffene Kompartiment."""
cands = self.repair_candidates()
if not cands:
self.teams[team] = None
self._send(team, None)
return None
cur = self.teams.get(team)
if cur in cands:
nxt = cands[(cands.index(cur) + 1) % len(cands)]
else:
nxt = cands[0]
self.teams[team] = nxt
self._send(team, nxt)
return nxt
def assign_team(self, team: int, destination: str) -> bool:
"""Assign explicitly without silently displacing another team."""
if team not in self.teams or destination not in self.repair_candidates():
return False
self.teams[team] = destination
self._send(team, destination)
return True
def unassign_team(self, team: int) -> None:
self.teams[team] = None
self._send(team, None)
def teams_on(self, key: str) -> list[int]:
return [t for t, k in self.teams.items() if k == key]
"""Teams that have arrived and are working in this room."""
return [t for t, k in self.teams.items()
if k == key and self.team_eta.get(t, 0.0) <= 0.0]
def repair_rates(self, key: str) -> tuple[float, float]:
"""Flood/fire removal per second with the current team assignment."""
@@ -195,6 +373,15 @@ class DamageModel:
return (config.DMG_REPAIR_RATE * self.repair_mult * factor,
config.DMG_FIRE_REPAIR_RATE * count)
def _inflow_pct_s(self, c: Compartment) -> float:
geo = c.geometry
if c.hole_m2 <= 0.0 or c.state == "ZERSTOERT":
return 0.0
side = geo["y"]
waterline = self.draft_m + side * math.tan(self._heel_rad())
head = waterline - max(geo["floor"], c.water_level_m())
return orifice_inflow_m3_s(c.hole_m2, head) / geo["volume"] * 100.0
def compartment_trend(self, key: str) -> dict:
"""Pure instantaneous net rates, excluding random spread/transitions.
@@ -206,13 +393,11 @@ class DamageModel:
flood_rate = fire_rate = 0.0
if repairable:
flood_repair, fire_repair = self.repair_rates(key)
flood_rate = (config.DMG_FLOOD_RATE if c.state == "FLUTEND" else
config.DMG_LEAK_RATE if c.state == "BESCHAEDIGT" else 0.0)
flood_rate -= flood_repair
flood_rate = self._inflow_pct_s(c) - flood_repair
if c.flood <= 0.0:
flood_rate = max(0.0, flood_rate)
if c.fire > 0.0:
fire_rate = config.DMG_FIRE_RATE - fire_repair
fire_rate = self._fire_growth(c) - fire_repair
return {"flood_rate": flood_rate, "fire_rate": fire_rate,
"repairable": repairable}
@@ -228,48 +413,116 @@ class DamageModel:
return self.compartments[key].state in ("FLUTEND", "BESCHAEDIGT") \
or self.compartments[key].fire > 0.0
def capability(self, key: str) -> float:
return self.compartments[key].capability()
def avg_flood(self) -> float:
return self.total / len(self.compartments)
def list_deg(self) -> float:
"""Heel from asymmetric flooding: positive = listing to starboard.
Pure derived value from the existing hull_left/hull_right flood
percentages (already part of save state) - not itself new state.
"""
asymmetry = (self.compartments["hull_right"].flood
- self.compartments["hull_left"].flood)
return config.clamp(asymmetry * config.SHIP_LIST_DEG_PER_FLOOD_PCT,
-config.SHIP_MAX_LIST_DEG, config.SHIP_MAX_LIST_DEG)
"""Heel from off-centre floodwater (positive = to starboard)."""
return config.clamp(math.degrees(self._heel_rad()),
-CAPSIZE_HEEL_DEG, CAPSIZE_HEEL_DEG)
def engine_speed_cap(self) -> float:
if self.station_down("engine"):
return 8.0
if self.station_degraded("engine"):
return 15.0
# Continuous loss of plant power with flooding and fire.
return max(8.0, 8.0 + (config.SHIP_SPEED_MAX_KN - 8.0)
* min(15.0 / config.SHIP_SPEED_MAX_KN,
self.capability("engine") + 0.2))
return config.SHIP_SPEED_MAX_KN
# --- Update ---
def update(self, dt: float) -> None:
def _fire_growth(self, c: Compartment) -> float:
"""Net intensity change: fuel-driven growth limited by oxygen, minus
cooling by floodwater (continuous, so trends stay predictable)."""
oxygen = max(0.0, 1.0 - c.flood / FIRE_SMOTHER_FLOOD)
cooling = FIRE_WATER_COOLING * max(0.0, c.flood - 20.0) / FIRE_SMOTHER_FLOOD
return config.DMG_FIRE_RATE * c.geometry["fuel"] * oxygen - cooling
def _update_compartment(self, c: Compartment, dt: float) -> None:
if c.state == "ZERSTOERT":
return
teams = self.teams_on(c.key)
flood_repair, fire_repair = self.repair_rates(c.key)
# Rates of this step come from the state at its start.
fire_net = self._fire_growth(c) - fire_repair
inflow = self._inflow_pct_s(c)
if teams and c.hole_m2 > 0.0 and c.state == "FLUTEND":
# Shoring and patching the hole needs a kit.
if self.patch_kits > 0 and c.flood <= 35.0 + flood_repair * PATCH_TIME_S:
self.patch_kits -= 1
c.hole_m2 *= PATCH_LEAK_FRACTION
c.state = "BESCHAEDIGT"
c.flood += inflow * dt
if teams:
c.flood -= flood_repair * dt
if c.flood <= 0.0:
c.flood = 0.0
c.hole_m2 = 0.0
c.state = "OK" if c.fire <= 0.0 else "BESCHAEDIGT"
c.flood = max(0.0, c.flood)
if c.state in ("FLUTEND", "BESCHAEDIGT") and c.flood >= config.DMG_DESTROY_FLOOD:
c.state = "ZERSTOERT"
c.flood = config.DMG_DESTROY_FLOOD
return
if (c.geometry["electrical"] and not c.shorted
and c.flood >= ELECTRICAL_SHORT_FLOOD):
c.shorted = True
c.fire = max(c.fire, 10.0)
if c.fire > 0.0:
c.fire += fire_net * dt
c.fire = max(0.0, c.fire)
c.heat_s = c.heat_s + dt if c.fire >= FIRE_SPREAD_LEVEL else 0.0
if c.fire >= config.DMG_FIRE_KILL:
c.state = "ZERSTOERT"
c.flood = max(c.flood, config.DMG_DESTROY_FLOOD)
else:
c.heat_s = 0.0
def _spread_fire(self) -> None:
for c in self.compartments.values():
if c.heat_s < FIRE_SPREAD_HEAT_S:
continue
c.heat_s = 0.0
for key in COMPARTMENT_ADJACENCY[c.key]:
neighbour = self.compartments[key]
if neighbour.fire <= 0.0 and neighbour.state != "ZERSTOERT" \
and neighbour.flood < FIRE_SMOTHER_FLOOD:
neighbour.fire = config.DMG_FIRE_START[0]
def _cook_off(self) -> None:
room = self.compartments["weapons"]
if self.cooked_off or room.fire < COOK_OFF_FIRE:
return
self.cooked_off = True
room.state = "ZERSTOERT"
room.flood = config.DMG_DESTROY_FLOOD
for key in COMPARTMENT_ADJACENCY["weapons"]:
neighbour = self.compartments[key]
if neighbour.state == "ZERSTOERT":
continue
neighbour.state = "FLUTEND"
neighbour.hole_m2 = max(neighbour.hole_m2, HIT_HOLE_M2)
neighbour.fire = max(neighbour.fire, 30.0)
def update(self, dt: float, draft_m: float | None = None) -> None:
if self.ship_sunk:
return
if draft_m is not None:
self.draft_m = draft_m
for team, eta in self.team_eta.items():
if eta > 0.0:
self.team_eta[team] = max(0.0, eta - dt)
if self.team_eta[team] <= 0.0 and self.teams[team] is not None:
self.team_position[team] = self.teams[team]
for c in self.compartments.values():
teams = self.teams_on(c.key)
flood_repair, _ = self.repair_rates(c.key)
c.update(dt, bool(teams), flood_repair,
fire_teams=len(teams))
# M14: Brandausbreitung in benachbarte Kompartimente
for c in list(self.compartments.values()):
if c.fire > 0.0 and \
self.rng.random() < config.DMG_FIRE_SPREAD_PPS * dt:
neighbors = [self.compartments[key]
for key in COMPARTMENT_ADJACENCY[c.key]
if self.compartments[key].fire <= 0.0
and self.compartments[key].state != "ZERSTOERT"]
if neighbors:
o = self.rng.choice(neighbors)
o.fire = self.rng.uniform(*config.DMG_FIRE_START)
self._update_compartment(c, dt)
self._spread_fire()
self._cook_off()
for team, key in self.teams.items():
c = self.compartments[key] if key is not None else None
if c is not None and c.state == "OK" and c.fire <= 0.0:
+4 -1
View File
@@ -317,7 +317,10 @@ def test_raider_salvo_asms_hit_the_frigate_and_damage_compartments(game, monkeyp
asm.speed_kn = 0.0 # Treffer-Zeitpunkt kontrollieren
game._update_air_defense(0.1, publish_picture=False)
assert asm.state == "TREFFER"
assert any(c.flood > 0.0 for c in game.damage.compartments.values())
# A missile strikes above the waterline: mainly fire, flooding only if
# the blast holes a room low enough.
assert any(c.fire > 0.0 or c.flood > 0.0 or c.state != "OK"
for c in game.damage.compartments.values())
# --- Air Picture ---
+38 -16
View File
@@ -5,7 +5,7 @@ import random
import pytest
from src.core import config
from src.ship.damage import Compartment, DamageModel
from src.ship.damage import CAPSIZE_HEEL_DEG, HIT_HOLE_M2, TEAM_HOP_S, Compartment, DamageModel
class FixedRng:
@@ -43,29 +43,43 @@ def test_repeated_hit_does_not_revive_destroyed_compartment():
assert compartment.flood == config.DMG_DESTROY_FLOOD
def _arrive(model):
for team in model.team_eta:
model.team_eta[team] = 0.0
def test_repair_is_applied_before_flood_destruction():
compartment = Compartment("engine", "Maschinerie")
model = DamageModel(random.Random(3))
compartment = model.compartments["engine"]
compartment.state = "FLUTEND"
compartment.flood = config.DMG_DESTROY_FLOOD - 1.0
compartment.hole_m2 = HIT_HOLE_M2
model.patch_kits = 0
model.assign_team(1, "engine")
_arrive(model)
trend = model.compartment_trend("engine")["flood_rate"]
compartment.update(1.0, repaired=True)
model.update(1.0)
assert compartment.state == "FLUTEND"
assert compartment.flood == pytest.approx(
config.DMG_DESTROY_FLOOD - 1.0
+ config.DMG_FLOOD_RATE - config.DMG_REPAIR_RATE)
config.DMG_DESTROY_FLOOD - 1.0 + trend, rel=1e-6)
def test_fire_growth_and_suppression_are_net_before_destruction():
compartment = Compartment("weapons", "Waffenzentrale")
compartment.fire = config.DMG_FIRE_KILL - 1.0
model = DamageModel(random.Random(3))
compartment = model.compartments["engine"]
compartment.fire = config.DMG_FIRE_KILL - 5.0
compartment.state = "BESCHAEDIGT"
model.assign_team(1, "engine")
_arrive(model)
growth = config.DMG_FIRE_RATE * compartment.geometry["fuel"]
compartment.update(1.0, repaired=True, fire_teams=1)
model.update(1.0)
assert compartment.state == "OK"
assert compartment.state != "ZERSTOERT"
assert compartment.fire == pytest.approx(
config.DMG_FIRE_KILL - 1.0
+ config.DMG_FIRE_RATE - config.DMG_FIRE_REPAIR_RATE)
config.DMG_FIRE_KILL - 5.0 + growth - config.DMG_FIRE_REPAIR_RATE)
def test_fire_only_spreads_to_explicit_neighbors(monkeypatch):
@@ -87,6 +101,10 @@ def test_multiple_teams_can_share_a_repairable_compartment():
assert model.assign_team(1, "engine") is True
assert model.assign_team(2, "engine") is True
# Teams walk from damage control: working only after the transit.
assert model.teams_on("engine") == []
assert model.team_eta[1] == pytest.approx(2 * TEAM_HOP_S)
model.update(2 * TEAM_HOP_S)
assert model.teams_on("engine") == [1, 2]
@@ -97,6 +115,7 @@ def test_fully_repaired_compartment_releases_all_teams():
compartment.flood = 1.0
model.assign_team(1, "engine")
model.assign_team(2, "engine")
_arrive(model)
model.update(7.0)
@@ -111,16 +130,19 @@ def test_list_deg_reflects_flood_asymmetry_and_is_bounded():
assert model.list_deg() == 0.0
model.compartments["hull_right"].flood = 20.0
assert model.list_deg() == pytest.approx(
20.0 * config.SHIP_LIST_DEG_PER_FLOOD_PCT)
starboard = model.list_deg()
# Off-centre floodwater moment over displacement x effective GM.
assert 1.0 < starboard < 6.0
model.compartments["hull_left"].flood = 20.0
assert model.list_deg() == 0.0 # symmetric flooding: no net list
assert model.list_deg() == pytest.approx(0.0, abs=1e-9)
model.compartments["hull_left"].flood = 0.0
model.compartments["hull_right"].flood = 1000.0
assert model.list_deg() == config.SHIP_MAX_LIST_DEG # clamped
assert model.list_deg() == CAPSIZE_HEEL_DEG # clamped at downflooding
model.compartments["hull_right"].flood = 0.0
model.compartments["hull_left"].flood = 1000.0
assert model.list_deg() == -config.SHIP_MAX_LIST_DEG
assert model.list_deg() == -CAPSIZE_HEEL_DEG
+1
View File
@@ -44,6 +44,7 @@ def test_net_trends_match_simulation_and_diminishing_teams(monkeypatch, mult, te
room.state, room.flood, room.fire = state, 60.0, 40.0
for team in range(1, teams + 1):
model.assign_team(team, "engine")
model.team_eta[team] = 0.0 # teams have arrived (transit tested elsewhere)
before_rng = model.rng.getstate()
trend = model.compartment_trend("engine")
assert trend["repairable"]
+145
View File
@@ -0,0 +1,145 @@
"""Phase 10: flooding physics, stability, fire, repair logistics."""
import copy
import json
import random
import pytest
from src.core import config
from src.core.game import Game
from src.ship import damage as dmg
from src.ship.damage import DamageModel
def _model(seed=1):
return DamageModel(random.Random(seed))
def test_orifice_inflow_slows_as_levels_equalize_and_high_rooms_stay_dry():
model = _model()
hull = model.compartments["hull_left"]
hull.state, hull.hole_m2 = "FLUTEND", dmg.HIT_HOLE_M2
first = model.compartment_trend("hull_left")["flood_rate"]
hull.flood = 60.0
later = model.compartment_trend("hull_left")["flood_rate"]
assert first > later > 0.0
bridge = model.compartments["bridge"]
bridge.state, bridge.hole_m2 = "FLUTEND", dmg.HIT_HOLE_M2
assert model.compartment_trend("bridge")["flood_rate"] == 0.0
def test_patching_consumes_a_kit_and_leaves_a_small_leak():
model = _model()
room = model.compartments["engine"]
room.state, room.hole_m2, room.flood = "FLUTEND", dmg.HIT_HOLE_M2, 20.0
model.assign_team(1, "engine")
model.team_eta[1] = 0.0
model.update(0.1)
assert model.patch_kits == dmg.PATCH_KITS - 1
assert room.state == "BESCHAEDIGT"
assert room.hole_m2 == pytest.approx(dmg.HIT_HOLE_M2 * dmg.PATCH_LEAK_FRACTION)
empty = _model()
empty.patch_kits = 0
other = empty.compartments["engine"]
other.state, other.hole_m2, other.flood = "FLUTEND", dmg.HIT_HOLE_M2, 20.0
empty.assign_team(1, "engine")
empty.team_eta[1] = 0.0
empty.update(0.1)
assert other.state == "FLUTEND" and other.hole_m2 == dmg.HIT_HOLE_M2
def test_impact_point_selects_the_compartment():
assert "engine" in _model().torpedo_hit(impact=(-0.45, 0.0))
assert "sonar" in _model().torpedo_hit(impact=(0.85, 0.0))
assert "hull_right" in _model().torpedo_hit(impact=(0.0, 0.9))
missile = _model()
keys = missile.missile_hit(0.7, 0.0)
room = missile.compartments[keys[0]]
assert room.fire >= 40.0 and room.hole_m2 == 0.0
def test_reserve_buoyancy_and_capsize_decide_sinking():
sinking = _model()
for room in sinking.compartments.values():
room.flood = 65.0
sinking.update(0.0)
assert sinking.ship_sunk
capsize = _model()
for key in ("engine", "weapons", "flightdeck", "opz", "sonar"):
capsize.compartments[key].flood = 50.0
assert capsize.gm_effective_m() < dmg.GM_M
capsize.update(0.0)
assert capsize.capsized == (capsize.gm_effective_m() <= dmg.CAPSIZE_GM_M)
def test_fire_spreads_through_hot_bulkheads_and_water_cools_it():
model = _model()
engine = model.compartments["engine"]
engine.fire, engine.state = 70.0, "BESCHAEDIGT"
for _ in range(40):
model.update(1.0)
assert any(model.compartments[key].fire > 0.0
for key in dmg.COMPARTMENT_ADJACENCY["engine"])
wet = _model()
room = wet.compartments["engine"]
room.fire, room.flood, room.state = 30.0, 55.0, "BESCHAEDIGT"
assert wet.compartment_trend("engine")["fire_rate"] < 0.0
def test_flooded_switchboard_starts_a_fire_and_the_magazine_can_cook_off():
model = _model()
radio = model.compartments["radio"]
radio.flood, radio.state = dmg.ELECTRICAL_SHORT_FLOOD + 1.0, "BESCHAEDIGT"
model.update(0.1)
assert radio.shorted and radio.fire > 0.0
magazine = _model()
weapons = magazine.compartments["weapons"]
weapons.fire, weapons.state = dmg.COOK_OFF_FIRE + 1.0, "BESCHAEDIGT"
magazine.update(0.1)
assert magazine.cooked_off and weapons.state == "ZERSTOERT"
assert all(magazine.compartments[key].hole_m2 > 0.0
for key in dmg.COMPARTMENT_ADJACENCY["weapons"]
if magazine.compartments[key].state != "ZERSTOERT")
def test_capability_is_continuous():
model = _model()
room = model.compartments["sonar"]
assert model.capability("sonar") == 1.0
room.flood, room.state = 35.0, "BESCHAEDIGT"
assert 0.0 < model.capability("sonar") < 1.0
room.state = "ZERSTOERT"
assert model.capability("sonar") == 0.0
def test_hostile_hulls_flood_progressively_and_lose_systems():
from src.enemies.surface import NPC_RADAR_LOST_DAMAGE, SurfaceShip
ship = SurfaceShip(100.0, 100.0, random.Random(1),
profile=None, side="hostile", doctrine="surface_combatant")
ship.emitter = True
ship.damage = 50.0
ship._progressive_flooding(600.0)
assert ship.damage > 50.0
ship.damage = NPC_RADAR_LOST_DAMAGE
assert not ship.radar_emitting
def test_damage_state_round_trips_and_is_validated():
game = Game(seed=1010, start_menu=False, audio_enabled=False)
room = game.damage.compartments["engine"]
room.state, room.flood, room.hole_m2, room.heat_s = "FLUTEND", 22.0, 0.02, 5.0
game.damage.assign_team(2, "engine")
game.damage.patch_kits = 5
state = json.loads(json.dumps(game.save_state()))
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
twin = restored.damage
assert twin.team_eta == game.damage.team_eta and twin.patch_kits == 5
assert twin.compartments["engine"].hole_m2 == 0.02
for mutation in (lambda d: d.update(patch_kits=99),
lambda d: d["compartments"]["engine"].update(hole_m2=-1.0),
lambda d: d["team_eta"].update({"1": -5.0})):
broken = copy.deepcopy(state)
mutation(broken["damage"])
assert not restored._load_save_data(broken)