diff --git a/data/manual/03-weapons.de.md b/data/manual/03-weapons.de.md index 9b2b5011..213fddb3 100644 --- a/data/manual/03-weapons.de.md +++ b/data/manual/03-weapons.de.md @@ -46,7 +46,7 @@ Torpedolauf von oben: Gefechtslage: -1. Feindtorpedo gemeldet: sofort Nixie ausbringen (`V`). Er hält 600 s, läuft 0,2 sm achteraus in 10 m Tiefe; einer bereit, ein zweiter nach 60 s. +1. Feindtorpedo gemeldet: sofort Nixie ausbringen (`V`). Er hält 600 s an einem 0,2-sm-Kabel; einer bereit, ein zweiter nach 60 s. Bei 15 kn läuft er in 10 m Tiefe, bei langsamer Fahrt tiefer und näher achteraus, über 25 kn reißt das Kabel. In einer Wende läuft das Kabel hinterher. 2. Den Gegenangriff fortsetzen: ein frischer Kontakt hält das Draht-Datum auf dem U-Boot. 3. Ist der Helikopter in der Luft, erreicht ein Leichttorpedo (`D`) einen entfernten Kontakt schneller als der Schiffstorpedo. @@ -69,6 +69,7 @@ Das Hauptquartier schaltet nach dem ersten versenkten feindlichen U-Boot per Fun - 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. +- Zielsuchköpfe halten den lautesten Kandidaten und wechseln nur, wenn ein anderer deutlich (6 dB) lauter ist. Echos ohne Doppler ignorieren sie, ein schwebendes Ziel ist daher schwer zu finden; ein Torpedo, der einen Täuschkörper ohne Rumpftreffer überläuft, merkt ihn sich und greift erneut an. Täuschkörper gegnerischer U-Boote werden mit leerer werdender Batterie leiser; gegnerische Kriegsschiffe bringen eigene Täuschkörper aus, wenn sie Ihren Torpedostart hören. ## Nicht modelliert {#weapons-limits} diff --git a/data/manual/03-weapons.en.md b/data/manual/03-weapons.en.md index 93bc6e12..b03fdbb5 100644 --- a/data/manual/03-weapons.en.md +++ b/data/manual/03-weapons.en.md @@ -46,7 +46,7 @@ Torpedo run, seen from above: Combat situation: -1. Enemy torpedo reported: stream the Nixie at once (`V`). It lasts 600 s, trails 0.2 NM astern at 10 m; one ready, a second after 60 s. +1. Enemy torpedo reported: stream the Nixie at once (`V`). It lasts 600 s on a 0.2 NM cable; one ready, a second after 60 s. It runs at 10 m at 15 kn, deeper and closer astern when you slow down, and its cable parts above 25 kn. In a turn the cable lags behind. 2. Keep the counter-attack going: a fresh contact keeps the wire datum on the submarine. 3. With the helicopter airborne, a lightweight torpedo (`D`) can reach a distant contact faster than the ship's torpedo. @@ -69,6 +69,7 @@ HQ switches to FREE by radio after the first hostile submarine is sunk; the play - 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. +- Homing seekers lock on the loudest candidate and only switch when another is clearly (6 dB) louder. They ignore echoes without Doppler, so a hovering target is hard to find; a torpedo that overruns a decoy without a hull hit remembers it and re-attacks. Hostile submarine decoys fade as their battery drains; hostile warships stream their own decoys when they hear your torpedo launch. ## Not modelled {#weapons-limits} diff --git a/data/manual/10-reference.de.md b/data/manual/10-reference.de.md index 592237e2..817b841e 100644 --- a/data/manual/10-reference.de.md +++ b/data/manual/10-reference.de.md @@ -34,7 +34,7 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke | 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 | +| Nixie-Schlepptäuschkörper | 2 je Mission, 600 s, 0,2-sm-Kabel (10 m bei 15 kn, langsamer tiefer, reißt über 25 kn), 60 s Nachladen | | ESSM | 6 Flugkörper, 30 sm, 2 Feuerkanäle | | CIWS | 1,5 sm, 180 Schuss, braucht Freigabe | | Flak-Geschütz | 240 Schuss, braucht Freigabe | diff --git a/data/manual/10-reference.en.md b/data/manual/10-reference.en.md index 41580d63..01c7c053 100644 --- a/data/manual/10-reference.en.md +++ b/data/manual/10-reference.en.md @@ -34,7 +34,7 @@ All values are the defaults of the current game version. Custom difficulty and 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 | +| Nixie towed decoy | 2 per mission, 600 s, 0.2 NM cable (10 m at 15 kn, deeper when slower, parts above 25 kn), 60 s reload | | ESSM | 6 missiles, 30 NM, 2 fire channels | | CIWS | 1.5 NM, 180 rounds, needs release | | AA gun | 240 rounds, needs release | diff --git a/docs/simulation-gaps.md b/docs/simulation-gaps.md index d95bf3ec..8b105790 100644 --- a/docs/simulation-gaps.md +++ b/docs/simulation-gaps.md @@ -122,9 +122,9 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment. |-----|-------------------|------------| | ~~**No ship hydrodynamics**~~ | **Closed (Phase 6).** Speed lag from the catalog, Nomoto-linear turning, and added resistance in waves lowering attainable speed by hull length (small hulls lose more). | — | | ~~**No radar horizon**~~ | **Fixed (2026-09).** Surface detection now uses `min(effective_range × aspect, radar_horizon_nm(RADAR_ANTENNA_HEIGHT_M, RADAR_SURFACE_TARGET_HEIGHT_M))` for both civilians and warships (`game.py`, `_update_air_picture`), the same formula already used for raiders. | — | -| **No countermeasures** | Warships do not deploy chaff/flare | ASM jamming, chaff, hard-kill CIWS on enemy ships | +| ~~**No countermeasures**~~ | **Closed (Phase 9 / Phase 12).** Hostile combatants stream acoustic decoys (saved store of 2) when they hear a torpedo launch; missile defence (ship chaff/CIWS) is modelled on the own ship in Phase 12. | — | | **No damage propagation** | Single scalar `damage`; one torpedo = 34 damage → 3 hits to sink | Compartment flooding, fire, loss of specific capabilities | -| **No evasive manoeuvres** | Loiter pattern only; no evasive when torpedo detected | Evasive turns, smoke, decoys | +| ~~**No evasive manoeuvres**~~ | **Closed.** Combatants turn away at flank speed on a heard launch (W2, state saved in Phase 0) and stream decoys (Phase 9). | — | | **No weapon systems modelling** | ASM/ASROC are simple projectiles; no fire-control solution error | Guidance accuracy, warhead proximity fuze, multi-target saturation | ### 3.3 Data structures touched @@ -190,11 +190,13 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment. ### 5.2 Gaps and simplifications -- No self-noise model (decoys are "loud" with fixed quiet factor) -- No towed-decoy cable dynamics (drag, sway, depth variation) -- No frequency/content modulation of decoy signal -- No decoy effectiveness model (why does it fool the torpedo? just proximity + being a candidate) -- No multiple-decoy confusion logic +All closed in Phase 9: + +- ~~No self-noise model~~ — decoy emission fades with its battery (`source_level_offset_db`); the Nixie has a designed emission 12 dB above a quiet hull. +- ~~No towed-decoy cable dynamics~~ — quasi-static cable equilibrium: depth ~ design depth x (15 kn / v)^2 (bounded), layback from the cable length, tow bearing lagging the ship's course (saved), cable parts above 25 kn. +- ~~No frequency/content modulation~~ — replica tonals with a slow +/-2 % sweep and battery-dependent level. +- ~~No decoy effectiveness model~~ — seekers score candidates by received level (source level, spreading, depth mismatch) with a Doppler gate against stationary echoes; the moving towed Nixie passes the gate. +- ~~No multiple-decoy confusion logic~~ — lock hysteresis (6 dB), and a torpedo that overruns a decoy remembers it (bounded, saved) and re-attacks with its remaining energy. --- diff --git a/src/core/config.py b/src/core/config.py index 3fb89c52..b792c344 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -170,6 +170,7 @@ RADAR_AIR_RANGE_NM = 100.0 # KAMPFSCHIFF (Kontakt-DB): feindliche Kriegsschiffe loiteren um ihre Basis # und feuern ASM-Salven, wenn die Fregatte in Reichweite ist. WARSHIP_ASM_RANGE_NM = 35.0 # Abstand, ab dem Salven möglich sind +WARSHIP_TORPEDO_DECOYS = 2 # acoustic decoys a combatant can stream WARSHIP_TORPEDO_EVADE_S = 90.0 # W2: Torpedoalarm -> harte Wende, dann weiter # M5: Schadensmodell (Raten in sim-Sekunden) diff --git a/src/core/game.py b/src/core/game.py index 0f2b5bea..fbd0de57 100644 --- a/src/core/game.py +++ b/src/core/game.py @@ -5610,6 +5610,16 @@ class Game: self.ship.x - warship.x, -(self.ship.y - warship.y))) % 360.0 warship.alert_torpedo(bearing) + if (warship.countermeasures_left > 0 and warship.side == "hostile" + and len(self.decoys) < MAX_DECOYS): + # Stream an acoustic decoy while turning away. + warship.countermeasures_left -= 1 + decoy_profile = self.runtime_catalog.decoys[ + self.runtime_catalog.runtime_bindings["submarine_decoy"]] + self.decoys.append(Decoy( + warship.x, warship.y, 10.0, self.rng_asw, decoy_profile, + self.runtime_catalog.acoustic_for(decoy_profile.key), + source_id=warship.id)) self._emit_sound("torpedo_launch") self.flash(message("runtime.torpedo.launched", torpedo=self.torpedo_seq), 2.0) self.feed.add(self.world.format_time(), "waffen", @@ -6844,6 +6854,7 @@ class Game: sensor_contact_age=w.sensor_contact_age, sunk_score_awarded=w.sunk_score_awarded, torpedo_evade_left=w._torpedo_evade_left, + countermeasures_left=w.countermeasures_left, torpedo_threat_bearing=w._torpedo_threat_bearing, pending_asm=list(w.pending_asm), asroc_battery=(w.asroc_battery.serialize() @@ -6884,7 +6895,8 @@ class Game: 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) + wire_stress_s=t.wire_stress_s, + rejected_ids=list(t.rejected_ids)) for t in self.torpedoes], "enemy_torpedoes": [ dict(id=t.id, x=t.x, y=t.y, course=t.course, depth=t.depth, @@ -7522,6 +7534,7 @@ class Game: w.sensor_contact_age = wd["sensor_contact_age"] w.sunk_score_awarded = wd["sunk_score_awarded"] w._torpedo_evade_left = wd["torpedo_evade_left"] + w.countermeasures_left = wd["countermeasures_left"] w._torpedo_threat_bearing = wd["torpedo_threat_bearing"] w.pending_asm = [tuple(row) for row in wd["pending_asm"]] if wd["asroc_battery"] is not None: @@ -7586,6 +7599,7 @@ class Game: t.depth_rate = td["depth_rate"] t.wire_ship_out_nm = td["wire_ship_out_nm"] t.wire_stress_s = td["wire_stress_s"] + t.rejected_ids = list(td["rejected_ids"]) self.torpedoes.append(t) for ed in data["enemy_torpedoes"]: enemy_key = ed["profile_key"] @@ -8345,7 +8359,8 @@ class Game: "speed", "life", "sensor_seed", "profile_key", "source_id"} or not identity(source_id) - or source_id not in group_ids["sub"] + or (source_id not in group_ids["sub"] + and source_id not in group_ids["surface"]) or not bounded(entry.get("depth"), 0, 10000) or not bounded(entry.get("course"), 0, 360) or entry.get("course") == 360 @@ -8459,6 +8474,13 @@ class Game: "asroc_battery", "pending_asroc", "asw_last_seen"} <= set(entry): return False + left = entry.get("countermeasures_left") + if (type(left) is not int + or not 0 <= left <= config.WARSHIP_TORPEDO_DECOYS): + return False + if entity_id is not None: + spent_decoys[entity_id] = ( + config.WARSHIP_TORPEDO_DECOYS - left) battery = entry.get("asroc_battery") expected_battery = WeaponBattery.from_catalog( runtime_catalog, profile_key, "asroc") @@ -8871,7 +8893,10 @@ class Game: 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)): + or not bounded(row.get("wire_stress_s"), 0.0, 1e6) + or not isinstance(row.get("rejected_ids"), list) + or len(row["rejected_ids"]) > 4 + or any(not identity(item) for item in row["rejected_ids"])): return False for row in data.get("enemy_torpedoes", []): if (not isinstance(row, dict) diff --git a/src/enemies/decoy.py b/src/enemies/decoy.py index b9e8133e..fe234779 100644 --- a/src/enemies/decoy.py +++ b/src/enemies/decoy.py @@ -11,6 +11,10 @@ from src.data.catalog import CATALOG from src.weapons.torpedo import underwater_path_blocked +DECOY_SWEEP_FRACTION = 0.02 +DECOY_SWEEP_PERIOD_S = 30.0 + + class Decoy: """Sonar-Objekt wie Sub/Animal (Duck-Typing), aber ohne KI-Fahrplan.""" @@ -71,6 +75,17 @@ class Decoy: # Lautes, leichtes Rauschen: maskiert das U-Boot im LOFAR return 0.15 + @property + def speed_kn(self) -> float: + return self.speed * 3600.0 + + def battery_fraction(self) -> float: + return max(0.0, min(1.0, self.life / max(self.profile.life_s, 1e-6))) + + def source_level_offset_db(self) -> float: + """Emission weakens as the battery drains (amplifier voltage).""" + return 20.0 * math.log10(max(0.1, math.sqrt(self.battery_fraction()))) + def acoustic_signature(self) -> str: if self.dead: return "" @@ -78,9 +93,15 @@ class Decoy: return f"mechanisch · {text} (Dekoy?)" def lofar_lines(self, t_sim: float = 0.0) -> list: + """Replica tonals with a slow frequency modulation (+/-2 %, 30 s) and + a level that follows the battery.""" if self.dead: return [] - return [tuple(v) for v in self.profile.lines] + sweep = 1.0 + DECOY_SWEEP_FRACTION * math.sin( + 2.0 * math.pi * t_sim / DECOY_SWEEP_PERIOD_S + + (self.sensor_seed % 360) * math.pi / 180.0) + level = math.sqrt(self.battery_fraction()) + return [(v[0] * sweep, v[1] * level, *v[2:]) for v in self.profile.lines] def broadband(self) -> dict: if self.dead: diff --git a/src/enemies/surface.py b/src/enemies/surface.py index a89d4205..f62c0120 100644 --- a/src/enemies/surface.py +++ b/src/enemies/surface.py @@ -108,6 +108,9 @@ class SurfaceShip: # W2: Torpedo-Alarm -> harte Wende weg von der Bedrohung self._torpedo_evade_left = 0.0 self._torpedo_threat_bearing = 0.0 + # Acoustic torpedo decoys carried by combatants (saved). + self.countermeasures_left = (config.WARSHIP_TORPEDO_DECOYS + if doctrine == "surface_combatant" else 0) @property def hostile(self) -> bool: diff --git a/src/weapons/asw.py b/src/weapons/asw.py index 900020f3..99d0358e 100644 --- a/src/weapons/asw.py +++ b/src/weapons/asw.py @@ -568,32 +568,64 @@ class ASROC: return result +NIXIE_LEVEL_DB = 12.0 # designed emission above a quiet hull +NIXIE_MAX_TOW_KN = 25.0 # the tow cable parts above this speed +NIXIE_DESIGN_TOW_KN = 15.0 # speed at which it streams at its design depth +NIXIE_HEADING_TAU_S = 60.0 # cable lag in turns + + class TowedAcousticDecoy: - """A bounded, ownship-tethered terminal seeker candidate.""" + """Towed acoustic decoy on a cable. + + Quasi-static cable equilibrium: hydrodynamic drag (~v^2) against the + body's wet weight sets the cable angle, so the decoy streams deeper and + closer astern when the ship slows and shallower/farther when it speeds up + (depth ~ design depth * (v_design / v)^2, bounded). The tow bearing lags + the ship's course in turns; above NIXIE_MAX_TOW_KN the cable parts. The + emitted level is designed louder than a quiet hull and it moves with the + ship, so a Doppler-gated seeker cannot reject it.""" + + acoustic_level_db = NIXIE_LEVEL_DB def __init__(self, seq: int, ship, *, life_s: float, tether_nm: float, - depth_m: float): + depth_m: float, tow_heading: float | None = None): self.seq = seq self.life = life_s self.tether_nm = tether_nm + self.design_depth = depth_m self.depth = depth_m self.dead = False self.state = "RUN" self.sunk = False + self.speed_kn = float(getattr(ship, "speed", NIXIE_DESIGN_TOW_KN)) + self.tow_heading = (ship.course % 360.0 if tow_heading is None + else tow_heading % 360.0) self.x, self.y = ship.x, ship.y - self.update(0.0, ship, None) + self._place(ship) + + def _place(self, ship) -> None: + speed = max(3.0, self.speed_kn) + factor = min(6.0, max(0.5, (NIXIE_DESIGN_TOW_KN / speed) ** 2)) + cable_m = self.tether_nm * 1852.0 + self.depth = min(self.design_depth * factor, 0.9 * cable_m) + layback_nm = math.sqrt(max(0.0, cable_m ** 2 - self.depth ** 2)) / 1852.0 + angle = math.radians((self.tow_heading + 180.0) % 360.0) + self.x = ship.x + layback_nm * math.sin(angle) + self.y = ship.y - layback_nm * math.cos(angle) def update(self, dt: float, ship, world) -> None: if self.dead: return self.life = max(0.0, self.life - max(0.0, dt)) - if self.life <= 0.0: + self.speed_kn = float(getattr(ship, "speed", self.speed_kn)) + if self.life <= 0.0 or self.speed_kn > NIXIE_MAX_TOW_KN: self.dead = True self.state = "SASE" return - angle = math.radians((ship.course + 180.0) % 360.0) - self.x = ship.x + self.tether_nm * math.sin(angle) - self.y = ship.y - self.tether_nm * math.cos(angle) + self.tow_heading = (self.tow_heading + config.angle_diff_deg( + ship.course, self.tow_heading) * (1.0 - math.exp( + -max(0.0, dt) / NIXIE_HEADING_TAU_S))) % 360.0 + self._place(ship) if world is not None and (world.on_land(self.x, self.y) or world.depth_m(self.x, self.y) <= self.depth): self.dead = True @@ -601,14 +633,15 @@ class TowedAcousticDecoy: def serialize(self) -> dict: return {"seq": self.seq, "x": self.x, "y": self.y, - "depth": self.depth, "life": self.life, + "depth": self.design_depth, "life": self.life, "tether_nm": self.tether_nm, "dead": self.dead, - "state": self.state} + "state": self.state, "tow_heading": self.tow_heading} @classmethod def restore(cls, value: dict, ship) -> TowedAcousticDecoy: result = cls(value["seq"], ship, life_s=value["life"], - tether_nm=value["tether_nm"], depth_m=value["depth"]) + tether_nm=value["tether_nm"], depth_m=value["depth"], + tow_heading=value["tow_heading"]) result.x, result.y = value["x"], value["y"] result.dead, result.state = value["dead"], value["state"] return result @@ -668,8 +701,11 @@ def valid_asw_state(value, torpedo_total: int, torpedo_count: int, nixie_ids = set() for row in nixies: _object(row, {"seq", "x", "y", "depth", "life", "tether_nm", - "dead", "state"}, + "dead", "state", "tow_heading"}, "asw.nixie") + heading = _number(row["tow_heading"], 0, 360, "asw.nixie.tow_heading") + if heading >= 360: + return False seq = _integer(row["seq"], 1, nixie_seq, "asw.nixie.seq") if seq in nixie_ids: return False diff --git a/src/weapons/torpedo.py b/src/weapons/torpedo.py index b51c55fa..9d8a3abc 100644 --- a/src/weapons/torpedo.py +++ b/src/weapons/torpedo.py @@ -41,6 +41,55 @@ def underwater_path_blocked(world, x0, y0, depth0, x1, y1, depth1): ASROC_HELIX_DEG_PER_S = 6.0 +# Seeker discrimination: a new candidate must be this much louder than the +# held one to steal the lock; echoes without Doppler (stationary objects) +# are suppressed; overrun decoys are remembered and ignored. +SEEKER_LOCK_HYSTERESIS_DB = 6.0 +SEEKER_NO_DOPPLER_DB = 10.0 +SEEKER_DOPPLER_MIN_KN = 1.0 +SEEKER_REJECT_MAX = 4 + + +def seeker_level_db(weapon, candidate) -> float: + """Received level of a candidate at a homing seeker (relative dB). + + Source level from the candidate's quietness/radiated level (a decoy's + designed emission), spherical spreading, a depth-mismatch penalty and the + Doppler gate against echoes from stationary objects.""" + distance = max(0.01, math.hypot(candidate.x - weapon.x, candidate.y - weapon.y)) + level = getattr(candidate, "acoustic_level_db", None) + if level is None: + quiet = getattr(candidate, "quiet_factor", None) + level = (20.0 * math.log10(1.0 + 0.8 * (1.0 - quiet())) + if callable(quiet) else 0.0) + offset = getattr(candidate, "source_level_offset_db", None) + if callable(offset): + level += offset() + level -= 20.0 * math.log10(distance) + depth = getattr(candidate, "depth", None) + if depth is not None: + level -= abs(depth - weapon.depth) / 10.0 + speed = getattr(candidate, "speed_kn", None) + if speed is None and hasattr(candidate, "stype"): + speed = getattr(candidate, "speed", None) + if speed is not None and speed < SEEKER_DOPPLER_MIN_KN: + level -= SEEKER_NO_DOPPLER_DB + return level + + +def choose_seeker_target(weapon, viable, current): + """Loudest viable candidate, holding the current lock unless a new one + is louder by the hysteresis margin.""" + if not viable: + return None + scored = [(seeker_level_db(weapon, candidate), index, candidate) + for index, candidate in enumerate(viable)] + best_level, _index, best = max(scored, key=lambda item: (item[0], -item[1])) + if current is not None: + held = next((item for item in scored if item[2] is current), None) + if held is not None and best_level < held[0] + SEEKER_LOCK_HYSTERESIS_DB: + return current + return best WAKE_HOMING_THRESHOLD = 0.15 @@ -121,6 +170,7 @@ class Torpedo: self.wire_ship_out_nm = 0.0 self.wire_stress_s = 0.0 self.last_miss_m = None + self.rejected_ids: list[int] = [] self._search_phase = 0.0 # M15: Serpentin-Phase self._midcourse = course_deg % 360.0 # M15: Draht-Mittelkurs # The persisted timer also carries wire age. @@ -218,10 +268,10 @@ class Torpedo: if underwater_path_blocked(world, self.x, self.y, self.depth, candidate.x, candidate.y, getattr(candidate, "depth", self.target_depth)): continue - depth_error = abs(getattr(candidate, "depth", self.target_depth) - - self.depth) - viable.append((distance + depth_error / 1000.0, candidate)) - return min(viable, key=lambda item: item[0])[1] if viable else None + if getattr(candidate, "id", None) in self.rejected_ids: + continue + viable.append(candidate) + return choose_seeker_target(self, viable, self._seeker_target) def _bearing_to(self, x_nm: float, y_nm: float) -> float: return math.degrees(math.atan2(x_nm - self.x, @@ -359,10 +409,10 @@ class Torpedo: if (not underwater_path_blocked(world, ox, oy, old_depth, hx, hy, hd) and not underwater_path_blocked(world, hx, hy, hd, body.x, body.y, body.depth)): - self.x, self.y, self.depth = hx, hy, hd - self.travel -= step * (1.0 - fraction) - self.target = body if callable(getattr(body, "hit", None)): + self.x, self.y, self.depth = hx, hy, hd + self.travel -= step * (1.0 - fraction) + self.target = body # 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) @@ -370,9 +420,16 @@ class Torpedo: self.state = "HIT" _apply_warhead(body, slant) else: - # A decoy/contact consumes the terminal run but is not a - # reportable target hit. - self.state = "SASE" + # Overran a decoy: no hull, no detonation. Remember it and + # re-attack with the energy that is left. + identity = getattr(body, "id", None) + if identity is not None: + self.rejected_ids = (self.rejected_ids + [identity])[ + -SEEKER_REJECT_MAX:] + self._seeker_target = None + self.seeker_acquired = False + self.target = None + continue return if (underwater_path_blocked(world, ox, oy, old_depth, self.x, self.y, self.depth) @@ -510,9 +567,8 @@ class EnemyTorpedo: world, self.x, self.y, self.depth, candidate.x, candidate.y, getattr(candidate, "depth", 5.0)): continue - stable = getattr(candidate, "seq", getattr(candidate, "id", index)) - viable.append((distance, type(candidate).__name__, stable, candidate)) - return min(viable, key=lambda item: item[:3])[3] if viable else None + viable.append(candidate) + return choose_seeker_target(self, viable, self._seeker_target) def update(self, dt: float, ship, world=None, seeker_candidates=()) -> None: if self.state != "RUN": diff --git a/tests/test_asw_runtime.py b/tests/test_asw_runtime.py index f59b05ca..0c04eacb 100644 --- a/tests/test_asw_runtime.py +++ b/tests/test_asw_runtime.py @@ -153,18 +153,33 @@ def test_asroc_rejects_land_or_out_of_range_datum(): def test_towed_acoustic_decoy_is_bounded_to_ownship_and_finite(): - ship = SimpleNamespace(x=10.0, y=10.0, course=90.0) + ship = SimpleNamespace(x=10.0, y=10.0, course=90.0, speed=15.0) decoy = TowedAcousticDecoy(1, ship, life_s=10, tether_nm=.2, depth_m=10) - assert (decoy.x, decoy.y) == pytest.approx((9.8, 10.0)) + # At the design tow speed it streams at its design depth, almost the + # full cable length astern. + assert decoy.depth == pytest.approx(10.0) + assert decoy.x == pytest.approx(9.8, abs=1e-3) and decoy.y == pytest.approx(10.0) ship.x, ship.course = 20, 0 decoy.update(5, ship, ocean()) - assert (decoy.x, decoy.y) == pytest.approx((20, 10.2)) + # The cable lags the turn: still mostly astern of the old heading. + assert decoy.x < 20.0 and decoy.y > 10.0 decoy.update(5, ship, ocean()) assert decoy.dead and decoy.state == "SASE" assert TowedAcousticDecoy.restore(decoy.serialize(), ship).serialize() \ == decoy.serialize() +def test_towed_decoy_depth_follows_speed_and_cable_parts_when_overspeeding(): + slow = SimpleNamespace(x=0.0, y=0.0, course=0.0, speed=5.0) + fast = SimpleNamespace(x=0.0, y=0.0, course=0.0, speed=20.0) + deep = TowedAcousticDecoy(1, slow, life_s=60, tether_nm=.2, depth_m=10) + shallow = TowedAcousticDecoy(2, fast, life_s=60, tether_nm=.2, depth_m=10) + assert deep.depth > 3 * shallow.depth + fast.speed = 27.0 + shallow.update(1.0, fast, ocean()) + assert shallow.dead + + def test_enemy_torpedo_uses_datum_until_terminal_search(): first = SimpleNamespace(x=1.0, y=0.0, depth=5.0, sunk=False) second = SimpleNamespace(x=-100.0, y=100.0, depth=5.0, sunk=False) diff --git a/tests/test_decoys_countermeasures.py b/tests/test_decoys_countermeasures.py new file mode 100644 index 00000000..626cbdc8 --- /dev/null +++ b/tests/test_decoys_countermeasures.py @@ -0,0 +1,111 @@ +"""Phase 9: decoy acoustics, seeker discrimination and countermeasures.""" + +import copy +import json +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.decoy import Decoy +from src.weapons import torpedo as torpedo_mod +from src.weapons.torpedo import Torpedo + + +class Ocean: + size_nm = 500.0 + + def on_land(self, *args): + return False + + def depth_m(self, *args): + return 3000.0 + + def sonar_path_blocked(self, *args): + return False + + def current_vec(self, *args): + return (0.0, 0.0) + + +def _decoy(life=None): + decoy = Decoy(0.0, 0.0, 50.0, random.Random(1)) + if life is not None: + decoy.life = life + return decoy + + +def test_decoy_battery_fades_its_emission_and_modulates_tonals(): + fresh, tired = _decoy(), _decoy() + tired.life = 0.1 * tired.profile.life_s + assert tired.source_level_offset_db() < fresh.source_level_offset_db() - 5.0 + lines_a, lines_b = fresh.lofar_lines(0.0), fresh.lofar_lines(7.5) + if lines_a: + assert lines_a[0][0] != lines_b[0][0] + + +def test_louder_candidate_wins_and_lock_has_hysteresis(): + weapon = SimpleNamespace(x=0.0, y=0.0, depth=50.0) + quiet = SimpleNamespace(x=1.0, y=0.0, depth=50.0, speed_kn=5.0, + quiet_factor=lambda: 0.9) + loud = SimpleNamespace(x=1.0, y=0.1, depth=50.0, speed_kn=5.0, + quiet_factor=lambda: 0.1) + assert torpedo_mod.choose_seeker_target(weapon, [quiet, loud], None) is loud + slightly = SimpleNamespace(x=1.0, y=0.0, depth=50.0, speed_kn=5.0, + quiet_factor=lambda: 0.85) + assert torpedo_mod.choose_seeker_target(weapon, [quiet, slightly], quiet) is quiet + + +def test_doppler_gate_suppresses_a_stationary_echo(): + weapon = SimpleNamespace(x=0.0, y=0.0, depth=50.0) + moving = SimpleNamespace(x=1.0, y=0.0, depth=50.0, speed_kn=4.0, + quiet_factor=lambda: 0.5) + still = SimpleNamespace(x=0.8, y=0.0, depth=50.0, speed_kn=0.0, + quiet_factor=lambda: 0.5) + assert torpedo_mod.choose_seeker_target(weapon, [moving, still], None) is moving + + +def test_torpedo_overruns_a_decoy_and_reattacks(): + decoy = _decoy() + decoy.x, decoy.y, decoy.depth = 100.05, 100.0, 50.0 + torpedo = Torpedo(100.0, 100.0, 90.0, 50.0, None, 1, speed_kn=360.0, + guidance_x=100.0, guidance_y=100.0) + torpedo.depth = 50.0 + for _ in range(10): + torpedo.update(0.2, seeker_candidates=[decoy], world=Ocean()) + assert torpedo.state == "RUN" + assert decoy.id in torpedo.rejected_ids + assert torpedo.evaluate_seeker_candidates([decoy], Ocean()) is None + + +def test_warship_streams_decoys_on_a_torpedo_launch_and_saves_the_store(): + from src.enemies.surface import SurfaceShip + game = Game(seed=9901, start_menu=False, audio_enabled=False) + warship = SurfaceShip(game.ship.x + 5.0, game.ship.y, game.rng_world, + profile=game.runtime_catalog.surfaces["warship_01"], + side="hostile", doctrine="surface_combatant", + runtime_catalog=game.runtime_catalog) + game.warships = [warship] + game.world.sonar_path_blocked = lambda *args: False + assert warship.countermeasures_left == config.WARSHIP_TORPEDO_DECOYS + from src.sonar.sonar import Contact + target_id = game.subs[0].id + contact = Contact(17, target_id, "ping", "sub") + contact.update_ping(90.0, 5.0, 50.0, 1.0, game.sim_t) + contact.observed_x, contact.observed_y = game.ship.x + 5.0, game.ship.y + contact.player_class = "U_BOOT" + game.sonar.contacts[target_id] = contact + game.target = contact + assert game.launch_torpedo_at(contact, 50.0) is True + assert warship.countermeasures_left == config.WARSHIP_TORPEDO_DECOYS - 1 + assert any(d.source_id == warship.id for d in game.decoys) + 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)) + assert restored.warships[0].countermeasures_left == warship.countermeasures_left + broken = copy.deepcopy(state) + broken["warships"][0]["countermeasures_left"] = config.WARSHIP_TORPEDO_DECOYS + assert not restored._load_save_data(broken) # decoy without store spend