Phase 8: torpedo physics

Add src/physics/torpedo_dyn.py and apply it to both torpedo classes:
- Energy store in cruise seconds with power ~ v^3 (range emerges, longer
  when throttled); an empty battery stops the motor, the weapon coasts
  against quadratic drag and is lost below 30 % speed.
- Constant turning radius (turn rate ~ speed); fin-limited depth control
  with a saved vertical rate (hostile torpedoes gain depth control and rise
  to keel depth when homing).
- Wire: torpedo and ship spools, tension breaks from ship overspeed or hard
  turns held for 5 s; the old timers stay as datalink latency.
- Proximity fuze with shock-factor damage for submarines and ships.
- Speed-dependent propulsor lines and 60 log v source level; boats hear a
  running torpedo through the passive sonar equation (re-anchored at its
  6 NM reference range).
- Shallow hostile torpedoes leave a lookout-visible wake by day; hostile
  torpedoes can home on the own-ship wake; ASROC payloads fly a helix
  search at the splash point.
Manual EN/DE and simulation-gaps updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 17:55:31 +02:00
1 parent 8e6b1d3227
commit ae3991bece
13 files changed
+522 -45

No files matched your search

+5 -1
View File
@@ -64,10 +64,14 @@ Das Hauptquartier schaltet nach dem ersten versenkten feindlichen U-Boot per Fun
- Aus etwa 6-8 sm oder näher schießen: mit 45 kn braucht der Torpedo 8 Minuten für 6 sm, und das U-Boot hört den Abschuss bis 35 sm und weicht aus.
- Das Datum vor ein fahrendes Ziel legen, indem TMA weiterläuft; der Draht folgt der Beobachtung, nicht der Wahrheit.
- Während der Lenkung unter der Kavitationsgrenze bleiben; Kontaktverlust heißt Verlust des Draht-Datums.
- Der Draht ist ein echtes Kabel: er reißt, wenn das Schiff etwa 5 s lang schneller als 20 kn läuft oder schneller als 1,5 Grad/s dreht, wenn die schiffsseitige Spule (5 sm eigener Weg) abgelaufen ist oder wenn der Torpedo das 1,25-fache seiner Reichweite gelaufen ist.
- Die Torpedoreichweite kommt aus der Batterie: bei voller Fahrt läuft er die Katalogreichweite, harte Manöver drosseln ihn und sparen Energie; ist die Batterie leer, läuft er einige Sekunden aus und geht verloren. Direkt nach dem Ausstoß dreht er langsamer (fester Drehkreis), und Tiefenänderungen brauchen einen Moment.
- Der Gefechtskopf hat einen Annäherungszünder: er zündet bei der größten Annäherung innerhalb seines Radius, der Schaden fällt mit dem Abstand (Schockfaktor). Ein knapper Fehlschuss kann ein U-Boot beschädigt entkommen lassen.
- Ein laufender Torpedo wird vom Ziel über die Sonargleichung gehört: leise Boote hören ihn bei ruhiger See auf einige Meilen, Regen und eigene Fahrt überdecken ihn.
- Nur zwei Nixies je Mission: den ersten ausbringen, wenn ein Torpedo wahrscheinlich ist, den zweiten für den nächsten Angriff aufheben.
## Nicht modelliert {#weapons-limits}
- Keine Wasserbomben, U-Jagd-Raketen oder vom Schiff gestartetes ASROC (ASROC nutzen nur befreundete KI-Kriegsschiffe).
- Kein wählbares Torpedo-Suchmuster (Helix, Leiter) und kein manueller Aktivierungspunkt: Schlangensuche und Sucheraktivierung bei 1,2 sm sind fest.
- Kein wählbares Torpedo-Suchmuster und kein manueller Aktivierungspunkt: Schlangensuche und Sucheraktivierung bei 1,2 sm sind fest (befreundete ASROC-Nutzlasten suchen in einer Helix um ihren Eintauchpunkt).
- Ein Torpedotyp für das Schiff und einer für den Helikopter; keine wählbare Salvendoktrin.
+5 -1
View File
@@ -64,10 +64,14 @@ HQ switches to FREE by radio after the first hostile submarine is sunk; the play
- Fire from inside about 6-8 NM: at 45 kn the torpedo needs 8 minutes for 6 NM, and the submarine hears the launch out to 35 NM and starts evading.
- Aim the datum ahead of a moving target by keeping TMA running; the wire follows the observation, not the truth.
- Keep own speed below cavitation while guiding; losing the contact means losing the wire datum.
- The wire is a physical cable: it snaps if the ship runs faster than 20 kn or turns faster than 1.5 deg/s for about 5 s, when the ship-side spool (5 NM of own track) runs out, or when the torpedo has run 1.25 x its range.
- Torpedo range comes from its battery: at full speed it runs the catalogue range, hard manoeuvring throttles it and saves energy; when the battery is empty it coasts for a few seconds and is lost. Turning is slower right after launch (constant turning circle), and depth changes need a moment to build up.
- The warhead has a proximity fuze: it fires at the closest approach inside its radius, and the damage falls with distance (shock factor). A near miss can leave a submarine damaged but able to escape.
- A running torpedo is heard by the target through the sonar equation: quiet boats in calm water hear it from a few miles, rain and their own speed mask it.
- Only two Nixies per mission: stream the first when a torpedo is likely, keep the second for the next attack.
## Not modelled {#weapons-limits}
- No depth charges, ASW rockets or ship-launched ASROC (ASROC is used only by friendly AI warships).
- No selectable torpedo search pattern (helix, ladder) and no manual enable point: the snake search and the 1.2 NM seeker switch-on are fixed.
- No selectable torpedo search pattern and no manual enable point: the snake search and the 1.2 NM seeker switch-on are fixed (friendly ASROC payloads use a helix search at their splash point).
- One torpedo type for the ship and one for the helicopter; no selectable salvo doctrine.
+1 -1
View File
@@ -31,7 +31,7 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| System | Daten |
|---|---|
| Fregattentorpedo | 45 kn, 12 sm, drahtgelenkt, 2 Rohre, 60 s Nachladen, Tiefe 10-300 m |
| Fregattentorpedo | 45 kn, 12 sm (Batterie), drahtgelenkt (Schiff <= 20 kn, <= 1,5 Grad/s, 5 sm Spule), 2 Rohre, 60 s Nachladen, Tiefe 10-300 m, Annäherungszünder |
| Helikoptertorpedo | 55 kn, 12 sm, 2 je Einsatz, ohne Draht |
| Feindtorpedo | 28 kn, 30 sm, zielsuchend ab 3 sm |
| Nixie-Schlepptäuschkörper | 2 je Mission, 600 s, 0,2 sm achteraus, 60 s Nachladen |
+1 -1
View File
@@ -31,7 +31,7 @@ All values are the defaults of the current game version. Custom difficulty and m
| System | Data |
|---|---|
| Frigate torpedo | 45 kn, 12 NM, wire-guided, 2 tubes, 60 s reload, depth 10-300 m |
| Frigate torpedo | 45 kn, 12 NM (battery), wire-guided (ship <= 20 kn, <= 1.5 deg/s, 5 NM spool), 2 tubes, 60 s reload, depth 10-300 m, proximity fuze |
| Helicopter torpedo | 55 kn, 12 NM, 2 per sortie, no wire |
| Hostile torpedo | 28 kn, 30 NM, homes from 3 NM |
| Nixie towed decoy | 2 per mission, 600 s, 0.2 NM astern, 60 s reload |
+10 -10
View File
@@ -157,17 +157,17 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| ~~**No launch dynamics**~~ | **Partially fixed (2026-09).** Torpedoes now spool up from a reduced initial speed to cruise speed over `TORP_SPOOLUP_S` (both player and enemy classes; ASROC water-entry too). Still open: no initial depth offset from ship draft/tube, no water-jet impulse or wake effects. | Initial depth offset; water-jet impulse; wake effects |
| **No acceleration phase** | Constant speed from launch | Motor spool-up (0 → cruise in seconds), speed-dependent range |
| **No depth inertia** | Depth changes at fixed 10 m/s toward target | Buoyancy + plane angle + drag; overshoot; depth hold with oscillation |
| **No hydrodynamic turn limit** | Fixed 8°/s (player), 6°/s (enemy) turn rate; throttle penalty is heuristic | Turn radius from rudder geometry, speed, and depth; cavitation limit on turn |
| **No wire dynamics** | Wire is abstracted as a timer (stale/broken) | Wire payout length limits range; wire drag; wire tension; spool dynamics |
| **No propeller noise model** | Static LOFAR lines from catalog | Speed-dependent blade rate; cavitation at high speed; motor harmonics |
| **Kill is binary** | Distance + depth threshold → instant hit or miss | Warhead proximity fuze with lethal radius; damage proportional to standoff; no partial hits |
| ~~**No launch dynamics**~~ | **Closed (Phases W2 + 6 + 8).** Spool-up, launch-depth offset and tube transient on the firing boat, speed-dependent turning and depth response right after launch. | — |
| ~~**No acceleration phase**~~ | **Closed.** Spool-up (W2) plus an energy store: power ~ v^3, range emerges from the battery and grows when running slower. | — |
| ~~**No depth inertia**~~ | **Closed (Phase 8).** Fin-limited vertical acceleration (~ dynamic pressure) with a proportional depth command (saved rate, small overshoot); hostile torpedoes now have depth control too (run depth, keel depth when homing). | — |
| ~~**No hydrodynamic turn limit**~~ | **Closed (Phase 8).** Constant turning radius: turn rate proportional to speed, for both torpedo classes. | — |
| ~~**No wire dynamics**~~ | **Closed (Phase 8).** Two finite spools (torpedo 1.25 x range, ship 5 NM of own track) and tension breaks from ship overspeed (> 20 kn) or hard turns (> 1.5 deg/s) held for 5 s; the old timers remain as datalink latency. | — |
| ~~**No propeller noise model**~~ | **Closed (Phase 8).** Speed-dependent propulsor lines (both classes) and a 60 log v source level; the target hears a running torpedo through the passive sonar equation (ray excess, ambient, own noise). | — |
| ~~**Kill is binary**~~ | **Closed (Phase 8).** Proximity fuze at closest approach; damage from the shock factor sqrt(W)/R (250 kg), so near misses damage without sinking. | — |
| ~~**No target reaction to torpedo**~~ | **Closed (Phases W2 + 7 + 8).** Launch-transient and homing alerts, crew recognition delay (per-boat lognormal 2-15 s, saved countdown), evasive dive across the layer; Phase 8 makes the running-torpedo notice a sonar-equation detection. | — |
| **No self-destruction timing** | SASE at max range or terrain block; no time-based self-destruct | Motor burn time; battery depletion |
| **No wake / trail signature** | None | Torpedo wake detectable by passive sonar at close range |
| **ASROC payload depth** | Fixed `target_depth_m` from observation (default 60 m) | No depth-keeping logic; no terminal dive |
| ~~**No self-destruction timing**~~ | **Closed (Phase 8).** Battery exhaustion stops the motor; the weapon coasts (dv/dt = -k v^2) and is lost below 30 % speed. | — |
| ~~**No wake / trail signature**~~ | **Closed (Phase 8).** Shallow hostile torpedoes leave a bubble track visible to the lookout by day up to 1.5 NM; hostile torpedoes can home on the own-ship wake. | — |
| ~~**ASROC payload depth**~~ | **Closed (Phase 8).** The payload flies a helix search at its splash point while its depth controller descends to the search depth. | — |
### 4.3 Data structures touched
+83 -4
View File
@@ -37,6 +37,8 @@ from src.core.station import Station
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.sensors.ais import AISReceiver
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.sensors.platform import MAST_DEPTH_M
from src.world.ocean import OceanEnvironment
@@ -243,6 +245,10 @@ _ECO_REFRESH_EVENTS = frozenset(
"WINDOWFOCUSGAINED", "WINDOWFOCUSLOST") if hasattr(pygame, name))
TORPEDO_WAKE_VISIBLE_NM = 1.5
TORPEDO_WAKE_VISIBLE_DEPTH_M = 15.0
class Game:
def __init__(self, seed: int = 42, difficulty: dict = None,
start_menu: bool = False, fullscreen: bool = None,
@@ -3691,6 +3697,16 @@ class Game:
def _update_lookout_picture(self) -> None:
"""Publish bounded visual fixes without correlating sensor identities."""
# A shallow-running torpedo leaves a visible bubble track by day in a
# moderate sea.
if (not self.world.is_night()
and getattr(self.world, "effective_sea_state", self.world.sea_state) <= 3.0):
for torpedo in sorted(self.enemy_torpedoes, key=lambda item: item.id):
if (torpedo.state == "RUN" and torpedo.depth <= TORPEDO_WAKE_VISIBLE_DEPTH_M
and math.hypot(torpedo.x - self.ship.x, torpedo.y - self.ship.y)
<= TORPEDO_WAKE_VISIBLE_NM):
self._lookout_observe(torpedo, "torpedo-wake", "TORP",
TORPEDO_WAKE_VISIBLE_NM, torpedo.id)
for actor in sorted(self.civilians + self.warships,
key=lambda item: item.id):
if not actor.sunk:
@@ -6145,13 +6161,44 @@ class Game:
return "stern"
return "starboard" if relative > 0.0 else "port"
def _sub_hears_torpedo(self, sub, torpedo, distance_nm: float) -> bool:
"""Passive sonar equation for a running torpedo heard by a boat.
The figure of merit reproduces TORP_RUNNING_NOISE_RANGE_NM for a
quiet boat and a torpedo at cruise speed; propagation, ambient noise,
the boat's own noise and the torpedo's speed-dependent level decide."""
if distance_nm > 3.0 * config.TORP_RUNNING_NOISE_RANGE_NM:
return False
frequency = torpedo_dyn.RUNNING_NOISE_BAND_HZ
excess = sonar_propagation.ray_excess_db(
self.world, sub.x, sub.y, max(sub.depth, 1.0), torpedo.x, torpedo.y,
max(torpedo.depth, 1.0), frequency)
absorption = sonar_equation.francois_garrison_db_per_km(frequency)
terms = sonar_equation.passive_terms(
frequency_hz=frequency, distance_nm=max(distance_nm, 0.01),
target_bonus=10.0 ** (torpedo.source_level_offset_db() / 20.0),
excess_path_loss_db=(0.0 if excess is None else excess
- sonar_propagation.ray_reference_excess_db(
config.TORP_RUNNING_NOISE_RANGE_NM, frequency))
# Absorption is part of the reference-range figure of merit too.
- absorption * config.TORP_RUNNING_NOISE_RANGE_NM * 1.852,
absorption_db_per_km=absorption,
legacy_absorption_db=0.0,
own_range_factor=max(0.2, 1.0 - 0.8 * sub.noise_level()),
array_range_factor=(config.TORP_RUNNING_NOISE_RANGE_NM
/ config.SONAR_PASSIVE_BASE_NM),
sea_state=float(getattr(self.world, "effective_sea_state",
self.world.sea_state)),
rain=float(getattr(self.world, "rain_intensity", 0.0)),
shipping_contacts=self.sonar.shipping_contacts)
return terms.signal_excess_db > 0.0
def _update_player_torpedoes(self, dt: float) -> None:
"""Bewegt eigene Torpedos und verarbeitet Treffer/Fehlkontakte."""
for sub in self.subs:
if (sub.sunk or sub.state == "SINKING"
or sub.memory["last_torpedo_age"] < config.SUB_EVADE_DURATION_S):
continue
notice_range = sub.torpedo_notice_range_nm()
for torpedo in self.torpedoes:
if torpedo.state != "RUN":
continue
@@ -6165,7 +6212,7 @@ class Game:
# W2: graduated passive notice of a running torpedo's own
# noise, between pure terminal homing and the loud one-time
# launch transient - additive, does not replace either.
if (dist <= notice_range
if (self._sub_hears_torpedo(sub, torpedo, dist)
and not self.world.sonar_path_blocked(
torpedo.x, torpedo.y, torpedo.depth,
sub.x, sub.y, sub.depth)):
@@ -6178,6 +6225,9 @@ class Game:
if (solution_fresh and contact.observed_x is not None
and contact.observed_y is not None):
torpedo.wire_update(contact.observed_x, contact.observed_y)
if torpedo.launch_origin == "frigate":
torpedo.wire_tension_update(dt, self.ship.speed,
self.ship.yaw_rate)
torpedo.update(dt, seeker_candidates=(
[s for s in self.subs if not s.sunk]
+ [d for d in self.decoys if not d.dead]
@@ -6831,7 +6881,10 @@ class Game:
search_phase=t._search_phase, midcourse=t._midcourse,
midcourse_timer=t._midcourse_timer,
kill_dist_nm=t.kill_dist_nm, kill_depth_m=t.kill_depth_m,
time_since_launch=t.time_since_launch)
time_since_launch=t.time_since_launch,
energy_s=t.energy_s, motor_fraction=t.motor_fraction,
depth_rate=t.depth_rate, wire_ship_out_nm=t.wire_ship_out_nm,
wire_stress_s=t.wire_stress_s)
for t in self.torpedoes],
"enemy_torpedoes": [
dict(id=t.id, x=t.x, y=t.y, course=t.course, depth=t.depth,
@@ -6844,7 +6897,9 @@ class Game:
seeker_target=("ship" if t._seeker_target is self.ship else
f"nixie:{t._seeker_target.seq}"
if t._seeker_target in self.nixies else None),
time_since_launch=t.time_since_launch)
time_since_launch=t.time_since_launch,
energy_s=t.energy_s, motor_fraction=t.motor_fraction,
depth_rate=t.depth_rate, target_depth=t.target_depth)
for t in self.enemy_torpedoes],
"asms": [dict(x=a.x, y=a.y, course=a.course, seq=a.seq,
profile_key=a.profile_key,
@@ -7526,6 +7581,11 @@ class Game:
t._search_phase = td["search_phase"]
t._midcourse = td["midcourse"]
t._midcourse_timer = td["midcourse_timer"]
t.energy_s = td["energy_s"]
t.motor_fraction = td["motor_fraction"]
t.depth_rate = td["depth_rate"]
t.wire_ship_out_nm = td["wire_ship_out_nm"]
t.wire_stress_s = td["wire_stress_s"]
self.torpedoes.append(t)
for ed in data["enemy_torpedoes"]:
enemy_key = ed["profile_key"]
@@ -7542,6 +7602,10 @@ class Game:
self.enemy_torpedoes[-1].id = ed["id"]
self.enemy_torpedoes[-1].terminal_active = ed["terminal_active"]
self.enemy_torpedoes[-1].seeker_acquired = ed["seeker_acquired"]
self.enemy_torpedoes[-1].energy_s = ed["energy_s"]
self.enemy_torpedoes[-1].motor_fraction = ed["motor_fraction"]
self.enemy_torpedoes[-1].depth_rate = ed["depth_rate"]
self.enemy_torpedoes[-1].target_depth = ed["target_depth"]
seeker_target = ed["seeker_target"]
self.enemy_torpedoes[-1]._seeker_target = (
(self.ship if seeker_target == "ship" else
@@ -8801,6 +8865,21 @@ class Game:
return False
if len(asms) + pending_missiles > Game.MAX_SAVED_ASMS:
return False
# Phase 8 torpedo physics state.
for row in torpedoes:
if (not bounded(row.get("energy_s"), 0.0, 1e6)
or not bounded(row.get("motor_fraction"), 0.0, 1.0)
or not bounded(row.get("depth_rate"), -20.0, 20.0)
or not bounded(row.get("wire_ship_out_nm"), 0.0, 1e4)
or not bounded(row.get("wire_stress_s"), 0.0, 1e6)):
return False
for row in data.get("enemy_torpedoes", []):
if (not isinstance(row, dict)
or not bounded(row.get("energy_s"), 0.0, 1e6)
or not bounded(row.get("motor_fraction"), 0.0, 1.0)
or not bounded(row.get("depth_rate"), -20.0, 20.0)
or not bounded(row.get("target_depth"), 0.0, 10000.0)):
return False
asm_ids = set()
for asm in asms:
seq = asm.get("seq")
+8 -3
View File
@@ -243,11 +243,16 @@ class Sub:
self.decision_reason = f"{action}: {scores[action]:.2f}"
return action
def hit(self) -> None:
"""Torpedotreffer: Schaden; bei 100 % Sinkbeginn (Captain's Log §3)."""
def hit(self, amount: float | None = None) -> None:
"""Torpedotreffer: Schaden; bei 100 % Sinkbeginn (Captain's Log §3).
``amount`` is the warhead's shock-factor damage from the proximity
fuze; without it the historical 60-100 draw applies."""
if self.sunk or self.state == "SINKING":
return
self.damage = min(100.0, self.damage + self.rng.uniform(60.0, 100.0))
if amount is None:
amount = self.rng.uniform(60.0, 100.0)
self.damage = min(100.0, self.damage + amount)
if self.damage >= 100.0:
self.state = "SINKING"
self.sink_left = 20.0
+3 -2
View File
@@ -141,10 +141,11 @@ class SurfaceShip:
# --- Torpedo-Treffer ---
def hit(self) -> None:
def hit(self, amount: float | None = None) -> None:
"""Warhead damage (shock-factor amount from the fuze, else legacy)."""
if self.sunk:
return
self.damage = min(100.0, self.damage + 34.0)
self.damage = min(100.0, self.damage + (34.0 if amount is None else amount))
if self.damage >= 100.0:
self.sunk = True
+88
View File
@@ -0,0 +1,88 @@
"""Torpedo physics helpers (pure functions).
* Energy: the battery/fuel store is expressed in "cruise seconds" - the
catalog range at catalog speed. Propulsive power grows with the cube of
speed, so running slower (a throttled turn) stretches the store. When it
is empty the motor stops and the weapon coasts down against drag
(dv/dt = -k v^2) until it sinks/self-destructs.
* Turning: a constant minimum turning radius, so the turn rate is
proportional to speed.
* Depth: fins give a pitch/depth acceleration proportional to dynamic
pressure; the depth rate follows a proportional command at that
acceleration limit (small overshoot emerges).
* Warhead: a proximity fuze fires at closest approach inside its radius;
damage follows the underwater-explosion shock factor SF = sqrt(W) / R.
* Wire: finite payout on both spools, and tension breaks the wire when the
launching ship runs too fast or turns too hard for long enough.
"""
from __future__ import annotations
import math
COAST_DRAG_K = 0.45 # 1/s in dv/dt = -k v^2 (v as cruise fraction)
COAST_SINK_FRACTION = 0.3 # below this speed fraction the weapon is lost
DEPTH_ACCEL_MPS2 = 12.0 # at cruise speed (calibrated: 1.0.0 dive profile)
DEPTH_GAIN_PER_S = 0.8
DEPTH_RATE_MAX_MPS = 10.0
DEPTH_SUBSTEP_S = 0.1
WARHEAD_KG = 250.0
SF_LETHAL_SUBMARINE = 0.35
SF_LETHAL_SURFACE = 1.0
SURFACE_DAMAGE_CAP = 60.0
WIRE_TORPEDO_SPOOL_FACTOR = 1.25 # torpedo spool vs. catalog range
WIRE_SHIP_SPOOL_NM = 5.0
WIRE_MAX_SHIP_KN = 20.0
WIRE_MAX_SHIP_YAW_DEG_S = 1.5
WIRE_TENSION_BREAK_S = 5.0
RUNNING_NOISE_BAND_HZ = 1600.0
def energy_budget_s(range_nm: float, speed_kn: float) -> float:
"""Store in cruise seconds: catalog range at catalog speed."""
return range_nm / max(speed_kn / 3600.0, 1e-9)
def energy_rate(speed_fraction: float) -> float:
"""Cruise-seconds consumed per second at a fraction of cruise speed."""
return max(0.0, speed_fraction) ** 3
def coast_step(fraction: float, dt: float) -> float:
"""Exact coast-down of the speed fraction under quadratic drag."""
return fraction / (1.0 + COAST_DRAG_K * fraction * dt)
def turn_rate_deg_s(base_rate: float, speed_fraction: float) -> float:
"""Constant turning radius: rate scales with speed."""
return base_rate * max(0.0, min(1.0, speed_fraction))
def depth_step(depth: float, rate: float, target: float, speed_fraction: float,
dt: float, max_rate: float = DEPTH_RATE_MAX_MPS) -> tuple[float, float]:
"""Advance depth with a fin-limited vertical acceleration (substepped
to at most DEPTH_SUBSTEP_S so long frames integrate faithfully)."""
accel = DEPTH_ACCEL_MPS2 * max(0.05, speed_fraction) ** 2
steps = min(1000, max(1, math.ceil(dt / DEPTH_SUBSTEP_S - 1e-9)))
h = dt / steps
for _ in range(steps):
desired = max(-max_rate, min(max_rate, DEPTH_GAIN_PER_S * (target - depth)))
change = max(-accel * h, min(accel * h, desired - rate))
new_rate = rate + change
depth = max(0.0, depth + 0.5 * (rate + new_rate) * h)
rate = new_rate
return depth, rate
def shock_factor(charge_kg: float, slant_m: float) -> float:
return math.sqrt(charge_kg) / max(slant_m, 1.0)
def submarine_damage(slant_m: float) -> float:
return min(100.0, 100.0 * shock_factor(WARHEAD_KG, slant_m)
/ SF_LETHAL_SUBMARINE)
def surface_damage(slant_m: float) -> float:
return min(SURFACE_DAMAGE_CAP, 100.0 * shock_factor(WARHEAD_KG, slant_m)
/ SF_LETHAL_SURFACE)
+12
View File
@@ -337,3 +337,15 @@ def ray_excess_db(world, sensor_x: float, sensor_y: float, sensor_depth_m: float
tl = raytrace.lookup_tl_db(table, frequency_hz, distance,
min(target_depth_m, key[3]), key[3])
return tl - _spherical_db(distance) - ray_anchor_db()
def ray_reference_excess_db(range_nm: float, frequency_hz: float) -> float:
"""Ray excess of the reference environment at ``range_nm`` (relative to
the 20 NM anchor). Subtract it to re-anchor a short-range figure of
merit at its own calibration range."""
from src.sonar import raytrace
table = raytrace.cached_table(RAY_REFERENCE_KEY, _profile_from_key)
return (raytrace.lookup_tl_db(table, frequency_hz, range_nm,
RAY_REFERENCE_RECEIVER_M, RAY_REFERENCE_KEY[3])
- _spherical_db(range_nm) - ray_anchor_db())
+152 -19
View File
@@ -3,6 +3,7 @@
import math
from src.core import config
from src.physics import torpedo_dyn
from src.data.catalog import CATALOG
@@ -39,6 +40,27 @@ def underwater_path_blocked(world, x0, y0, depth0, x1, y1, depth1):
return False
ASROC_HELIX_DEG_PER_S = 6.0
WAKE_HOMING_THRESHOLD = 0.15
def _apply_warhead(body, slant_m: float) -> None:
"""Deliver shock-factor damage; fall back to the legacy hit call."""
if getattr(body, "signature_key", None) is not None:
amount = torpedo_dyn.surface_damage(slant_m)
else:
amount = torpedo_dyn.submarine_damage(slant_m)
try:
body.hit(amount)
except TypeError:
body.hit()
def radiated_source_db(speed_fraction: float) -> float:
"""Torpedo self noise: ~60 log v (cavitating propulsor at depth)."""
return 60.0 * math.log10(max(speed_fraction, 0.05))
class Torpedo:
# Exact speeds, envelopes, rates and timing below are gameplay tuning
# values. They do not describe real weapon performance or doctrine.
@@ -47,6 +69,7 @@ class Torpedo:
KILL_DIST_NM = _FRIGATE_TORP_PROFILE.hit_dist_nm
KILL_DEPTH_M = 15.0 # Tiefentoleranz
TURN_DEG_PER_S = 8.0
HOMING_TURN_DEG_PER_S = 15.0
DEPTH_RATE_M_PER_S = 10.0
WIRE_UPDATE_CADENCE_S = config.TORP_MIDCOURSE_UPDATE_S
WIRE_STALE_S = 3.0
@@ -89,6 +112,15 @@ class Torpedo:
# sites pass time_since_launch=0.0 for the ramp-up.
self.time_since_launch = (config.TORP_SPOOLUP_S if time_since_launch is None
else time_since_launch)
# Phase 8 physics state (saved): energy store in cruise seconds, motor
# speed fraction (1 while powered, falling while coasting), vertical
# rate, and the wire's ship-side payout/tension.
self.energy_s = torpedo_dyn.energy_budget_s(self.range_nm, self.speed_kn)
self.motor_fraction = 1.0
self.depth_rate = 0.0
self.wire_ship_out_nm = 0.0
self.wire_stress_s = 0.0
self.last_miss_m = None
self._search_phase = 0.0 # M15: Serpentin-Phase
self._midcourse = course_deg % 360.0 # M15: Draht-Mittelkurs
# The persisted timer also carries wire age.
@@ -134,6 +166,24 @@ class Torpedo:
return "STALE"
return "ACTIVE"
def speed_fraction(self) -> float:
"""Current speed as a fraction of the catalog cruise speed."""
return self._spoolup_factor() * self.motor_fraction
def wire_tension_update(self, dt: float, ship_speed_kn: float,
ship_yaw_deg_s: float) -> None:
"""Pay out the ship-side spool and break the wire on overload."""
if self.state != "RUN" or self.wire_state == "BROKEN":
return
self.wire_ship_out_nm += config.kn_to_nm_per_s(max(0.0, ship_speed_kn)) * dt
overload = (ship_speed_kn > torpedo_dyn.WIRE_MAX_SHIP_KN
or abs(ship_yaw_deg_s) > torpedo_dyn.WIRE_MAX_SHIP_YAW_DEG_S)
self.wire_stress_s = (self.wire_stress_s + dt) if overload else 0.0
if (self.wire_stress_s >= torpedo_dyn.WIRE_TENSION_BREAK_S
or self.wire_ship_out_nm >= torpedo_dyn.WIRE_SHIP_SPOOL_NM
or self.travel >= self.range_nm * torpedo_dyn.WIRE_TORPEDO_SPOOL_FACTOR):
self.break_wire()
def break_wire(self) -> None:
"""Permanently reject further command updates for this run."""
self._midcourse_timer = self.WIRE_BREAK_S
@@ -202,6 +252,10 @@ class Torpedo:
desired = None
wobble = 0.0
turn = self.TURN_DEG_PER_S
if self.launch_origin == "asroc" and not self.seeker_acquired:
# Air-dropped payload: helical search around the splash point
# while descending to the search depth.
self.terminal_active = True
# Normal activation is based on the commanded datum, never hidden truth.
seeker_active = self.guidance_distance_nm() <= config.TORP_HOME_RANGE_NM
if self.guidance_x is None or self.guidance_y is None:
@@ -227,7 +281,9 @@ class Torpedo:
if self.seeker_acquired and target_alive:
desired = self._bearing_to(sub.x, sub.y)
self.target_depth = max(0.0, sub.depth)
turn = 15.0
turn = self.HOMING_TURN_DEG_PER_S
elif self.launch_origin == "asroc" and self.guidance_distance_nm() < 0.5:
desired = (self.course + ASROC_HELIX_DEG_PER_S) % 360.0
else:
# Vor der Eigenortung folgt der Torpedo nur Drahtdaten und sucht
# um deren Kurs. Die wahre Zielposition korrigiert ihn hier nicht.
@@ -244,16 +300,18 @@ class Torpedo:
# um in Zieltiefe zu treffen (lineares Tauchen kam zu spat an).
old_depth = self.depth
d_target = max(0.0, self.target_depth + wobble)
d_diff = d_target - self.depth
self.depth += config.clamp(
d_diff, -self.DEPTH_RATE_M_PER_S * dt,
self.DEPTH_RATE_M_PER_S * dt)
fraction = self.speed_fraction()
self.depth, self.depth_rate = torpedo_dyn.depth_step(
self.depth, self.depth_rate, d_target, fraction, dt,
self.DEPTH_RATE_M_PER_S)
throttle = 1.0
if desired is not None:
diff = config.angle_diff_deg(desired, self.course)
# Constant turning radius: the rate scales with speed.
rate = torpedo_dyn.turn_rate_deg_s(turn, fraction)
self.course = (self.course + config.clamp(
diff, -turn * dt, turn * dt)) % 360.0
diff, -rate * dt, rate * dt)) % 360.0
# M15: bei starkem Ruderbedarf krabbeln, damit der Torpedo
# nicht um das Ziel kreist: Kurs erst richten, dann anrennen.
if abs(diff) > 60.0:
@@ -261,10 +319,21 @@ class Torpedo:
else:
throttle = 1.0 - 0.5 * max(
0.0, min(1.0, (abs(diff) - 30.0) / 30.0))
# Energy: power ~ v^3; an empty store stops the motor and the weapon
# coasts against drag until it is lost.
effective = self._spoolup_factor() * throttle * self.motor_fraction
if self.motor_fraction >= 1.0:
self.energy_s -= torpedo_dyn.energy_rate(
self._spoolup_factor() * throttle) * dt
if self.energy_s <= 0.0:
self.energy_s = 0.0
self.motor_fraction = 1.0 - 1e-9
else:
self.motor_fraction = torpedo_dyn.coast_step(self.motor_fraction, dt)
effective = self._spoolup_factor() * self.motor_fraction
# Bewegung (Anti-Tunneling: Swept-Check über den ganzen Schritt)
ox, oy = self.x, self.y
step = min(self.speed_nm_per_s * dt * throttle * self._spoolup_factor(),
max(0.0, self.range_nm - self.travel))
step = self.speed_nm_per_s * dt * effective
self.x += step * math.sin(math.radians(self.course))
self.y -= step * math.cos(math.radians(self.course))
self.travel += step
@@ -294,8 +363,12 @@ class Torpedo:
self.travel -= step * (1.0 - fraction)
self.target = body
if callable(getattr(body, "hit", None)):
# Proximity fuze at closest approach: shock-factor damage.
horizontal = self._swept_dist(body, ox, oy) * 1852.0
slant = math.hypot(horizontal, getattr(body, "depth", hd) - hd)
self.last_miss_m = slant
self.state = "HIT"
body.hit()
_apply_warhead(body, slant)
else:
# A decoy/contact consumes the terminal run but is not a
# reportable target hit.
@@ -303,9 +376,25 @@ class Torpedo:
return
if (underwater_path_blocked(world, ox, oy, old_depth,
self.x, self.y, self.depth)
or self.travel >= self.range_nm):
or self.motor_fraction < torpedo_dyn.COAST_SINK_FRACTION):
self.state = "SASE"
# --- radiated noise (heard by the target's sonar) ---------------------
def source_level_offset_db(self) -> float:
return radiated_source_db(self.speed_fraction())
def quiet_factor(self) -> float:
return config.ENEMY_TORP_QUIET
def lofar_lines(self, t_sim: float = 0.0) -> list:
"""Propulsor tonals scale with motor speed."""
if self.state != "RUN":
return []
f = 180.0 * max(0.1, self.speed_fraction())
amplitude = min(1.0, 0.9 * self.speed_fraction())
return [(f * 0.5, 0.4 * amplitude, 5.0), (f, amplitude, 8.0)]
def _swept_hit_fraction(self, target, ox, oy, old_depth, radius):
"""First overlap of the horizontal hit circle and vertical tolerance."""
dx, dy = self.x - ox, self.y - oy
@@ -387,10 +476,21 @@ class EnemyTorpedo:
# sites pass time_since_launch=0.0 for the ramp-up.
self.time_since_launch = (config.TORP_SPOOLUP_S if time_since_launch is None
else time_since_launch)
# Phase 8 physics state (saved).
self.energy_s = torpedo_dyn.energy_budget_s(self.range_nm, self.speed_kn)
self.motor_fraction = 1.0
self.depth_rate = 0.0
self.target_depth = depth_m
def _spoolup_factor(self) -> float:
return Torpedo._spoolup_factor(self)
def speed_fraction(self) -> float:
return self._spoolup_factor() * self.motor_fraction
def source_level_offset_db(self) -> float:
return radiated_source_db(self.speed_fraction())
@property
def dead(self) -> bool:
return self.state != "RUN"
@@ -436,15 +536,35 @@ class EnemyTorpedo:
self._seeker_target = candidate
self.seeker_acquired = True
target = self._seeker_target
fraction = self.speed_fraction()
desired = None
if target is not None:
desired = math.degrees(math.atan2(
target.x - self.x, -(target.y - self.y))) % 360.0
# Homing on a surface ship: run up to keel depth.
self.target_depth = min(self.target_depth,
max(3.0, getattr(target, "depth", 5.0) + 1.0))
else:
wake = getattr(ship, "wake_strength_at", None)
if wake is not None and wake(self.x, self.y) >= WAKE_HOMING_THRESHOLD:
# Wake homing: follow the bubble trail toward its young end.
desired = self._wake_course(ship)
if desired is not None:
diff = config.angle_diff_deg(desired, self.course)
rate = torpedo_dyn.turn_rate_deg_s(self.TURN_DEG_PER_S, fraction)
self.course = (self.course + config.clamp(
diff, -6.0 * dt, 6.0 * dt)) % 360.0
diff, -rate * dt, rate * dt)) % 360.0
self.depth, self.depth_rate = torpedo_dyn.depth_step(
self.depth, self.depth_rate, self.target_depth, fraction, dt)
if self.motor_fraction >= 1.0:
self.energy_s -= torpedo_dyn.energy_rate(self._spoolup_factor()) * dt
if self.energy_s <= 0.0:
self.energy_s = 0.0
self.motor_fraction = 1.0 - 1e-9
else:
self.motor_fraction = torpedo_dyn.coast_step(self.motor_fraction, dt)
ox, oy = self.x, self.y
step = min(self.speed_nm_per_s * dt * self._spoolup_factor(),
max(0.0, self.range_nm - self.travel))
step = self.speed_nm_per_s * dt * self.speed_fraction()
self.x += step * math.sin(math.radians(self.course))
self.y -= step * math.cos(math.radians(self.course))
self.travel += step
@@ -470,9 +590,20 @@ class EnemyTorpedo:
if hasattr(target, "dead"):
target.dead = True
target.state = "SASE"
elif self.travel >= self.range_nm:
elif self.motor_fraction < torpedo_dyn.COAST_SINK_FRACTION:
self.state = "SASE"
TURN_DEG_PER_S = 6.0
def _wake_course(self, ship) -> float:
"""Course along the wake toward its youngest sampled point."""
points = getattr(ship, "wake", ())
if not points:
return self.course
youngest = points[-1]
return math.degrees(math.atan2(youngest[0] - self.x,
-(youngest[1] - self.y))) % 360.0
# --- Duck-Type-Interface wie Sub/Animal (passives Sonar) ---
def distance_nm(self, ship) -> float:
@@ -487,13 +618,15 @@ class EnemyTorpedo:
return config.ENEMY_TORP_QUIET
def lofar_lines(self, t_sim: float = 0.0) -> list:
"""Kreisch-Linie: 150->90 Hz ueber die Laufstrecke, plus
Unterharmonische (45-75 Hz) im DEMON-Trennbereich."""
"""Propulsor whine: frequency and level follow the motor speed as the
battery sags over the run (150 -> 90 Hz), plus the subharmonic."""
if self.state != "RUN":
return []
frac = min(1.0, self.travel / max(0.001, self.range_nm))
f = 150.0 - 60.0 * frac
return [(f * 0.5, 0.35, 5.0), (f, 0.90, 8.0)]
used = 1.0 - self.energy_s / max(
torpedo_dyn.energy_budget_s(self.range_nm, self.speed_kn), 1e-9)
f = (150.0 - 60.0 * min(1.0, max(0.0, used))) * max(0.1, self.speed_fraction())
amplitude = min(1.0, 0.9 * self.speed_fraction())
return [(f * 0.5, 0.39 * amplitude, 5.0), (f, amplitude, 8.0)]
def broadband(self) -> dict:
prof = self.profile
+144
View File
@@ -0,0 +1,144 @@
"""Phase 8: torpedo energy, turning, depth, wire, warhead, noise, wake."""
import copy
import json
import math
import random
from types import SimpleNamespace
import pytest
from src.core import config
from src.core.game import Game
from src.data.catalog import CATALOG
from src.enemies.sub import Sub
from src.physics import torpedo_dyn
from src.ship.ship import Ship
from src.weapons.torpedo import EnemyTorpedo, Torpedo
PROFILE = CATALOG.get_torpedo("frigate_torp")
def _run(torpedo, seconds, dt=0.5, **kwargs):
for _ in range(int(seconds / dt)):
torpedo._midcourse_timer = 0.0
torpedo.update(dt, **kwargs)
if torpedo.state != "RUN":
break
def test_energy_store_sets_range_and_the_weapon_coasts_then_is_lost():
torpedo = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=PROFILE,
guidance_x=100.0, guidance_y=0.0)
_run(torpedo, 5000.0)
assert torpedo.state == "SASE"
assert torpedo.energy_s == 0.0
assert torpedo.motor_fraction < torpedo_dyn.COAST_SINK_FRACTION
assert torpedo.travel == pytest.approx(PROFILE.range_nm, rel=0.02)
def test_slower_running_stretches_the_store():
assert torpedo_dyn.energy_rate(0.5) == pytest.approx(0.125)
assert torpedo_dyn.coast_step(1.0, 10.0) < 0.25
def test_turn_rate_scales_with_speed():
assert torpedo_dyn.turn_rate_deg_s(8.0, 0.5) == pytest.approx(4.0)
fresh = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=PROFILE,
guidance_x=130.0, guidance_y=100.0, time_since_launch=0.0)
cruising = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=PROFILE,
guidance_x=130.0, guidance_y=100.0)
for torpedo in (fresh, cruising):
torpedo._midcourse_timer = 0.0
torpedo.update(1.0)
assert fresh.course < cruising.course
def test_wire_breaks_on_ship_overspeed_or_spool_end():
torpedo = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=PROFILE,
guidance_x=100.0, guidance_y=90.0)
for _ in range(20):
torpedo.wire_tension_update(0.5, 16.0, 0.5)
assert torpedo.wire_state != "BROKEN"
for _ in range(12):
torpedo.wire_tension_update(0.5, 24.0, 0.0)
assert torpedo.wire_state == "BROKEN"
spool = Torpedo(100.0, 100.0, 0.0, 60.0, None, 0, profile=PROFILE,
guidance_x=100.0, guidance_y=90.0)
spool.wire_ship_out_nm = torpedo_dyn.WIRE_SHIP_SPOOL_NM - 0.001
spool.wire_tension_update(10.0, 12.0, 0.0)
assert spool.wire_state == "BROKEN"
def test_proximity_fuze_damage_follows_shock_factor():
close = torpedo_dyn.submarine_damage(20.0)
far = torpedo_dyn.submarine_damage(150.0)
assert close == 100.0 and 10.0 < far < 50.0
sub = Sub(100.0, 100.0, 60.0, 0.0, "aip_modern", random.Random(1))
sub.hit(far)
assert sub.damage == pytest.approx(far) and sub.state == "EVADE"
def test_enemy_torpedo_rises_to_keel_depth_when_homing():
ship = Ship(100.0, 100.0)
torpedo = EnemyTorpedo(100.0, 101.0, 0.0, 40.0, 1)
for _ in range(60):
torpedo.update(0.5, ship)
if torpedo.state != "RUN":
break
assert torpedo.target_depth < 10.0 and torpedo.depth < 40.0
def test_enemy_torpedo_follows_the_wake():
ship = Ship(100.0, 100.0, course_deg=90.0, speed_kn=20.0)
ship.target_speed = 20.0
for _ in range(120):
ship.update(1.0)
tail = ship.wake[0]
torpedo = EnemyTorpedo(tail[0], tail[1] + 0.02, 180.0, 10.0, 1,
guidance_x=tail[0], guidance_y=tail[1] + 10.0)
start = torpedo.course
for _ in range(20):
torpedo.update(0.5, ship)
assert abs(config.angle_diff_deg(torpedo.course, 90.0)) < abs(
config.angle_diff_deg(start, 90.0))
def test_lookout_sees_a_shallow_torpedo_wake_by_day():
game = Game(seed=8801, start_menu=False, audio_enabled=False)
game.world.hour = 12.0
game.world.sea_state = 1
game.world.weather_shift_timer = 0.0
game.world.refresh_weather()
game.world.land_blocks_line = lambda *args: False
torpedo = EnemyTorpedo(game.ship.x + 1.0, game.ship.y, 270.0, 8.0, 1)
game.enemy_torpedoes = [torpedo]
game._update_lookout_picture()
assert any(track.kind == "TORP" and track.source == "LOOKOUT"
for track in game.air_picture._tracks.values())
def test_torpedo_physics_state_round_trips_and_is_validated():
game = Game(seed=8802, start_menu=False, audio_enabled=False)
weapon_key = game.player_torpedo_battery.fire()
weapon = next(row for row in game._ownship_loadout["weapons"]
if row["key"] == weapon_key)
profile = game.runtime_catalog.torpedoes[weapon["runtime_profile_key"]]
game.torpedo_count = game.player_torpedo_battery.remaining_total
torpedo = Torpedo(game.ship.x, game.ship.y, 0.0, 60.0, None, 1, profile=profile,
guidance_x=game.ship.x, guidance_y=game.ship.y - 5.0,
kill_dist_nm=game.difficulty["kill_dist_nm"],
kill_depth_m=game.difficulty["kill_depth_m"])
game.torpedo_seq = 1
torpedo.energy_s, torpedo.depth_rate = 100.0, 3.0
torpedo.wire_ship_out_nm, torpedo.wire_stress_s = 1.5, 2.0
game.torpedoes = [torpedo]
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.torpedoes[0]
assert (twin.energy_s, twin.depth_rate, twin.wire_ship_out_nm,
twin.wire_stress_s) == (100.0, 3.0, 1.5, 2.0)
broken = copy.deepcopy(state)
broken["torpedoes_in_flight"][0]["motor_fraction"] = 2.0
assert not restored._load_save_data(broken)
+10 -3
View File
@@ -90,10 +90,15 @@ def test_torpedo_notice_ranges_are_ordered_between_homing_and_launch_alert():
< config.SUB_TORPEDO_ALERT_NM)
def test_quiet_sub_notices_running_torpedo_before_homing_range(game):
def test_quiet_sub_notices_running_torpedo_before_homing_range(game, monkeypatch):
"""Between TORP_HOME_RANGE_NM and the launch transient, a sub can still
passively notice a running torpedo - scaled by how much its own noise
masks its listening."""
# Heard through the passive sonar equation; calm, dry weather so rain
# and wind noise do not mask the reference range.
monkeypatch.setattr(game.world, "weather_values", lambda: dict(
wind_speed_kn=6.0, rain_intensity=0.0, visibility_nm=10.0,
wind_from_deg=0.0, sea_state=1.0))
torpedo = Torpedo(game.ship.x + config.TORP_RUNNING_NOISE_RANGE_NM - 1.0,
game.ship.y, 90.0, 50.0, None, 1)
game.torpedoes = [torpedo]
@@ -297,11 +302,13 @@ def test_terminal_depth_tracking_loss_and_reacquisition():
torpedo.update(1.0, [first])
assert torpedo.seeker_acquired
assert torpedo.target_depth == 100
assert torpedo.depth == 15.0
# Fin-limited vertical acceleration: diving, never faster than 10 m/s.
first_depth = torpedo.depth
assert 5.0 < first_depth <= 15.0
first.depth = 200
torpedo.update(1.0, [first])
assert torpedo.target_depth == 200
assert torpedo.depth == 25.0
assert first_depth < torpedo.depth <= first_depth + 10.0
first.x = 200
torpedo.update(0.1, [first])
assert not torpedo.seeker_acquired