Phase 2: force-based own-ship hydrodynamics

Add src/physics/ship_dynamics.py with hull/propeller data in
data/loadouts/ownship_hull.json, calibrated at load time against the
1.0.0 references (top speed, 92 s to 90 % of FULL, 92 s stop, 1.2 deg/s
at FULL, cavitation at 15 kn, cubic fuel law):
- Surge from propeller thrust (linear K_T(J)) against quadratic resistance
  and added resistance in waves; three exactly integrable regimes
  (load-up programme, governed, reverse-pitch braking) keep the result
  independent of the step size.
- Cavitation from the cavitation number at the screw depth (earlier when
  pitching lifts the stern); physical shaft rpm; fuel from shaft power.
- First-order Nomoto steering (turn circle ~0.4 NM at all speeds).
- 1-DOF roll/pitch driven by a Pierson-Moskowitz wave slope, turn heel,
  list and speed-dependent fin stabilizers.
- Displacement from fuel and floodwater; hydrostatic draft plus Barrass
  squat feed swept grounding.
- Jammed rudder when the aft steering-gear room is destroyed, stabilizers
  lost with a destroyed hull compartment.
- Saved wake ring with bubble decay for later sensor/weapon phases.
Deviations (rpm display values, HALF turn rate) are recorded in
tests/calibration/deviations.json. Manual EN/DE updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 14:09:53 +02:00
1 parent d666b1b46f
commit 236d23be0f
22 files changed
+970 -83

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
{
"version": 1,
"note": "Fictional gameplay frigate; physically consistent, not a real ship.",
"displacement_t": 3600.0,
"length_m": 118.0,
"beam_m": 14.0,
"draft_m": 7.5,
"block_coefficient": 0.48,
"waterplane_coefficient": 0.75,
"max_brake_power_kw": 30000.0,
"propulsive_efficiency": 0.65,
"propeller_diameter_m": 4.2,
"propeller_zero_thrust_advance_ratio": 1.4,
"flank_advance_ratio": 1.26,
"shaft_immersion_m": 5.5,
"idle_rpm": 20.0,
"metacentric_height_m": 1.2,
"turn_heel_lever_m": 2.0,
"roll_period_s": 10.0,
"roll_damping_ratio": 0.06,
"stabilizer_damping_ratio": 0.2,
"stabilizer_full_speed_kn": 18.0,
"pitch_period_s": 5.5,
"pitch_damping_ratio": 0.3,
"flood_mass_t_per_percent": 2.5,
"brake_thrust_limit_fraction": 0.6,
"wake_sample_s": 10.0,
"wake_max_points": 48,
"wake_decay_s": 180.0,
"surge_added_mass_ratio": 0.08
}
+3 -1
View File
@@ -49,7 +49,9 @@ Gefechtslage:
## Tipps für Profis {#bridge-tips}
- TMA braucht eine echte Änderung der eigenen Geschwindigkeit. Eine Wende um 30-60 Grad mit anschließend mehreren Minuten ruhigem Schlag liefert die beste Entfernungsschätzung. Drehen auf der Stelle hilft nicht.
- Das Schiff dreht höchstens 0,8 Grad pro Sekunde und braucht Minuten für Fahrtänderungen. Ausweichmanöver früh beginnen.
- Die Drehrate wächst mit der Fahrt (etwa 0,75 Grad/s bei 10 kn, 1,2 bei 16 kn, 1,9 bei 25 kn), der Drehkreis bleibt deshalb bei etwa 0,4 NM. Ein gestopptes Schiff kann nicht drehen. Fahrtänderungen brauchen Minuten: etwa 90 s bis 90 % von FULL; ein Stopp aus FULL nutzt Umsteuerung der Propellersteigung und dauert etwa 90 s. Ausweichmanöver früh beginnen.
- In einer harten Wende mit Fahrt krängt das Schiff einige Grad nach außen; bei schwerer See dämpfen die Flossenstabilisatoren das Rollen, aber nur mit Fahrt durchs Wasser.
- Im Flachwasser sackt der Rumpf ab (Squat): bei 25 kn wächst der Tiefgang um bis zu 3 m, wenn das Wasser weniger als etwa fünf Tiefgänge tief ist. Im Flachwasser Fahrt reduzieren.
- Sprint und Drift: mit FULL an eine neue Position, dann auf 4-6 kn gehen und horchen.
- Starke einseitige Flutung bewirkt Krängung und einen stetigen Drehzug; mit Ruder ausgleichen.
- Das Schiff kann nicht auf Land fahren (es wird zurückgeschoben), aber Flachwasser begrenzt die Tauchtiefe des Helikoptersonars (10 m Bodenabstand).
+3 -1
View File
@@ -49,7 +49,9 @@ Combat situation:
## Pro tips {#bridge-tips}
- TMA needs a real change of own velocity. A 30-60 degree turn followed by a steady leg of several minutes gives the best range estimate. Turning on the spot does not help.
- The ship turns at no more than 0.8 degrees per second and needs minutes to change speed. Start evasive turns early.
- The turn rate grows with speed (about 0.75 deg/s at 10 kn, 1.2 at 16 kn, 1.9 at 25 kn), so the turning circle stays near 0.4 NM. A stopped ship cannot turn. Speed changes take minutes: about 90 s to 90 % of FULL, and a stop from FULL uses reverse propeller pitch and takes about 90 s. Start evasive turns early.
- In a hard turn at speed the ship heels outward a few degrees; in heavy seas the fin stabilizers damp the roll, but only with steerage way.
- In shallow water the hull squats: at 25 kn the draft grows by up to 3 m when the water is less than about five draughts deep. Slow down in shoal water.
- Sprint-and-drift: sprint at FULL to a new position, then slow to 4-6 kn and listen.
- Heavy flooding on one side gives a list and a steady yaw pull; correct with rudder.
- The ship cannot run aground onto land; it is pushed back, but shallow water limits the helicopter dipping depth (10 m bottom clearance).
+1
View File
@@ -23,6 +23,7 @@ Seite 1 ist der Schiffsplan; Seite 2 zeigt Details je Abteilung (Flutung, Brand,
- **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.
- **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.
+1
View File
@@ -23,6 +23,7 @@ Page 1 is the ship schematic; page 2 lists details per compartment (flooding, fi
- **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.
- **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.
+3 -3
View File
@@ -26,11 +26,11 @@ Seite 1 ist der Maschinentelegraph mit Stufe, Fahrt, Wellendrehzahl und Eigenlä
4 15 25
```
- Der Eigenlärm steigt linear von 4 kn bis 25 kn. Ab 15 kn kavitieren die Schrauben: der Lärm liegt bei mindestens 0,85, die passive Sonarreichweite fällt auf 35 %.
- Der Eigenlärm steigt linear von 4 kn bis 25 kn. Die Schrauben kavitieren, wenn die Flügelspitzengeschwindigkeit für den Wasserdruck an den Schrauben zu hoch ist: bei ruhiger See ab 15 kn, bei schwerer See früher, wenn das Stampfen das Heck anhebt. Kavitation hebt den Lärm auf mindestens 0,85 und senkt die passive Sonarreichweite auf 35 %.
- Modus LEISE senkt den Eigenlärm auf 65 % und begrenzt die Fahrt auf 12 kn.
- Die Wellendrehzahl beträgt etwa 20 + 2,4 x Fahrt. Die eigene Wellenlinie im LOFAR wandert mit der Fahrt.
- Die Wellendrehzahl folgt dem Festpropeller: bei konstanter Fahrt etwa 5,8 U/min je Knoten (146 U/min bei 25 kn). Beim Beschleunigen hält das Fahrprogramm die Welle höchstens etwa 11 U/min vor der aktuellen Fahrt; beim Abbremsen wird die Steigung umgesteuert und die Welle läuft mit 20 U/min im Leerlauf. Die eigene Wellenlinie im LOFAR wandert mit der Fahrt.
- Maschinenschaden begrenzt die Fahrt auf 15 kn (beschädigt) oder 8 kn (zerstört).
- Der Kraftstoffverbrauch steigt mit der Fahrt. Mit leeren Tanks steht die Welle, und kein Maschinenbefehl wird angenommen.
- Der Kraftstoffverbrauch folgt der abgegebenen Propellerleistung: bei konstanter Fahrt wächst er mit der dritten Potenz der Fahrt, Beschleunigen und Bremsen kosten zusätzlich. Ein leichteres Schiff (verbrauchter Kraftstoff) beschleunigt etwas schneller; Flutwasser macht es langsamer und tiefer. Schwere See erhöht den Widerstand und kostet bei FULL bis etwa 1 kn. Mit leeren Tanks steht die Welle, und kein Maschinenbefehl wird angenommen.
## Tasten {#engine-keys}
+3 -3
View File
@@ -26,11 +26,11 @@ Page 1 is the engine telegraph with order, speed, shaft RPM and own noise; page
4 15 25
```
- Own noise rises linearly from 4 kn to 25 kn. From 15 kn the propellers cavitate: noise is at least 0.85 and passive sonar range is cut to 35 %.
- Own noise rises linearly from 4 kn to 25 kn. The propellers cavitate when the blade-tip speed is too high for the water pressure at the screws: in calm water from 15 kn, in heavy seas earlier when pitching lifts the stern. Cavitation raises noise to at least 0.85 and cuts passive sonar range to 35 %.
- QUIET mode reduces own noise to 65 % and limits speed to 12 kn.
- Shaft RPM is about 20 + 2.4 x speed. The own shaft line on LOFAR moves with speed.
- Shaft RPM follows the fixed-pitch propeller: about 5.8 rpm per knot at steady speed (146 rpm at 25 kn). While accelerating the control programme keeps the shaft at most about 11 rpm ahead of the present speed; when slowing down the pitch reverses and the shaft idles at 20 rpm. The own shaft line on LOFAR moves with speed.
- Machinery damage caps speed at 15 kn (damaged) or 8 kn (destroyed).
- Fuel burn grows with speed. With empty tanks the shaft stops and no engine order is accepted.
- Fuel burn follows the power the propellers deliver: at steady speed it grows with the cube of speed, accelerating and braking cost extra. A lighter ship (burnt fuel) accelerates slightly faster; floodwater makes it slower and deeper. Heavy seas add resistance and cost up to about 1 kn at FULL. With empty tanks the shaft stops and no engine order is accepted.
## Keys {#engine-keys}
+2 -2
View File
@@ -45,8 +45,8 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| Merkmal | Wert |
|---|---|
| Fahrt | 4-25 kn; Telegraph STOP 0, SLOW 6, HALF 10, FULL 16, FLANK 25 kn |
| Drehrate | bis 0,8 Grad/s |
| Kavitation | ab 15 kn; Passivreichweite x0,35 |
| Drehrate | etwa 0,075 Grad/s je Knoten (1,2 Grad/s bei 16 kn); Drehkreis etwa 0,4 NM |
| Kavitation | ab 15 kn bei ruhiger See, bei schwerer See früher; Passivreichweite x0,35 |
| 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 |
+2 -2
View File
@@ -45,8 +45,8 @@ All values are the defaults of the current game version. Custom difficulty and m
| Item | Value |
|---|---|
| Speed | 4-25 kn; telegraph STOP 0, SLOW 6, HALF 10, FULL 16, FLANK 25 kn |
| Turn rate | up to 0.8 deg/s |
| Cavitation | from 15 kn; passive range x0.35 |
| Turn rate | about 0.075 deg/s per knot (1.2 deg/s at 16 kn); turning circle about 0.4 NM |
| Cavitation | from 15 kn in calm water, earlier in heavy seas; passive range x0.35 |
| 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 |
+9 -9
View File
@@ -30,16 +30,16 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need for realism |
|-----|-------------------|------------------------|
| **Hydrodynamic resistance** | Speed approaches target linearly at fixed rate regardless of hull shape, loading, sea state | Drag polynomial `F_D(v) = C_D · ρ · A · v²` with speed-dependent thrust from shaft power; sea-state drag penalty |
| **Propeller/shaft physics** | Speed is a kinematic variable; no torque, no shaft RPM coupling to noise except a linear `SHIP_RPM_PER_KN` | Propeller thrust curve, shaft RPM as independent state, cavitation threshold from `n ∝ √(T/ρ)` not fixed kn |
| ~~**Hydrodynamic resistance**~~ | **Closed (Phase 2).** `src/physics/ship_dynamics.py`: resistance R = k v^2 (k from installed power and propulsive efficiency) plus added resistance in waves (Hs^2 B^2/L); thrust from a linear K_T(J) propeller; exact Riccati integration so any step size gives the same speed. | — |
| ~~**Propeller/shaft physics**~~ | **Closed (Phase 2).** Shaft revolutions from the propeller (steady rpm proportional to speed), a propulsion control programme limiting load-up, reverse-pitch braking, and cavitation from the cavitation number sigma at the screw depth (calibrated to 15 kn in calm water; earlier when pitching lifts the stern). | — |
| ~~**Rudder effectiveness vs speed**~~ | **Fixed (2026-09).** `speed_factor = clamp((speed/10)^2, 0, 1.5)` — already quadratic (dynamic-pressure-like), not linear. `ship.py:139`. | — |
| **Turn radius** | Implicit from yaw-rate limit; no explicit radius computation | `R = v / (g·tan φ / v)` or from rudder angle; depends on Froude number |
| **Trim / sink at speed** | None; ship always at "surface" depth = 5 m for sonar | Longitudinal trim from propeller wash + rudder; affects drag, freeboard, radar horizon |
| **Sea-state effect on motion** | Only cosmetic roll/pitch; no effect on speed loss or rudder authority | Added resistance in waves, heave/pitch coupling to rudder lift, spray-on-deck at high speed in rough seas |
| **Draft / under-keel clearance** | Fixed `draft_m = 7.5` + `keel_reserve_m = 1.5`; no squat effect | Squat ∝ v² in shallow water; draft varies with fuel/buoyancy |
| **Fuel → mass → performance** | Fuel depletes but does not affect speed, draught, or noise | Mass reduction changes inertia and speed polar |
| ~~**Damage → hydrodynamics**~~ | **Partially fixed (2026-09).** `DamageModel.list_deg()` already derives list angle from `hull_left`/`hull_right` flood asymmetry and feeds a persistent yaw bias into `Ship.update()`, scaled by the same speed factor above. Still open: no rudder loss, no loss of stabilisers. | Rudder loss; loss of stabilisers |
| **Wake signature** | None | Surface wake / turbulence behind ship affects sonar and torpedo performance |
| ~~**Turn radius**~~ | **Closed (Phase 2).** First-order Nomoto steering r = K (V/L) delta with T proportional to L/V, calibrated to 1.2 deg/s at FULL; turning circle about 0.4 NM at all speeds. | — |
| ~~**Trim / sink at speed**~~ | **Closed (Phase 2).** Hydrostatic draft from displacement (fuel burnt, floodwater), Barrass squat in shallow water feeding swept grounding, dynamic trim by the stern ~ Fn^2. | — |
| ~~**Sea-state effect on motion**~~ | **Closed (Phase 2).** Added resistance in waves; 1-DOF roll and pitch oscillators driven by an 8-component Pierson-Moskowitz wave slope relative to the wave direction, turn heel, damage list and speed-dependent fin stabilizer damping. | — |
| ~~**Draft / under-keel clearance**~~ | **Closed (Phase 2).** Dynamic draft (displacement + squat) is passed to `swept_grounding`; the tide (Phase 1) changes the water depth. | — |
| ~~**Fuel → mass → performance**~~ | **Closed (Phase 2).** Displacement = design load - burnt fuel + floodwater drives surge inertia and draft; fuel burn follows delivered shaft power (steady values reproduce the 1.0.0 cubic law). | — |
| ~~**Damage → hydrodynamics**~~ | **Closed (Phase 2).** List yaw bias (existing), jammed rudder when the aft steering-gear compartment (flight deck) is destroyed, fin stabilizers lost with a destroyed hull compartment, floodwater mass. | — |
| ~~**Wake signature**~~ | **Closed (Phase 2 model).** Bounded, saved wake ring (48 points, one per 10 s) with sea-state-dependent bubble decay and `Ship.wake_strength_at()`; consumed by own-sonar and wake-homing weapons in later phases. | — |
### 1.3 Data structures / interfaces that would be touched
+3 -1
View File
@@ -21,6 +21,7 @@ import numpy as np
from src.audio.hydroacoustics import analytic_envelope
from src.core import config
from src.physics import ship_dynamics
_BROADBAND_GAIN = 0.04 # rms-Skalierung der Bandrauschaudio
_OWN_CAV_GAIN = 0.10 # rms-Skalierung der Eigen-Kavitation
@@ -328,7 +329,8 @@ class AcousticReceiver:
audio += shaft
self.ownship_tonals = [{
"label": "OWN SHAFT", "frequency_hz": shaft_hz,
"rpm": speed * config.SHIP_RPM_PER_KN + config.SHIP_RPM_MIN,
"rpm": max(ship_dynamics.HULL.idle_rpm, ship_dynamics.HULL.steady_rps(
speed * ship_dynamics.KN) * 60.0),
}] if speed > 0 else []
# Shaft frequency is machinery/RPM evidence, not a bearing return.
scan = np.full(180, (ambient_rms**2 + np.mean(shaft**2)) / .25**2)
+27
View File
@@ -36,6 +36,7 @@ from src.core.mission_definition import static_preview, validate_mission
from src.core.station import Station
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.sensors.ais import AISReceiver
from src.physics import ship_dynamics
from src.world.ocean import OceanEnvironment
from src.core.save_schema import (
COMPARTMENT_FIELDS, COMPARTMENT_STATES, DAMAGE_FIELDS, RNG_STREAMS,
@@ -5773,6 +5774,13 @@ class Game:
self.ship.turn_rate_scale = (
0.5 if self.damage.station_degraded("bridge") else 1.0)
self.ship.speed_cap = self.damage.engine_speed_cap()
# Steering gear sits aft under the flight deck; a destroyed room
# jams the rudder where it is. Stabilizer fins are lost with either
# hull side destroyed. Floodwater adds displacement.
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.update_fuel(dt)
self.world.update(dt)
contact = self.ship.update(dt, self.world, self.damage.list_deg())
@@ -6550,6 +6558,9 @@ class Game:
rudder_angle=self.ship.rudder_angle,
yaw_rate=self.ship.yaw_rate,
roll=self.ship.roll, pitch=self.ship.pitch,
roll_rate=self.ship.roll_rate,
pitch_rate=self.ship.pitch_rate,
wake=[list(point) for point in self.ship.wake],
quiet_mode=self.ship.quiet_mode,
fuel_capacity_kg=self.ship.fuel_capacity_kg,
fuel_kg=self.ship.fuel_kg,
@@ -7056,6 +7067,9 @@ class Game:
self.ship.yaw_rate = ship["yaw_rate"]
self.ship.roll = ship["roll"]
self.ship.pitch = ship["pitch"]
self.ship.roll_rate = ship["roll_rate"]
self.ship.pitch_rate = ship["pitch_rate"]
self.ship.wake = [list(point) for point in ship["wake"]]
self.ship.quiet_mode = ship["quiet_mode"]
self.ship.fuel_capacity_kg = ship["fuel_capacity_kg"]
self.ship.fuel_kg = ship["fuel_kg"]
@@ -8039,6 +8053,19 @@ class Game:
ship = data.get("ship")
if not isinstance(ship, dict) or set(ship) != SHIP_FIELDS:
return False
wake = ship["wake"]
if (any(not bounded(ship[key], -100.0, 100.0)
for key in ("roll_rate", "pitch_rate"))
or not bounded(ship["clock"], 0.0, 1e12)
or not isinstance(wake, list)
or len(wake) > ship_dynamics.HULL.wake_max_points
or any(not isinstance(point, list) or len(point) != 4
or not all(bounded(value, -1_000_000, 1_000_000)
for value in point)
or not 0.0 <= point[2] <= ship["clock"]
or not 0.0 <= point[3] <= config.SHIP_SPEED_MAX_KN
for point in wake)):
return False
radars = data.get("radars")
if (not isinstance(radars, dict)
or set(radars) != {"surface", "air", "range_nm"}
+1 -1
View File
@@ -33,7 +33,7 @@ SHIP_FIELDS = frozenset({
"x", "y", "course", "target_course", "speed", "target_speed",
"order_idx", "astern", "hull", "grounding", "turn_rate_scale",
"rudder_angle", "yaw_rate", "roll", "pitch", "quiet_mode", "clock",
"fuel_capacity_kg", "fuel_kg",
"fuel_capacity_kg", "fuel_kg", "roll_rate", "pitch_rate", "wake",
})
WORLD_FIELDS = frozenset({
+1
View File
@@ -0,0 +1 @@
"""Deterministic physics models shared by simulation entities."""
+468
View File
@@ -0,0 +1,468 @@
"""Surface-ship hydrodynamics: surge, propeller, cavitation, steering,
seakeeping, sinkage and wake.
The model is force based and calibrated at load time against the 1.0.0
gameplay references (``src/core/config.py``): top speed, the time to reach
90 % of FULL, the stop distance, the steady turn at FULL and the cavitation
onset. Physical inputs (hull, propeller, stability) come from
``data/loadouts/ownship_hull.json``.
Surge integrates exactly: with the propeller speed held over a step the
equation of motion ``M dv/dt = a0 - a1 v - a2 v^2`` is a constant-coefficient
Riccati equation with a closed-form solution, so one long step equals many
short ones.
"""
from __future__ import annotations
import functools
import json
import math
from dataclasses import dataclass
from importlib import resources
from src.core import config, detrand
RHO_SEA = 1025.0
G = 9.80665
P_ATM = 101_325.0
P_VAPOUR = 2_340.0
KN = 1852.0 / 3600.0 # m/s per knot
# Significant wave height (m) by sea state 0..6.
SEA_STATE_HS_M = (0.0, 0.1, 0.5, 1.25, 2.5, 4.0, 6.0)
WAVE_COMPONENTS = 8
# Added resistance in waves: R_aw = c * rho * g * Hs^2 * B^2 / L.
ADDED_RESISTANCE_COEFF = 0.6
_HULL_FIELDS = {
"version", "note", "displacement_t", "length_m", "beam_m", "draft_m",
"block_coefficient", "waterplane_coefficient", "max_brake_power_kw",
"propulsive_efficiency", "propeller_diameter_m",
"propeller_zero_thrust_advance_ratio", "flank_advance_ratio",
"shaft_immersion_m", "idle_rpm", "metacentric_height_m",
"turn_heel_lever_m", "roll_period_s", "roll_damping_ratio",
"stabilizer_damping_ratio", "stabilizer_full_speed_kn", "pitch_period_s",
"pitch_damping_ratio", "flood_mass_t_per_percent",
"brake_thrust_limit_fraction", "surge_added_mass_ratio",
"wake_sample_s", "wake_max_points",
"wake_decay_s",
}
def load_hull_data() -> dict:
path = resources.files("data.loadouts") / "ownship_hull.json"
data = json.loads(path.read_text(encoding="utf-8"),
parse_constant=lambda value: (_ for _ in ()).throw(
ValueError(value)))
if not isinstance(data, dict) or set(data) != _HULL_FIELDS:
raise ValueError("ownship_hull.json: unexpected fields")
if data["version"] != 1 or not isinstance(data["note"], str):
raise ValueError("ownship_hull.json: unsupported version")
for key, value in data.items():
if key in ("version", "note"):
continue
if (isinstance(value, bool) or not isinstance(value, (int, float))
or not math.isfinite(value) or value <= 0.0):
raise ValueError(f"ownship_hull.json: {key} must be positive")
if data["flank_advance_ratio"] >= data["propeller_zero_thrust_advance_ratio"]:
raise ValueError("ownship_hull.json: flank advance ratio too high")
return data
def riccati_step(v0: float, a0: float, a1: float, a2: float,
dt: float) -> float:
"""Exact solution of dv/dt = a0 - a1 v - a2 v^2 after ``dt`` (a2 > 0)."""
if dt <= 0.0:
return v0
disc = a1 * a1 + 4.0 * a2 * a0
if disc > 1e-18:
root = math.sqrt(disc)
r1 = (-a1 + root) / (2.0 * a2)
r2 = (-a1 - root) / (2.0 * a2)
if abs(v0 - r2) < 1e-15:
return r2
q = (v0 - r1) / (v0 - r2) * math.exp(-a2 * (r1 - r2) * dt)
return (r1 - r2 * q) / (1.0 - q)
shift = a1 / (2.0 * a2)
if disc > -1e-18:
w0 = v0 + shift
return 1.0 / (1.0 / w0 + a2 * dt) - shift if w0 > 0.0 else w0 - shift
omega = math.sqrt(-disc) / (2.0 * a2)
w0 = v0 + shift
angle = math.atan(w0 / omega) - a2 * omega * dt
return omega * math.tan(angle) - shift
def riccati_time_to(v0: float, v1: float, a0: float, a1: float,
a2: float) -> float:
"""Time for dv/dt = a0 - a1 v - a2 v^2 (no real roots) to fall v0->v1."""
disc = a1 * a1 + 4.0 * a2 * a0
omega = math.sqrt(max(-disc, 1e-18)) / (2.0 * a2)
shift = a1 / (2.0 * a2)
return (math.atan((v0 + shift) / omega)
- math.atan((v1 + shift) / omega)) / (a2 * omega)
@dataclass(frozen=True)
class HullModel:
"""Calibrated constants of the own frigate (SI units)."""
mass_design_kg: float
added_mass_ratio: float
drag_k: float # R = k v^2 [N s^2/m^2]
thrust_k: float # T = K n^2 - B n v (n in rev/s)
thrust_b: float
brake_thrust_n: float
load_up_rps: float # control-programme margin over steady rps
rpm_per_mps: float # steady rev/min per m/s
diameter_m: float
shaft_immersion_m: float
cavitation_sigma: float
sfc_kg_per_j: float
propulsive_efficiency: float
pitch_screw_m: float # zero-thrust advance per revolution
nomoto_k: float # r = K (V/L) delta
nomoto_t_s: float
length_m: float
beam_m: float
draft_m: float
block_coefficient: float
waterplane_area_m2: float
gm_m: float
turn_heel_lever_m: float
roll_omega: float
roll_zeta: float
stabilizer_zeta: float
stabilizer_full_mps: float
pitch_omega: float
pitch_zeta: float
flood_kg_per_percent: float
idle_rpm: float
wake_sample_s: float
wake_max_points: int
wake_decay_s: float
# --- steady relations ------------------------------------------------
def steady_rps(self, speed_mps: float) -> float:
return self.rpm_per_mps * max(0.0, speed_mps) / 60.0
def thrust_n(self, rps: float, speed_mps: float) -> float:
return self.thrust_k * rps * rps - self.thrust_b * rps * speed_mps
def added_resistance_n(self, sea_state: float) -> float:
index = max(0.0, min(6.0, sea_state))
low = int(index)
high = min(6, low + 1)
hs = (SEA_STATE_HS_M[low]
+ (SEA_STATE_HS_M[high] - SEA_STATE_HS_M[low]) * (index - low))
return (ADDED_RESISTANCE_COEFF * RHO_SEA * G * hs * hs
* self.beam_m ** 2 / self.length_m)
def effective_mass_kg(self, mass_kg: float) -> float:
return mass_kg * (1.0 + self.added_mass_ratio)
def cavitation_number(self, rps: float, speed_mps: float,
immersion_m: float) -> float:
tip = math.hypot(math.pi * rps * self.diameter_m, speed_mps)
if tip <= 1e-6:
return float("inf")
pressure = P_ATM + RHO_SEA * G * max(0.0, immersion_m) - P_VAPOUR
return pressure / (0.5 * RHO_SEA * tip * tip)
def shaft_power_w(self, thrust: float, rps: float) -> float:
"""Delivered power from thrust times screw advance (bollard-safe)."""
return abs(thrust) * max(rps, 0.0) * self.pitch_screw_m \
/ max(0.05, self.propulsive_efficiency)
def _exp_linear_step(v0: float, alpha: float, beta: float, dt: float) -> float:
"""Exact solution of dv/dt = alpha + beta v."""
if abs(beta) < 1e-15:
return v0 + alpha * dt
return (v0 + alpha / beta) * math.exp(beta * dt) - alpha / beta
def _exp_linear_time_to(v0: float, v1: float, alpha: float, beta: float) -> float:
if abs(beta) < 1e-15:
return (v1 - v0) / alpha if alpha > 0.0 else float("inf")
ratio = (v1 + alpha / beta) / (v0 + alpha / beta)
return math.log(ratio) / beta if ratio > 0.0 else float("inf")
def surge_step(model: HullModel, v0: float, target: float, mass_kg: float,
dt: float, extra_resistance: float = 0.0,
brake_margin: float = 0.15) -> tuple[float, float, bool]:
"""Advance speed (m/s) toward the ordered speed for ``dt`` seconds.
Three exactly integrable regimes, split at their boundaries:
* braking - more than ``brake_margin`` above the order the controllable
pitch reverses for a bounded braking thrust (``a0 - a2 v^2``);
* load-up - the propulsion control programme lets the shaft run at most
``load_up_rps`` above the steady revolutions of the present speed, so
the quadratic thrust and drag terms cancel and ``dv/dt`` is linear;
* governed - the shaft holds the steady revolutions of the order
(Riccati ``a0 - a1 v - a2 v^2``).
Returns ``(speed, shaft_rps, braking)``.
"""
mass_eff = model.effective_mass_kg(mass_kg)
n_target = model.steady_rps(target)
c = model.rpm_per_mps / 60.0
delta = model.load_up_rps
remaining = dt
v = max(0.0, v0)
governed = False
for _ in range(4):
if remaining <= 0.0:
break
if not governed and v > target + brake_margin:
a0 = -(model.brake_thrust_n + extra_resistance) / mass_eff
a2 = model.drag_k / mass_eff
t_hit = riccati_time_to(v, target + brake_margin, a0, 0.0, a2)
if t_hit >= remaining:
return max(0.0, riccati_step(v, a0, 0.0, a2, remaining)), 0.0, True
v = target + brake_margin
remaining -= t_hit
governed = True
continue
n_free = c * v + delta
if not governed and n_target > n_free:
alpha = (model.thrust_k * delta * delta - extra_resistance) / mass_eff
beta = (2.0 * model.thrust_k * c - model.thrust_b) * delta / mass_eff
v_switch = (n_target - delta) / c
t_hit = _exp_linear_time_to(v, v_switch, alpha, beta)
if t_hit >= remaining:
v = _exp_linear_step(v, alpha, beta, remaining)
return max(0.0, v), c * v + delta, False
v = v_switch
remaining -= t_hit
governed = True
continue
a0 = (model.thrust_k * n_target * n_target - extra_resistance) / mass_eff
a1 = model.thrust_b * n_target / mass_eff
a2 = model.drag_k / mass_eff
v = riccati_step(v, a0, a1, a2, remaining)
remaining = 0.0
return max(0.0, v), n_target, False
def _time_to_fraction(model: HullModel, mass_kg: float, start: float,
target: float, fraction_of: float, rising: bool,
limit_s: float = 3600.0) -> float:
"""Exact-ish time until speed crosses ``fraction_of`` (bisection)."""
def speed_at(t):
return surge_step(model, start, target, mass_kg, t)[0]
low, high = 0.0, limit_s
for _ in range(80):
mid = 0.5 * (low + high)
reached = speed_at(mid) >= fraction_of if rising else \
speed_at(mid) <= fraction_of
if reached:
high = mid
else:
low = mid
return high
def calibrate(data: dict | None = None) -> HullModel:
"""Solve model constants so the 1.0.0 gameplay references hold."""
data = data or load_hull_data()
orders = dict(config.TELEGRAPH_ORDERS)
v_max = config.SHIP_SPEED_MAX_KN * KN
power_w = data["max_brake_power_kw"] * 1000.0
eta = data["propulsive_efficiency"]
drag_k = power_w * eta / v_max ** 3
diameter = data["propeller_diameter_m"]
j0 = data["propeller_zero_thrust_advance_ratio"]
j_flank = data["flank_advance_ratio"]
rps_flank = v_max / (j_flank * diameter)
# Linear K_T(J): T = K n^2 (1 - J/J0) = K n^2 - (K/(D J0)) n v; steady at
# flank solves K.
thrust_k = drag_k * v_max ** 2 / (rps_flank ** 2 * (1.0 - j_flank / j0))
thrust_b = thrust_k / (diameter * j0)
rpm_per_mps = rps_flank * 60.0 / v_max
mass_design = data["displacement_t"] * 1000.0
waterplane = (data["waterplane_coefficient"] * data["length_m"]
* data["beam_m"])
screw = diameter * j0
base = dict(
mass_design_kg=mass_design,
added_mass_ratio=data["surge_added_mass_ratio"], drag_k=drag_k,
thrust_k=thrust_k, thrust_b=thrust_b, brake_thrust_n=1.0,
load_up_rps=0.1,
rpm_per_mps=rpm_per_mps, diameter_m=diameter,
shaft_immersion_m=data["shaft_immersion_m"], cavitation_sigma=0.0,
sfc_kg_per_j=0.0, propulsive_efficiency=eta, pitch_screw_m=screw, nomoto_k=1.0,
nomoto_t_s=config.SHIP_YAW_RESPONSE_S, length_m=data["length_m"],
beam_m=data["beam_m"], draft_m=data["draft_m"],
block_coefficient=data["block_coefficient"],
waterplane_area_m2=waterplane, gm_m=data["metacentric_height_m"],
turn_heel_lever_m=data["turn_heel_lever_m"],
roll_omega=2.0 * math.pi / data["roll_period_s"],
roll_zeta=data["roll_damping_ratio"],
stabilizer_zeta=data["stabilizer_damping_ratio"],
stabilizer_full_mps=data["stabilizer_full_speed_kn"] * KN,
pitch_omega=2.0 * math.pi / data["pitch_period_s"],
pitch_zeta=data["pitch_damping_ratio"],
flood_kg_per_percent=data["flood_mass_t_per_percent"] * 1000.0,
idle_rpm=data["idle_rpm"], wake_sample_s=data["wake_sample_s"],
wake_max_points=int(data["wake_max_points"]),
wake_decay_s=data["wake_decay_s"])
def with_(**changes):
values = dict(base)
values.update(changes)
return HullModel(**values)
# Load-up programme: time to 90 % of FULL from rest equals the 1.0.0
# reference SHIP_SPEED_TAU_S * ln 10.
v_full = orders["FULL"] * KN
t90_target = config.SHIP_SPEED_TAU_S * math.log(10.0)
low, high = 1e-4, rps_flank
for _ in range(80):
mid = 0.5 * (low + high)
model = with_(load_up_rps=mid)
t90 = _time_to_fraction(model, mass_design, 0.0, v_full, 0.9 * v_full,
True)
if t90 > t90_target:
low = mid
else:
high = mid
base["load_up_rps"] = 0.5 * (low + high)
# Braking thrust: STOP from FULL to 10 % in the same reference time.
low, high = 1.0, 20.0 * drag_k * v_max ** 2
for _ in range(80):
mid = 0.5 * (low + high)
model = with_(brake_thrust_n=mid)
t10 = _time_to_fraction(model, mass_design, v_full, 0.0, 0.1 * v_full,
False)
if t10 > t90_target:
low = mid
else:
high = mid
brake = 0.5 * (low + high)
base["brake_thrust_n"] = min(
brake, data["brake_thrust_limit_fraction"] * drag_k * v_max ** 2)
# Cavitation onset at CAVITATION_KN in calm water.
v_cav = config.CAVITATION_KN * KN
model = with_()
base["cavitation_sigma"] = model.cavitation_number(
model.steady_rps(v_cav), v_cav, data["shaft_immersion_m"])
# Fuel: steady FLANK burns the 1.0.0 propulsion allowance.
model = with_()
flank_power = model.shaft_power_w(drag_k * v_max ** 2, rps_flank)
base["sfc_kg_per_j"] = (config.SHIP_FUEL_MAX_PROPULSION_KG_H / 3600.0
/ flank_power)
# Nomoto gain: steady turn at FULL with full rudder equals the 1.0.0
# reference (max yaw rate x the capped speed factor).
reference_yaw = math.radians(config.SHIP_MAX_YAW_RATE_DEG_PER_S * 1.5)
base["nomoto_k"] = reference_yaw * data["length_m"] / (
v_full * math.radians(config.SHIP_MAX_RUDDER_DEG))
return HullModel(**base)
HULL = calibrate()
# --- seakeeping --------------------------------------------------------------
@functools.lru_cache(maxsize=64)
def _wave_components(seed: int, hs_key: float) -> tuple[tuple[float, float, float], ...]:
"""(omega, slope amplitude, phase) of the discretized PM spectrum."""
hs = hs_key
omega_p = 2.0 * math.pi / (4.2 * math.sqrt(hs) + 1.0)
lo, hi = 0.6 * omega_p, 2.2 * omega_p
step = (hi - lo) / WAVE_COMPONENTS
parts = []
for index in range(WAVE_COMPONENTS):
omega = lo + (index + 0.5) * step
spectrum = (5.0 / 16.0) * hs * hs * omega_p ** 4 * omega ** -5 \
* math.exp(-1.25 * (omega_p / omega) ** 4)
amplitude = math.sqrt(2.0 * spectrum * step)
# Wave slope amplitude k a with deep-water dispersion k = w^2/g.
parts.append((omega, (omega * omega / G) * amplitude,
detrand.phase(seed, "wave", index)))
return tuple(parts)
def wave_slope_rad(seed: int, clock_s: float, sea_state: float) -> float:
"""Effective wave slope from a Pierson-Moskowitz sea (8 components)."""
index = max(0.0, min(6.0, sea_state))
low = int(index)
high = min(6, low + 1)
hs = SEA_STATE_HS_M[low] + (SEA_STATE_HS_M[high] - SEA_STATE_HS_M[low]) \
* (index - low)
if hs <= 0.0:
return 0.0
# Quantize the height so the component cache stays small and exact.
parts = _wave_components(int(seed), round(hs, 2))
return sum(amplitude * math.sin(omega * clock_s + phase)
for omega, amplitude, phase in parts)
def turn_heel_rad(model: HullModel, speed_mps: float, yaw_rate_rad: float) -> float:
"""Steady outward heel from the centripetal moment in a turn."""
return (speed_mps * yaw_rate_rad * model.turn_heel_lever_m
/ (G * model.gm_m))
def squat_m(model: HullModel, speed_kn: float, depth_m: float,
draft_m: float) -> float:
"""Barrass squat, fading out as water depth exceeds ~5 draughts."""
if depth_m <= 0.0:
return 0.0
ratio = depth_m / max(draft_m, 0.1)
factor = max(0.0, min(1.0, (5.0 - ratio) / 3.8))
return model.block_coefficient * speed_kn * speed_kn / 100.0 * factor
def hydrostatic_draft_m(model: HullModel, mass_kg: float) -> float:
return model.draft_m + (mass_kg - model.mass_design_kg) / (
RHO_SEA * model.waterplane_area_m2)
# Effective fraction of the local wave slope that excites the hull (a long
# ship averages the slope over its beam/length).
ROLL_WAVE_GAIN = 0.55
PITCH_WAVE_GAIN = 0.35
SEAKEEPING_SUBSTEP_S = 0.05
def seakeeping_step(model: HullModel, roll_deg: float, roll_rate: float,
pitch_deg: float, pitch_rate: float, *, dt: float,
clock_s: float, seed: int, sea_state: float,
wave_relative_deg: float, speed_mps: float,
yaw_rate_rad: float, list_deg: float,
stabilizers: bool) -> tuple[float, float, float, float]:
"""Integrate 1-DOF roll and pitch oscillators (semi-implicit Euler).
Roll is driven toward the instantaneous equilibrium of wave slope (beam
component), steady turn heel and damage list; active fin stabilizers add
speed-dependent damping. Pitch follows the head/following-sea slope.
"""
steps = max(1, math.ceil(dt / SEAKEEPING_SUBSTEP_S - 1e-9))
h = dt / steps
rel = math.radians(wave_relative_deg)
beam = abs(math.sin(rel))
head = abs(math.cos(rel))
heel = math.degrees(turn_heel_rad(model, speed_mps, yaw_rate_rad))
zeta_roll = model.roll_zeta
if stabilizers:
zeta_roll += model.stabilizer_zeta * min(
1.0, (speed_mps / model.stabilizer_full_mps) ** 2)
w_r, w_p = model.roll_omega, model.pitch_omega
for index in range(steps):
t = clock_s + (index + 1) * h
slope = math.degrees(wave_slope_rad(seed, t, sea_state))
slope_p = math.degrees(wave_slope_rad(seed + 7919, t, sea_state))
roll_eq = ROLL_WAVE_GAIN * beam * slope + heel + list_deg
pitch_eq = PITCH_WAVE_GAIN * head * slope_p
roll_rate += h * (-2.0 * zeta_roll * w_r * roll_rate
- w_r * w_r * (roll_deg - roll_eq))
roll_deg += h * roll_rate
pitch_rate += h * (-2.0 * model.pitch_zeta * w_p * pitch_rate
- w_p * w_p * (pitch_deg - pitch_eq))
pitch_deg += h * pitch_rate
return roll_deg, roll_rate, pitch_deg, pitch_rate
+169 -46
View File
@@ -1,10 +1,14 @@
"""Fregatte-Modell: Position, Kurs, Geschwindigkeit, Lärmpegel."""
import dataclasses
import math
from src.core import config
from src.physics import ship_dynamics as dyn
from src.world.grounding import DEFAULT_HULL_SPEC, HullSpec
KN = dyn.KN
class Ship:
def __init__(self, x_nm: float, y_nm: float, course_deg: float = 0.0,
@@ -31,7 +35,16 @@ class Ship:
self.last_impact_speed_kn = 0.0
self.roll = 0.0
self.pitch = 0.0
self.roll_rate = 0.0
self.pitch_rate = 0.0
self._clock = 0.0
# Derived each tick from damage control (not saved state).
self.flood_percent = 0.0
self.steering_jammed = False
self.stabilizers_ok = True
self.sea_state = 0.0
# Wake ring: [x_nm, y_nm, clock_s, speed_kn], newest last.
self.wake: list[list[float]] = []
# --- Steuerung (dt = reelle Sekunden, turn_dir/speed_dir in -1/0/+1) ---
@@ -74,26 +87,76 @@ class Ship:
def grounded(self) -> bool:
return self.grounding_latched
# --- propulsion state (pure functions of the saved state) -------------
def effective_target_kn(self) -> float:
target = min(self.target_speed, self.speed_cap,
12.0 if self.quiet_mode else self.speed_cap)
if self.fuel_kg <= 0.0 or (self.grounding_latched and not self.astern):
return 0.0
return max(0.0, target)
def mass_kg(self) -> float:
"""Displacement: design load less burnt fuel plus floodwater."""
hull = dyn.HULL
return (hull.mass_design_kg - (self.fuel_capacity_kg - self.fuel_kg)
+ hull.flood_kg_per_percent * max(0.0, self.flood_percent))
def _propulsion(self) -> tuple[float, float, bool]:
"""(shaft rev/s, thrust N, braking) for the current state."""
hull = dyn.HULL
target = self.effective_target_kn() * KN
v = self.speed * KN
if v > target + 0.15:
return 0.0, hull.brake_thrust_n, True
c = hull.rpm_per_mps / 60.0
rps = min(hull.steady_rps(target), c * v + hull.load_up_rps)
return rps, hull.thrust_n(rps, v), False
@property
def shaft_immersion_m(self) -> float:
"""Propeller depth; a bow-down pitch lifts the stern screws."""
hull = dyn.HULL
return hull.shaft_immersion_m + 0.5 * hull.length_m * math.sin(
math.radians(self.pitch))
@property
def cavitating(self) -> bool:
"""M10: Schraubenkavitation (ab CAVITATION_KN deutlich lauter)."""
return self.speed >= config.CAVITATION_KN
"""Blade-tip cavitation from the cavitation number (sigma).
Calibrated to start at CAVITATION_KN in calm water; heavy pitching
that lifts the propellers makes it start earlier."""
if self.fuel_kg <= 0.0:
return False
rps, _thrust, braking = self._propulsion()
if braking:
rps = dyn.HULL.steady_rps(self.speed * KN)
sigma = dyn.HULL.cavitation_number(rps, self.speed * KN,
self.shaft_immersion_m)
return sigma <= dyn.HULL.cavitation_sigma + 1e-12
def rpm(self) -> float:
"""M10: Wellendrehzahl für die Maschinenraum-Anzeige."""
"""Shaft revolutions for the engine-room display."""
if self.fuel_kg <= 0.0:
return 0.0
return config.SHIP_RPM_MIN + self.speed * config.SHIP_RPM_PER_KN
rps, _thrust, braking = self._propulsion()
return max(dyn.HULL.idle_rpm, 0.0 if braking else rps * 60.0)
@staticmethod
def max_rpm() -> float:
return dyn.HULL.steady_rps(config.SHIP_SPEED_MAX_KN * KN) * 60.0
def fuel_burn_kg_h(self) -> float:
"""Current hotel plus propulsion consumption for the ordered load."""
"""Hotel load plus fuel for the power the propellers deliver now."""
if self.fuel_kg <= 0.0:
return 0.0
ordered_speed = min(
self.target_speed, self.speed_cap,
12.0 if self.quiet_mode else self.speed_cap)
load = config.clamp(ordered_speed / config.SHIP_SPEED_MAX_KN, 0.0, 1.0)
propulsion = config.SHIP_FUEL_MAX_PROPULSION_KG_H * load ** 3
hull = dyn.HULL
rps, thrust, braking = self._propulsion()
if braking:
power = thrust * max(self.speed * KN, 1.0) / hull.propulsive_efficiency
else:
power = hull.shaft_power_w(max(0.0, thrust), rps)
propulsion = hull.sfc_kg_per_j * power * 3600.0
if self.astern:
propulsion *= config.SHIP_FUEL_ASTERN_FACTOR
return config.SHIP_FUEL_HOTEL_KG_H + propulsion
@@ -126,40 +189,43 @@ class Ship:
"""
start_pose = (self.x, self.y, self.course)
# Kurs: Ruder, Giergeschwindigkeit und Kurs bauen sich nacheinander auf.
hull = dyn.HULL
if world is not None:
self.sea_state = float(getattr(world, "effective_sea_state",
getattr(world, "sea_state", 0.0)))
# Steering: the rudder slews toward the autopilot order unless the
# steering gear is disabled; yaw follows the first-order Nomoto model
# r_ss = K (V/L) delta, so the turning circle is nearly speed
# independent and a stopped ship does not turn.
diff = config.angle_diff_deg(self.target_course, self.course)
desired_rudder = config.clamp(
diff * 0.75 - self.yaw_rate * config.SHIP_YAW_DAMPING,
-config.SHIP_MAX_RUDDER_DEG, config.SHIP_MAX_RUDDER_DEG)
rudder_step = config.SHIP_RUDDER_RATE_DEG_PER_S * self.turn_rate_scale * dt
self.rudder_angle += config.clamp(
desired_rudder - self.rudder_angle, -rudder_step, rudder_step)
# W2: Ruderwirkung skaliert mit Staudruck (~v^2), nicht linear -
# ein liegen gebliebenes Schiff hat kaum Anstroemung am Ruderblatt.
speed_factor = config.clamp((self.speed / 10.0) ** 2, 0.0, 1.5)
max_yaw = config.SHIP_MAX_YAW_RATE_DEG_PER_S * speed_factor \
* self.turn_rate_scale
# Scaled by speed_factor too: a stopped ship has no flow over the
# rudder/hull, so a list alone should not spin it in place.
desired_yaw = ((self.rudder_angle / config.SHIP_MAX_RUDDER_DEG) * max_yaw
+ list_bias_deg * config.SHIP_LIST_YAW_GAIN * speed_factor)
yaw_step = max_yaw * dt / config.SHIP_YAW_RESPONSE_S if max_yaw else dt
self.yaw_rate += config.clamp(desired_yaw - self.yaw_rate,
-yaw_step, yaw_step)
if not self.steering_jammed:
rudder_step = config.SHIP_RUDDER_RATE_DEG_PER_S * self.turn_rate_scale * dt
self.rudder_angle += config.clamp(
desired_rudder - self.rudder_angle, -rudder_step, rudder_step)
v_mps = self.speed * KN
steady_yaw = math.degrees(
hull.nomoto_k * (v_mps / hull.length_m)
* math.radians(self.rudder_angle)) * self.turn_rate_scale
# Damage list pulls the bow toward the low side, again scaled by
# the flow past the hull (no spin in place).
steady_yaw += list_bias_deg * config.SHIP_LIST_YAW_GAIN * min(
1.5, self.speed / 10.0)
tau = config.clamp(hull.nomoto_t_s * (config.TELEGRAPH_ORDERS[3][1] * KN)
/ max(v_mps, 0.5), config.SHIP_YAW_RESPONSE_S * 0.5,
config.SHIP_YAW_RESPONSE_S * 6.0)
self.yaw_rate = steady_yaw + (self.yaw_rate - steady_yaw) * math.exp(-dt / tau)
self.course = (self.course + self.yaw_rate * dt) % 360.0
# Geschwindigkeit: Schub/Widerstand-Gleichgewicht als Exponential-Verzug
# (geschlossene Form -> dt-unabhaengig: ein Aufruf mit grossem dt liefert
# exakt dasselbe Ergebnis wie viele kleine Teilschritte).
effective_target = min(self.target_speed, self.speed_cap,
12.0 if self.quiet_mode else self.speed_cap)
if self.grounding_latched and not self.astern:
effective_target = 0.0
if abs(effective_target - self.speed) <= 0.05:
self.speed = effective_target
else:
self.speed = effective_target + (self.speed - effective_target) \
* math.exp(-dt / config.SHIP_SPEED_TAU_S)
# Surge: thrust against resistance (exact Riccati integration).
effective_target = self.effective_target_kn()
extra = hull.added_resistance_n(self.sea_state)
speed_mps, _rps, _braking = dyn.surge_step(
hull, self.speed * KN, effective_target * KN, self.mass_kg(), dt,
extra_resistance=extra)
self.speed = min(config.SHIP_SPEED_MAX_KN, speed_mps / KN)
# Physikalische Bewegung (W3: Land-Rueckstoss)
# Nautisch: 0° = Nord/-y, 90° = Ost/+x (konsistent zu Peilungen)
@@ -173,9 +239,50 @@ class Ship:
nx += config.kn_to_nm_per_s(cu) * dt
ny -= config.kn_to_nm_per_s(cv) * dt
contact = self._advance(start_pose, nx, ny, world)
self._update_roll_pitch(dt, world)
self._update_roll_pitch(dt, world, list_bias_deg)
self._update_wake(dt)
return contact
# --- sinkage ---------------------------------------------------------------
def dynamic_draft_m(self, water_depth_m: float | None = None) -> float:
"""Hydrostatic draft from displacement plus squat in shallow water."""
hull = dyn.HULL
draft = dyn.hydrostatic_draft_m(hull, self.mass_kg())
if water_depth_m is not None:
draft += dyn.squat_m(hull, self.speed, water_depth_m, draft)
return draft
@property
def trim_deg(self) -> float:
"""Dynamic trim by the stern, growing with Froude number squared."""
froude = self.speed * KN / math.sqrt(dyn.G * dyn.HULL.length_m)
return 1.2 * froude * froude
# --- wake ----------------------------------------------------------------
def _update_wake(self, dt: float) -> None:
hull = dyn.HULL
last = self.wake[-1][2] if self.wake else -1e9
if self.speed >= 3.0 and self._clock - last >= hull.wake_sample_s:
self.wake.append([self.x, self.y, self._clock, self.speed])
del self.wake[:-hull.wake_max_points]
cutoff = self._clock - 4.0 * hull.wake_decay_s
while self.wake and self.wake[0][2] < cutoff:
self.wake.pop(0)
def wake_strength_at(self, x_nm: float, y_nm: float,
radius_nm: float = 0.15) -> float:
"""0..1 bubble density of the own wake near a point."""
hull = dyn.HULL
decay = hull.wake_decay_s / (1.0 + 0.25 * self.sea_state)
best = 0.0
for px, py, t, speed in self.wake:
if math.hypot(px - x_nm, py - y_nm) <= radius_nm:
best = max(best, (speed / config.SHIP_SPEED_MAX_KN)
* math.exp(-(self._clock - t) / decay))
return min(1.0, best)
def _advance(self, start_pose, nx: float, ny: float, world):
"""Advance to the first safe swept pose and latch physical contact."""
if world is None:
@@ -186,8 +293,13 @@ class Ship:
self.x, self.y, self.course = self.last_safe_pose
self.speed = 0.0
return None
depth_query = getattr(world, "depth_m", None)
hull = self.hull_spec
if depth_query is not None:
draft = self.dynamic_draft_m(depth_query(start_pose[0], start_pose[1]))
hull = dataclasses.replace(self.hull_spec, draft_m=max(0.5, draft))
result = world.swept_grounding(
start_pose, (nx, ny, self.course), self.hull_spec)
start_pose, (nx, ny, self.course), hull)
self.x, self.y, self.course = (result.safe_x_nm, result.safe_y_nm,
result.safe_course_deg)
self.last_safe_pose = (self.x, self.y, self.course)
@@ -207,13 +319,19 @@ class Ship:
# --- M10: Roll/Pitch aus Seegang + Fahrt (Anzeige) ---
def _update_roll_pitch(self, dt: float, world) -> None:
sea = (getattr(world, "effective_sea_state", world.sea_state)
if world is not None else 0)
amp = 0.4 + 0.30 * sea + 0.02 * self.speed
def _update_roll_pitch(self, dt: float, world, list_deg: float = 0.0) -> None:
wind_from = float(getattr(world, "wind_from_deg", 0.0)) if world else 0.0
seed = int(getattr(getattr(world, "ocean", None), "seed", 0)) if world else 0
start = self._clock
self._clock += dt
self.roll = amp * math.sin(self._clock * 0.23)
self.pitch = amp * 0.7 * math.sin(self._clock * 0.31 + 1.3)
(self.roll, self.roll_rate, self.pitch,
self.pitch_rate) = dyn.seakeeping_step(
dyn.HULL, self.roll, self.roll_rate, self.pitch, self.pitch_rate,
dt=dt, clock_s=start, seed=seed, sea_state=self.sea_state,
wave_relative_deg=wind_from - self.course,
speed_mps=self.speed * KN,
yaw_rate_rad=math.radians(self.yaw_rate), list_deg=list_deg,
stabilizers=self.stabilizers_ok)
# --- Akustik (vereinfacht, Captain's Log §1.1) ---
@@ -255,6 +373,11 @@ class Ship:
def time_to_course_s(self) -> float:
return abs(self.course_error_deg) / max(abs(self.yaw_rate), 0.05)
@property
def heel_deg(self) -> float:
return math.degrees(dyn.turn_heel_rad(
dyn.HULL, self.speed * KN, math.radians(self.yaw_rate)))
@property
def turn_radius_nm(self) -> float:
omega = abs(math.radians(self.yaw_rate))
+2 -1
View File
@@ -15,6 +15,7 @@ from src.core import config
from src.core.i18n import display_value, localized, localize, message as structured_message
from src.core.station import Station
from src.ship.damage import COMPARTMENTS
from src.ship.ship import Ship
from src.sensors.esm import animated_signal_fingerprint, spectrum_band
from src.ui import layout
from src.ui import nato_symbols
@@ -1846,7 +1847,7 @@ def draw_engine_view(game, tr=None) -> None:
label_w=140, size=20)
py += 40
bar_w = int(pw * 0.72)
max_rpm = config.SHIP_RPM_MIN + config.SHIP_SPEED_MAX_KN * config.SHIP_RPM_PER_KN
max_rpm = Ship.max_rpm()
frac = min(1.0, ship.rpm() / max_rpm)
pygame.draw.rect(s, config.COLOR_GRID, (px, py, bar_w, 16))
pygame.draw.rect(s, config.COLOR_TEXT, (px, py, int(bar_w * frac), 16))
+22 -1
View File
@@ -1 +1,22 @@
{}
{
"ship.rpm_eq.FLANK": {
"phase": 2,
"reason": "Phase 2: shaft revolutions now follow a fixed-pitch propeller with a linear K_T(J) curve (steady rpm proportional to speed, 146 rpm at 25 kn). The 1.0.0 values were a cosmetic 20 + 2.4*v display line that is not physically consistent with a 4.2 m propeller.",
"value": 145.8176
},
"ship.rpm_eq.FULL": {
"phase": 2,
"reason": "Phase 2: shaft revolutions now follow a fixed-pitch propeller with a linear K_T(J) curve (steady rpm proportional to speed, 146 rpm at 25 kn). The 1.0.0 values were a cosmetic 20 + 2.4*v display line that is not physically consistent with a 4.2 m propeller.",
"value": 93.3233
},
"ship.rpm_eq.HALF": {
"phase": 2,
"reason": "Phase 2: shaft revolutions now follow a fixed-pitch propeller with a linear K_T(J) curve (steady rpm proportional to speed, 146 rpm at 25 kn). The 1.0.0 values were a cosmetic 20 + 2.4*v display line that is not physically consistent with a 4.2 m propeller.",
"value": 58.327
},
"ship.yaw_steady_deg_s.HALF": {
"phase": 2,
"reason": "Phase 2: first-order Nomoto steering, r = K (V/L) delta, makes the steady turn rate linear in speed, so the turning circle is nearly constant; calibrated at FULL (1.2 deg/s), HALF becomes 0.75 deg/s.",
"value": 0.75
}
}
+10 -3
View File
@@ -1,3 +1,4 @@
import pytest
"""Fokustests fuer mathematische ASW-Grundmechaniken."""
import random
@@ -147,13 +148,19 @@ def test_ship_helm_state_survives_save_load():
assert other.ship.yaw_rate == game.ship.yaw_rate
def test_ship_fuel_uses_simulation_time_and_ordered_load():
ship = Ship(0.0, 0.0, speed_kn=12.0)
def test_ship_fuel_uses_simulation_time_and_delivered_power():
ship = Ship(0.0, 0.0, speed_kn=15.0)
ship.target_speed = 15.0
# At steady speed the delivered power is the effective power k v^3 / eta,
# which reproduces the 1.0.0 cubic load law exactly.
expected_burn = (config.SHIP_FUEL_HOTEL_KG_H
+ config.SHIP_FUEL_MAX_PROPULSION_KG_H
* (15.0 / config.SHIP_SPEED_MAX_KN) ** 3)
assert ship.fuel_burn_kg_h() == expected_burn
assert ship.fuel_burn_kg_h() == pytest.approx(expected_burn, rel=1e-9)
accelerating = Ship(0.0, 0.0, speed_kn=8.0)
accelerating.target_speed = 15.0
assert accelerating.fuel_burn_kg_h() > config.SHIP_FUEL_HOTEL_KG_H
expected_burn = ship.fuel_burn_kg_h()
ship.update_fuel(3600.0)
assert abs(ship.fuel_kg - (config.SHIP_FUEL_CAPACITY_KG - expected_burn)) < 1e-9
assert ship.fuel_endurance_h() > 100.0
+1 -1
View File
@@ -23,7 +23,7 @@ CONTACT_NAMES = {
"acoustics.json", "aircraft.json", "animals.json", "civilians.json",
"decoys.json", "sources.json", "subs.json", "torpedoes.json", "warships.json",
}
LOADOUT_NAMES = {"air_defense.json", "ownship.json"}
LOADOUT_NAMES = {"air_defense.json", "ownship.json", "ownship_hull.json"}
CONTACT_ANALYSIS_MANIFEST = json.loads(
(ROOT / "data/contact_analysis/manifest.json").read_text(encoding="utf-8"))
CONTACT_ANALYSIS_NAMES = {
+9 -8
View File
@@ -39,21 +39,22 @@ def test_ship_speed_response_is_dt_agnostic_and_asymptotic():
assert 0.0 < big.speed < 25.0
def test_ship_rudder_authority_scales_quadratically_with_speed():
"""W2: rudder force scales with dynamic pressure (~v^2), not linearly -
doubling speed should roughly quadruple the yaw rate a hard rudder order
builds up to (until the shared max-yaw-rate cap kicks in)."""
def test_ship_turn_rate_scales_linearly_with_speed_nomoto():
"""Phase 2: Nomoto steering r = K (V/L) delta - rudder force grows with
dynamic pressure but so does the hull's yaw damping, so the steady turn
rate doubles with speed and the turning circle stays nearly constant."""
slow = Ship(100.0, 100.0, course_deg=0.0, speed_kn=4.0)
slow.target_speed = 4.0
slow.target_course = 90.0
fast = Ship(100.0, 100.0, course_deg=0.0, speed_kn=8.0)
fast.target_speed = 8.0
fast.target_course = 90.0
for _ in range(20):
slow.update(1.0)
fast.update(1.0)
for _ in range(300):
for ship in (slow, fast):
ship.target_course = (ship.course + 90.0) % 360.0 # hold hard rudder
ship.update(1.0)
assert fast.yaw_rate == pytest.approx(4.0 * slow.yaw_rate, rel=0.1)
assert fast.yaw_rate == pytest.approx(2.0 * slow.yaw_rate, rel=0.02)
def test_ship_drifts_with_ocean_current_when_stopped():
+199
View File
@@ -0,0 +1,199 @@
"""Phase 2: force-based own-ship hydrodynamics."""
import copy
import json
import math
from types import SimpleNamespace
import pytest
from src.core import config
from src.core.game import Game
from src.physics import ship_dynamics as dyn
from src.ship.ship import Ship
KN = dyn.KN
def _rk4(f, v, dt, steps):
h = dt / steps
for _ in range(steps):
k1 = f(v)
k2 = f(v + .5 * h * k1)
k3 = f(v + .5 * h * k2)
k4 = f(v + h * k3)
v += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
return v
@pytest.mark.parametrize("a0,a1,a2,v0", [
(0.5, 0.02, 0.01, 0.0), (0.5, 0.02, 0.01, 9.0), (-0.3, 0.0, 0.01, 8.0),
(0.0, 0.0, 0.02, 5.0)])
def test_riccati_step_matches_numerical_integration(a0, a1, a2, v0):
exact = dyn.riccati_step(v0, a0, a1, a2, 12.0)
numeric = _rk4(lambda v: a0 - a1 * v - a2 * v * v, v0, 12.0, 4000)
assert exact == pytest.approx(numeric, rel=1e-7, abs=1e-9)
def test_surge_is_step_size_invariant_across_regimes():
hull = dyn.HULL
mass = hull.mass_design_kg
for start, target in ((0.0, 25.0), (25.0, 0.0), (16.0, 6.0), (6.0, 16.0)):
big = dyn.surge_step(hull, start * KN, target * KN, mass, 150.0)[0]
small = start * KN
for _ in range(1500):
small = dyn.surge_step(hull, small, target * KN, mass, 0.1)[0]
assert big == pytest.approx(small, abs=1e-9)
@pytest.mark.parametrize("order,speed", config.TELEGRAPH_ORDERS)
def test_every_telegraph_order_reaches_its_calibrated_speed(order, speed):
ship = Ship(0.0, 0.0, speed_kn=0.0)
ship.target_speed = speed
ship.update(1200.0)
assert ship.speed == pytest.approx(speed, abs=0.02)
def test_heavier_ship_accelerates_slower_and_sits_deeper():
light = Ship(0.0, 0.0, speed_kn=0.0)
heavy = Ship(0.0, 0.0, speed_kn=0.0)
heavy.flood_percent = 200.0
light.fuel_kg = 100_000.0
for ship in (light, heavy):
ship.target_speed = 16.0
ship.update(60.0)
assert light.speed > heavy.speed
assert heavy.dynamic_draft_m() > dyn.HULL.draft_m > light.dynamic_draft_m()
def test_added_resistance_in_heavy_sea_costs_speed():
calm = Ship(0.0, 0.0, speed_kn=16.0)
rough = Ship(0.0, 0.0, speed_kn=16.0)
world = SimpleNamespace(effective_sea_state=6.0, sea_state=6,
wind_from_deg=0.0, ocean=SimpleNamespace(seed=1),
current_vec=lambda x, y: (0.0, 0.0),
depth_m=lambda x, y: 4000.0,
swept_grounding=lambda start, end, hull: SimpleNamespace(
safe_x_nm=end[0], safe_y_nm=end[1],
safe_course_deg=end[2], contacted=False,
contact=None))
calm.target_speed = rough.target_speed = 16.0
calm.update(1200.0)
rough.update(1200.0, world)
assert calm.speed == pytest.approx(16.0, abs=0.01)
assert 13.0 < rough.speed < 15.8
def test_cavitation_onset_is_calibrated_and_earlier_when_stern_lifts():
below = Ship(0.0, 0.0, speed_kn=14.9)
below.target_speed = 14.9
at = Ship(0.0, 0.0, speed_kn=15.0)
at.target_speed = 15.0
assert not below.cavitating and at.cavitating
pitched = Ship(0.0, 0.0, speed_kn=13.5)
pitched.target_speed = 13.5
assert not pitched.cavitating
pitched.pitch = -3.0 # bow down: screws rise toward the surface
assert pitched.cavitating
def test_squat_deepens_draft_in_shallow_water_and_feeds_grounding():
ship = Ship(0.0, 0.0, speed_kn=25.0)
assert ship.dynamic_draft_m(11.0) - ship.dynamic_draft_m() > 2.0
assert ship.dynamic_draft_m(2000.0) == pytest.approx(ship.dynamic_draft_m())
slow = Ship(0.0, 0.0, speed_kn=4.0)
assert slow.dynamic_draft_m(11.0) - slow.dynamic_draft_m() < 0.2
seen = {}
def swept(start, end, hull):
seen["draft"] = hull.draft_m
return SimpleNamespace(safe_x_nm=end[0], safe_y_nm=end[1],
safe_course_deg=end[2], contacted=False,
contact=None)
world = SimpleNamespace(depth_m=lambda x, y: 11.0, swept_grounding=swept,
effective_sea_state=0.0, sea_state=0,
wind_from_deg=0.0, current_vec=lambda x, y: (0, 0))
ship.target_speed = 25.0
ship.update(1.0, world)
assert seen["draft"] > dyn.HULL.draft_m + 2.0
assert ship.hull_spec.draft_m == dyn.HULL.draft_m # saved spec unchanged
def test_jammed_steering_gear_holds_the_rudder_and_keeps_turning():
ship = Ship(0.0, 0.0, speed_kn=16.0)
ship.target_speed = 16.0
ship.rudder_angle = 15.0
ship.steering_jammed = True
ship.target_course = 0.0
for _ in range(120):
ship.update(1.0)
assert ship.rudder_angle == 15.0
assert ship.yaw_rate > 0.3
def test_stabilizers_damp_roll_and_turn_heels_outward():
world = SimpleNamespace(wind_from_deg=90.0, ocean=SimpleNamespace(seed=5))
def peak(stabilized):
ship = Ship(0.0, 0.0, speed_kn=18.0)
ship.stabilizers_ok = stabilized
ship.sea_state = 6.0
values = []
for _ in range(4000):
ship._update_roll_pitch(0.05, world)
values.append(abs(ship.roll))
return max(values[800:])
assert peak(True) < 0.8 * peak(False)
turning = Ship(0.0, 0.0, speed_kn=25.0)
turning.yaw_rate = 1.5
assert turning.heel_deg > 1.0
def test_wake_is_bounded_decays_and_round_trips():
ship = Ship(100.0, 100.0, speed_kn=20.0)
ship.target_speed = 20.0
for _ in range(700):
ship.update(1.0)
assert 0 < len(ship.wake) <= dyn.HULL.wake_max_points
newest = ship.wake[-1]
assert ship.wake_strength_at(newest[0], newest[1]) > 0.3
assert ship.wake_strength_at(ship.x + 30, ship.y) == 0.0
oldest = ship.wake[0]
assert ship.wake_strength_at(oldest[0], oldest[1], 0.01) < \
ship.wake_strength_at(newest[0], newest[1], 0.01)
game = Game(seed=2201, start_menu=False, audio_enabled=False)
game.ship.speed = game.ship.target_speed = 20.0
for _ in range(30):
game.update(1.0)
game.ship.roll_rate = 0.7
state = json.loads(json.dumps(game.save_state()))
assert state["ship"]["wake"]
restored = Game(seed=1, start_menu=False, audio_enabled=False)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.ship.wake == game.ship.wake
assert restored.ship.roll_rate == 0.7
for _ in range(20):
game.update(0.5)
restored.update(0.5)
assert restored.save_state()["ship"] == game.save_state()["ship"]
for mutation in (lambda s: s.update(roll_rate=1e6),
lambda s: s["wake"].append([0.0, 0.0, 1e13, 5.0]),
lambda s: s.update(wake=[[0, 0, 0]])):
broken = copy.deepcopy(state)
mutation(broken["ship"])
assert not restored._load_save_data(broken)
def test_steady_fuel_matches_cubic_reference_and_braking_uses_power():
for speed in (6.0, 16.0, 25.0):
ship = Ship(0.0, 0.0, speed_kn=speed)
ship.target_speed = speed
expected = (config.SHIP_FUEL_HOTEL_KG_H
+ config.SHIP_FUEL_MAX_PROPULSION_KG_H
* (speed / config.SHIP_SPEED_MAX_KN) ** 3)
assert ship.fuel_burn_kg_h() == pytest.approx(expected, rel=1e-6)
braking = Ship(0.0, 0.0, speed_kn=16.0)
braking.target_speed = 0.0
assert braking.fuel_burn_kg_h() > config.SHIP_FUEL_HOTEL_KG_H
assert math.isclose(braking.rpm(), dyn.HULL.idle_rpm)