Phase 12: missile flight physics, chaff clouds, CIWS, raiders, helo, buoys

Anti-ship missiles are 3-DOF point masses: boost from the launcher's speed,
sustainer cruise, 20 m sea-skim (5 m terminal) with their own radar horizon
for radar detection and HOJ, inertial mid-course to the launch datum, an
active seeker with a +/-30 deg cone and 1.5 s lock, then proportional
navigation limited to 15 g. ESSM flies PN on its seeker line of sight. The
saved missile age is bounded by the powered flight time.

Chaff lays up to 8 saved clouds off the threat axis that bloom, drift with
the wind and fall out; seduction is the Swerling-1 contest of cloud and
ship echo, reduced when the cloud has not bloomed by the missile's arrival.
CIWS slews its mount (115 deg/s), uses its own latest measurement, and
kills by dispersion and prediction error over the rounds' time of flight;
calibrated to the 1.0.0 leak rate.

Raiders fly coordinated turns at a bank limit and pop up to lock their
fire-control radar (ESM emission) before each salvo. The helicopter burns
more fuel in the hover, drifts against its position hold, and launches and
lands only in a deck-motion window. Sonobuoys drift with current and
windage. Air-to-air combat is documented as out of scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 22:45:18 +02:00
1 parent 2f3b0f21b2
commit 97319f313e
25 files changed
+913 -132

No files matched your search

+3 -3
View File
@@ -1937,7 +1937,7 @@
"help.note.ciws": "CIWS: automatisch abfangend < 1.5 NM (begrenzt).",
"help.note.jammer": "JAMMER-ASMs: jenseits 20 NM nur HOJ-Peilung (Bearing-only).",
"help.note.clutter": "Die Antenne dreht alle 4 s; Seegangsclutter w\u00e4chst mit dem Seegang und Regen d\u00e4mpft, daher kann ein Kontakt einen Umlauf verfehlen.",
"help.note.chaff": "Chaff: Rakete bricht ab (40 %) oder wird kurz blind.",
"help.note.chaff": "Chaff: treibende Wolke lenkt die Rakete ab (40 % nach dem Aufbluehen) oder blendet sie kurz; frueh werfen.",
"help.note.air_defense": "Erst Chaff + Man\u00f6ver, dann ESSM gezielt. VLS-Zellen sind knapp.",
"help.note.hfdf": "HFDF: Peilung und Frequenz sendender U-Boote (\u00b18\u00b0 Bodenwelle, \u00b116\u00b0 Raumwelle).",
"help.note.teletype": "Teletype: HQ-Bulletins, Wetter, ROE-\u00c4nderungen.",
@@ -1949,7 +1949,7 @@
"help.note.quiet": "LEISE reduziert Eigenl\u00e4rm, begrenzt die Fahrt aber auf 12 kn.",
"help.note.engine_tactic": "Schnell anrennen (FULL/FLANK), dann SLOW zum Lauschen.",
"help.note.helo_stores": "Der HSP-5 hat endliche Bojen- und Torpedovorraete; Starts laden nicht nach.",
"help.note.helo_fuel": "Treibstoffende vor der Landung bedeutet Verlust des HSP-5.",
"help.note.helo_fuel": "Schweben verbraucht mehr Treibstoff; Treibstoffende vor der Landung bedeutet Verlust des HSP-5. Start und Landung warten auf ruhiges Deck.",
"help.note.buoys": "PASSIV-Bojen liefern Peilungen (zwei kreuzende Bojen ergeben einen Fix); AKTIV-Bojen liefern Entfernung und Peilung. Batterie 60 min.",
"help.note.helo_roe": "Das Ziel muss vor dem Lufttorpedo-Einsatz als U-Boot klassifiziert sein.",
"help.note.shared_controls": "H/B/D sind auch an der Waffenstation verfuegbar. Das Tauchsonar hat eigene Kontakte, Tiefensteuerung, Aktiv-Ping und OPZ-Freigabe.",
@@ -2602,7 +2602,7 @@
"bridge.line.weather_detail": "Wind aus {direction} Grad / {speed} kn | Regen {rain} | Sicht {visibility} NM",
"weather.day": "TAG",
"weather.night": "NACHT",
"runtime.helo.weather_unsafe": "Flugwetter ausserhalb der Einsatzgrenzen",
"runtime.helo.weather_unsafe": "Flugwetter oder Deckbewegung ausserhalb der Einsatzgrenzen",
"engine.quiet_limit": "LEISE (max 12 kn)",
"engine.limit.down": "Maschinenausfall",
"engine.limit.damaged": "Maschinenschaden",
+3 -3
View File
@@ -1937,7 +1937,7 @@
"help.note.ciws": "CIWS intercepts automatically inside 1.5 NM (limited ammunition).",
"help.note.jammer": "Jammer ASMs beyond 20 NM provide only a HOJ bearing.",
"help.note.clutter": "The antenna sweeps every 4 s; sea clutter grows with sea state and rain attenuates, so a contact may miss a sweep.",
"help.note.chaff": "Chaff makes a missile break lock (40%) or blinds it briefly.",
"help.note.chaff": "Chaff lays a drifting cloud that seduces a missile (40% once bloomed) or blinds it briefly; fire early.",
"help.note.air_defense": "Use chaff and maneuver first, then engage with ESSM. VLS cells are scarce.",
"help.note.hfdf": "HFDF gives bearings and frequency of transmitting submarines (+/-8 degrees ground wave, +/-16 sky wave).",
"help.note.teletype": "Teletype carries HQ bulletins, weather, and ROE changes.",
@@ -1949,7 +1949,7 @@
"help.note.quiet": "QUIET reduces own noise but limits speed to 12 kn.",
"help.note.engine_tactic": "Sprint in (FULL/FLANK), then use SLOW to listen.",
"help.note.helo_stores": "HSP-5 has finite buoy and torpedo stores; launches do not replenish them.",
"help.note.helo_fuel": "Running out of fuel before landing loses HSP-5.",
"help.note.helo_fuel": "Hovering burns fuel faster; running out before landing loses HSP-5. Launch and landing wait for a calm deck.",
"help.note.buoys": "PASSIVE buoys give bearings (two crossing buoys give a fix); ACTIVE buoys give range and bearing. Batteries last 60 min.",
"help.note.helo_roe": "The target must be classified as submarine before an air-torpedo attack.",
"help.note.shared_controls": "H/B/D are also available at Weapons. Helicopter dipping sonar has its own contacts, depth control, active ping, and CIC release.",
@@ -2602,7 +2602,7 @@
"bridge.line.weather_detail": "Wind from {direction} deg / {speed} kn | Rain {rain} | Vis {visibility} NM",
"weather.day": "DAY",
"weather.night": "NIGHT",
"runtime.helo.weather_unsafe": "Flight weather outside operating limits",
"runtime.helo.weather_unsafe": "Flight weather or deck motion outside operating limits",
"engine.quiet_limit": "QUIET (max 12 kn)",
"engine.limit.down": "Machinery failure",
"engine.limit.damaged": "Machinery damage",
+2 -1
View File
@@ -47,7 +47,8 @@ Ablauf Luftverteidigung (Flugkörper im Anflug):
## Tipps für Profis {#opz-tips}
- Radar ist eine Aussendung, die feindliches ESM auffassen kann. Radare abschalten (EMCON), wenn Tarnung wichtiger ist als das Luftlagebild.
- Störende Flugkörper jenseits 20 sm liefern nur eine Home-on-Jam-Peilung (HOJ); Entfernung kommt später.
- Seezielflugkörper fliegen in etwa 20 m Höhe (auf den letzten 5 sm in 5 m): das Radar sieht sie erst innerhalb etwa 20 sm, und ein störender Flugkörper liefert bis zum Durchbrennen nur eine Home-on-Jam-Peilung (HOJ). Flugkörper fliegen trägheitsgelenkt zu ihrem Startdatum; dann muss der Suchkopf das Schiff 1,5 s in seinem Kegel haben, bevor er ansteuert. Angriffsflugzeuge steigen vor jeder Salve für einige Sekunden auf etwa 300 m, um ihr Feuerleitradar aufzuschalten (eine ESM-Warnung und ein früher Radarkontakt).
- Düppel legt neben dem Schiff eine Wolke, die in etwa 3 s aufblüht und mit dem Wind treibt; früh genug werfen, damit die Wolke aufblühen kann. Das CIWS muss erst auf den Flugkörper schwenken und trifft meist auf den letzten paar hundert Metern.
- Zugehörigkeit ist Ihr Vermerk. Ein als FREUND oder NEUTRAL markierter Kontakt sperrt jeden Torpedoschuss darauf.
- `J` vergibt eine gemeinsame Track-ID, die die ganze Crew (und Remote-Crew-Browser) sieht.
- `Enter` bestätigt einen Angriff auf einen Live-Kontakt (echter Verkehr), nachdem Sie ihn als feindlich klassifiziert haben; auf unklassifizierte Kontakte wird nie automatisch gefeuert.
+2 -1
View File
@@ -47,7 +47,8 @@ Air defence sequence (missile inbound):
## Pro tips {#opz-tips}
- Radar is a transmission that hostile ESM can intercept. Switch radars off (EMCON) when stealth matters more than the air picture.
- Jamming missiles beyond 20 NM give only a home-on-jam (HOJ) bearing; expect range later.
- Anti-ship missiles skim at about 20 m (5 m in the last 5 NM): radar sees them only inside about 20 NM, and a jamming missile gives only a home-on-jam (HOJ) bearing until it burns through. Missiles fly inertially to their launch datum, then their seeker needs the ship inside its cone for 1.5 s before homing; attack aircraft pop up to about 300 m for a few seconds to lock their fire-control radar before each salvo (an ESM warning and an early radar contact).
- Chaff lays a cloud beside the ship that blooms in about 3 s and drifts with the wind; fire it early enough for the cloud to bloom. CIWS must first slew onto the missile and kills mostly in the last few hundred metres.
- Affiliation is your annotation. Marking a contact FRIEND or NEUTRAL blocks every torpedo shot on it.
- `J` gives a track a shared ID that the whole crew (and Remote Crew browsers) sees.
- `Enter` confirms an engagement against a live (real-world traffic) contact after you classified it hostile; nothing fires automatically on unclassified contacts.
+3 -3
View File
@@ -25,10 +25,10 @@ Die Station hat vier Seiten (nochmals `8` blättert); sie öffnet auf Seite 3.
AKTIV: Entfernung + Peilung alle 30 s aktiv 14 sm
```
- **Kraftstoff:** 2 Stunden. Der Helikopter kehrt automatisch zurück, wenn nur noch die 20-Minuten-Reserve bleibt. Leerfliegen vor der Landung kostet die Maschine.
- **Startgrenzen:** Wind bis 32 kn, Seitenwind bis 22 kn, Sicht mindestens 2 sm, Seegang höchstens 5, einsatzbereites Flugdeck.
- **Kraftstoff:** 2 Stunden im Vorwärtsflug; im Schwebeflug (Tauchsonar) verbraucht er 1,3-mal so schnell. Der Helikopter kehrt automatisch zurück, wenn nur noch die 20-Minuten-Reserve bleibt. Leerfliegen vor der Landung kostet die Maschine. Im Schwebeflug drückt ihn der Wind etwas von seinem Schwebepunkt nach Lee.
- **Startgrenzen:** Wind bis 32 kn, Seitenwind bis 22 kn, Sicht mindestens 2 sm, Seegang höchstens 5, einsatzbereites Flugdeck und ein ruhiges Deckfenster (Rollen höchstens 8 Grad, Stampfen höchstens 3,5 Grad). Auch die Landung wartet auf ein solches Fenster; gegen die See gedreht stampft das Schiff weniger.
- **Tauchsonar:** Tiefe 15-300 m (Standard 75 m, mindestens 10 m über Grund), passiv 18 sm mit +/-2 Grad, aktiver Ping 14 sm mit 30 s Abklingzeit. Tauchen braucht Wind bis 30 kn und 1 sm Sicht.
- **Sonarbojen:** 5 je Einsatz, 8 sm Reichweite, 60 min Batterie. PASSIV-Bojen liefern Peilungen (wie DIFAR); AKTIV-Bojen liefern Entfernung und Peilung alle 30 s (wie DICASS).
- **Sonarbojen:** 5 je Einsatz, 8 sm Reichweite, 60 min Batterie; sie treiben mit der Strömung und etwas mit dem Wind. PASSIV-Bojen liefern Peilungen (wie DIFAR); AKTIV-Bojen liefern Entfernung und Peilung alle 30 s (wie DICASS).
- **Leichttorpedo:** 2 je Einsatz, 55 kn, 12 sm, von der Helikopterposition Richtung Datum geworfen, ohne Draht. Das Ziel muss als U-Boot klassifiziert sein.
## Tasten {#helicopter-keys}
+3 -3
View File
@@ -25,10 +25,10 @@ The station has four pages (`8` again cycles them); it opens on page 3.
ACTIVE: range + bearing every 30 s active 14 NM
```
- **Fuel:** 2 hours. The helicopter returns automatically when only the 20-minute reserve remains. Running dry before landing loses the aircraft.
- **Launch limits:** wind up to 32 kn, crosswind up to 22 kn, visibility at least 2 NM, sea state 5 or less, working flight deck.
- **Fuel:** 2 hours in forward flight; hovering (dipping) burns 1.3 times as fast. The helicopter returns automatically when only the 20-minute reserve remains. Running dry before landing loses the aircraft. In the hover the wind pushes it slightly downwind of its hover point.
- **Launch limits:** wind up to 32 kn, crosswind up to 22 kn, visibility at least 2 NM, sea state 5 or less, working flight deck, and a deck-motion window (roll within 8 degrees, pitch within 3.5 degrees). Landing also waits for such a window; turning into the sea reduces pitching.
- **Dipping sonar:** depth 15-300 m (default 75 m, at least 10 m above the seabed), passive 18 NM with +/-2 degrees, active ping 14 NM with 30 s cooldown. Dipping needs wind up to 30 kn and visibility of 1 NM.
- **Sonobuoys:** 5 per sortie, 8 NM range, 60 min battery. PASSIVE buoys give bearings (like DIFAR); ACTIVE buoys give range and bearing every 30 s (like DICASS).
- **Sonobuoys:** 5 per sortie, 8 NM range, 60 min battery; they drift with the current and a little with the wind. PASSIVE buoys give bearings (like DIFAR); ACTIVE buoys give range and bearing every 30 s (like DICASS).
- **Lightweight torpedo:** 2 per sortie, 55 kn, 12 NM, dropped from the helicopter's position towards the datum, no wire. The target must be classified as submarine.
## Keys {#helicopter-keys}
+2 -2
View File
@@ -36,9 +36,9 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| Feindtorpedo | 28 kn, 30 sm, zielsuchend ab 3 sm |
| 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 |
| CIWS | 1,5 sm, 180 Schuss, braucht Freigabe; 115 Grad/s Schwenken, eigenes Folgeradar innerhalb 3 sm |
| Flak-Geschütz | 240 Schuss, braucht Freigabe |
| Düppel | 6 Ladungen, 8 sm, 40 % Zielverlust |
| Düppel | 6 Ladungen, 8 sm, 40 % Zielverlust nach dem Aufblühen; Wolke treibt 90 s mit dem Wind |
## Eigenes Schiff {#ref-ship}
+2 -2
View File
@@ -36,9 +36,9 @@ All values are the defaults of the current game version. Custom difficulty and m
| Hostile torpedo | 28 kn, 30 NM, homes from 3 NM |
| 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 |
| CIWS | 1.5 NM, 180 rounds, needs release; 115 deg/s slew, own track radar inside 3 NM |
| AA gun | 240 rounds, needs release |
| Chaff | 6 rounds, 8 NM, 40 % break-lock |
| Chaff | 6 rounds, 8 NM, 40 % break-lock when bloomed; cloud drifts with the wind for 90 s |
## Own ship {#ref-ship}
+13 -13
View File
@@ -121,11 +121,11 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| ~~**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 radar horizon**~~ | **Closed (Phase 12).** The ASM body has its own altitude (20 m cruise, 5 m terminal); radar detection and the HOJ bearing both require line of sight over the horizon. | — |
| ~~**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**~~ | **Closed (Phases 8/10).** Shock-factor damage (near misses no longer sink), progressive flooding above 30 %, radar lost above 60 % and missile launch above 75 % damage. | — |
| ~~**No evasive manoeuvres**~~ | **Closed.** Combatants turn away at flank speed on a heard launch (W2, state saved in Phase 0) and stream decoys (Phase 9). | — |
| **No weapon systems modelling** | ASM/ASROC are simple projectiles; no fire-control solution error | Guidance accuracy, warhead proximity fuze, multi-target saturation |
| ~~**No weapon systems modelling**~~ | **Closed (Phases 8/12).** Warship ASMs fly to the datum of the launcher's own (noisy) sensor contact, so fire-control error carries into the shot; 3-DOF missile with seeker FOV, lock delay and PN; torpedo and ASROC proximity fuze with shock-factor damage; salvos saturate the two ESSM fire channels and the CIWS mount. | — |
### 3.3 Data structures touched
@@ -217,19 +217,19 @@ All closed in Phase 9:
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No flight dynamics** | Fixed altitude, constant speed, rate-limited turn | Climb/dive rate, speed- altitude coupling, turn rate vs speed, engine-out |
| ~~**No flight dynamics**~~ | **Closed (Phase 12).** Raiders fly coordinated turns at a 56 deg bank limit (rate = g tan(bank)/v) and climb/descend at a limited vertical speed; missiles are 3-DOF point masses (boost, sustainer, altitude control, g-limited turns). Civil/military transit flights keep standard-rate turns at constant altitude (their cruise profile); engine failures are out of scope. | — |
| ~~**No radar horizon**~~ | **Fixed (2026-09) for airframes.** Raiders already used `radar_horizon_nm()`; regular civil/military `flights` now use it too (flat `FLIGHT_RADAR_ALTITUDE_M`). **Still open for the ASM body itself** (see below): its own search-radar detection in `game.py._update_air_picture` uses flat `air_eff` with no altitude/horizon term, so a sea-skimmer is currently seen by search radar at the same range as a 60 m-altitude aircraft. | — |
| **No ASM boost phase** | ASM flies at constant speed from launch | Boost motor (first seconds), then cruise; speed affects intercept geometry |
| **No seeker physics** | ESSM/ASM homing itself is a range gate + turn-rate limit (unchanged) | Seeker FOV, lock-on delay, jamming resistance (burn-through is binary) |
| ~~**No ASM boost phase**~~ | **Closed (Phase 12).** Launched rounds boost from the launcher's speed at 60 m/s^2, then the sustainer holds cruise; the saved age is bounded by the powered flight time (range at cruise plus boost). | — |
| ~~**No seeker physics**~~ | **Closed (Phase 12).** ASM: inertial mid-course to the launch datum, active seeker with a +/-30 deg field of view and 1.5 s lock, then proportional navigation (N = 4) limited to 15 g. ESSM: PN on the seeker LOS rate within its airframe turn limit. | — |
| ~~**No ESM warning for inbound ASM**~~ | **Fixed (2026-09).** ASM `seeker_active()` stays silent mid-course (INS-only) and radiates once inside `seeker_active_range_nm` (18 NM); the seeker's own fingerprint (9.0-9.5 GHz, pulse-Doppler) feeds `_update_esm_picture` as a distinct RWR track, independent of the existing HOJ/jammer path (`asm.py`, `game.py._asm_seeker_emitter`). Not yet catalogued for classification in `data/contacts/*` emitters, so `rank_emitters()` won't positively ID it as "missile" — an intentional ambiguity, but worth revisiting. | — |
| **ASM body ignores radar horizon** | Regular (non-jamming) radar detection of the missile airframe uses flat `air_eff` range (`game.py:3141`), unlike raiders/warships/civilians/flights which all use `radar_horizon_nm()` | Give ASM a low `altitude_m` (~10-20 m) and route its radar branch through the same horizon formula, so search radar only picks it up very late, consistent with the new ESM early warning |
| **Raider has no attack-altitude profile** | `altitude_m` is a fixed profile constant across APPROACH/ATTACK/RETREAT | Brief pop-up (e.g. 60 m → few hundred m) during ATTACK for target acquisition before missile release, then back down; ties into `radar_horizon_nm()` (a visible radar "spike") and could feed a raider fire-control-radar ESM emission during the pop-up window |
| **No CIWS physics** | CIWS is a probability roll per cycle with range falloff | Gun barrel elevation/traverse rate; radar-illuminated tracking; round-in-air time |
| **No chaff physics** | Chaff is a timer (`chaff_left`); ASM goes straight or breaks | Chaff cloud drift, radar reflectivity, seeker discrimination |
| **No ECM on own ship** | Only chaff (soft-kill) and CIWS/ESSM (hard-kill) | Radar jamming, GPS spoofing (less relevant 1970s but modern) |
| **Helicopter: no hover dynamics** | Hovering = zero motion; no wind drift | Wind drift, rotor downwash, fuel consumption in hover |
| **Sonobuoy: no drift** | Fixed position after deployment | Current drift; battery decay already present |
| **No air-to-air threat** | Only ASM + raiders; no friendly CAP, no air-to-air | Out of scope for U-Jagd but noted |
| ~~**ASM body ignores radar horizon**~~ | **Closed (Phase 12).** See radar horizon above: a sea-skimmer appears at about 20 NM (15 NM in the terminal phase). | — |
| ~~**Raider has no attack-altitude profile**~~ | **Closed (Phase 12).** Each salvo needs a pop-up to 300 m and a 4 s fire-control lock; the fire-control radar is an ESM emission only during the pop-up, and the higher raider crosses the radar horizon earlier. | — |
| ~~**No CIWS physics**~~ | **Closed (Phase 12).** Mount slews at 115 deg/s and fires only on target; the fire control uses its own latest measurement; the CIWS radar holds missiles inside 3 NM; burst kill from dispersion (2 mrad) and prediction error over the rounds' time of flight; bursts that would arrive after impact cannot kill. Calibrated to the 1.0.0 leak rate. | — |
| ~~**No chaff physics**~~ | **Closed (Phase 12).** Up to 8 saved chaff clouds laid off the threat axis, blooming over 3 s, drifting with the wind and falling out after 90 s; seduction is the Swerling-1 contest between cloud and ship echo, reduced when the cloud has not bloomed by the missile's arrival; a seduced missile steers to the cloud. | — |
| ~~**No ECM on own ship**~~ | **Closed.** The ELOKA station's ECM jammer (noise, RGPO/VGPO, false targets) acts on missile seekers; GPS spoofing is out of scope for this setting. | — |
| ~~**Helicopter: no hover dynamics**~~ | **Closed (Phase 12).** Hover burns fuel 1.3x faster; wind pushes the aircraft off its (saved) hover point against the pilot's position hold; launch and recovery wait for a deck-motion window (roll 8 deg, pitch 3.5 deg). | — |
| ~~**Sonobuoy: no drift**~~ | **Closed (Phase 12).** Buoys drift with the surface current (which carries the wind drift) plus 2 % windage. | — |
| **No air-to-air threat** | **Out of scope (by design).** U-Jagd is an ASW frigate simulation without fighters or CAP; hostile aircraft are engaged only by own ship air defence. | — |
### 6.3 Data structures touched
+152 -56
View File
@@ -6,12 +6,16 @@ Zeitbasis: Simulationssekunden; bei 1x identisch zu Echtzeit.
import math
from src.core import config
from src.air import chaff
from src.physics import missile
from src.weapons.air_defense import air_defense_loadout
from src.weapons.torpedo import Torpedo
class ASM:
"""Feindliche Schiffs-Rakete: skimmt auf ~20 m, optionaler ESM-Jammer.
"""Feindliche Schiffs-Rakete: 3-DOF-Punktmasse (Boost, Seeziel-Flughoehe,
INS-Mittelkurs zum Startdatum, aktiver Suchkopf mit Sichtfeld und
Aufschaltzeit, Proportionalnavigation mit g-Limit), optionaler ESM-Jammer.
Zustand: LAUF | CHAFF | ABGEFANGEN | TREFFER | VERLOREN
"""
@@ -19,20 +23,32 @@ class ASM:
# Bounded gameplay endurance, not a real missile specification.
_DEFAULT_PROFILE = air_defense_loadout()["asm"]
RANGE_NM = _DEFAULT_PROFILE["range_nm"]
LIFE_S = RANGE_NM / config.kn_to_nm_per_s(_DEFAULT_PROFILE["speed_kn"])
LIFE_S = missile.flight_time_bound_s(RANGE_NM, _DEFAULT_PROFILE["speed_kn"])
side = "hostile"
sensor_domain = "air"
def __init__(self, x_nm: float, y_nm: float, course_deg: float, seq: int,
rng, profile=None):
rng, profile=None, *, launch_speed_kn: float | None = None,
altitude_m: float | None = None, datum=None):
self.profile = profile or self._DEFAULT_PROFILE
self.profile_key = self.profile["key"]
self.speed_kn = self.profile["speed_kn"]
self.cruise_kn = self.profile["speed_kn"]
# A round created in flight (legacy callers, tests) is already at
# cruise; a launched round boosts from its launcher's speed.
self.speed_kn = (self.cruise_kn if launch_speed_kn is None
else max(0.0, float(launch_speed_kn)))
self.boosting = self.speed_kn < self.cruise_kn
self.range_nm = self.profile["range_nm"]
self.life_s = self.range_nm / config.kn_to_nm_per_s(self.speed_kn)
self.life_s = missile.flight_time_bound_s(self.range_nm, self.cruise_kn)
self.x = x_nm
self.y = y_nm
self.course = course_deg % 360.0
self.altitude_m = (missile.CRUISE_ALTITUDE_M if altitude_m is None
else max(0.0, float(altitude_m)))
if datum is None:
datum = (x_nm + self.range_nm * math.sin(math.radians(self.course)),
y_nm - self.range_nm * math.cos(math.radians(self.course)))
self.datum_x, self.datum_y = float(datum[0]), float(datum[1])
self.seq = seq
self.sensor_seed = int(seq)
self.rng = rng
@@ -40,8 +56,12 @@ class ASM:
self.jammer = rng.random() < self.profile["jam_probability"]
self.chaff_left = 0.0
self.broken = False
self.chaff_cloud = None # seq of the cloud that seduced the seeker
self.travel = 0.0
self.age_s = 0.0
self.lock_s = 0.0
self.locked = False
self.los_prev = None
# --- Abfragen ---
@@ -66,64 +86,130 @@ class ASM:
# --- Wirkung ---
def launch_chaff(self, rng, softkill_profile=None) -> bool:
"""Apply the profiled softkill result and temporary seeker blindness."""
def launch_chaff(self, rng, softkill_profile=None, cloud_seq=None,
arrival_s=None) -> bool:
"""A chaff cloud blooms in the seeker's resolution cell. The seeker
transfers to it when its echo exceeds the fluctuating (Swerling-1)
ship echo: P = 1 - exp(-sigma_chaff / sigma_ship), which the profiled
defeat probability expresses. Otherwise the cloud only confuses the
range gate for the effect duration."""
if self.state != "LAUF":
return False
softkill_profile = softkill_profile or air_defense_loadout()["softkill"]
self.state = "CHAFF"
self.chaff_left = rng.uniform(*softkill_profile["effect_duration_s"])
self.broken = rng.random() < softkill_profile["defeat_probability"]
probability = softkill_profile["defeat_probability"]
if arrival_s is not None:
probability = chaff.seduction_probability(probability, arrival_s)
self.broken = rng.random() < probability
self.chaff_cloud = cloud_seq if self.broken else None
return self.broken
# --- Physik ---
def update(self, dt: float, frigate, world=None, ecm_effect=None) -> None:
def _ecm_decision(self, ecm_effect):
effectiveness = (max(0.0, min(.7, float(ecm_effect)))
if isinstance(ecm_effect, (int, float))
else max(0.0, min(.7, float(getattr(
ecm_effect, "effectiveness", 0.0)))))
technique = getattr(ecm_effect, "technique", None)
home_on_jam = bool(getattr(ecm_effect, "hoj_exposure", False))
deceived = (effectiveness > 0.0 and not home_on_jam
and self.rng.random() < effectiveness)
return deceived, technique
def _turn_towards(self, bearing: float, rate_deg_s: float, dt: float) -> None:
diff = config.angle_diff_deg(bearing, self.course)
self.course = (self.course + config.clamp(
diff, -rate_deg_s * dt, rate_deg_s * dt)) % 360.0
def _guide(self, h: float, frigate, world, deceived: bool, technique) -> None:
distance = self.distance_nm(frigate)
bearing = math.degrees(math.atan2(frigate.x - self.x,
-(frigate.y - self.y))) % 360.0
visible = (distance <= self.profile["seeker_active_range_nm"]
and missile.in_field_of_view(self.course, bearing)
and not (world is not None and getattr(
world, "land_blocks_line", lambda *args: False)(
self.x, self.y, frigate.x, frigate.y)))
if not visible:
self.lock_s, self.locked, self.los_prev = 0.0, False, None
elif not self.locked:
self.lock_s += h
if self.lock_s >= missile.SEEKER_LOCK_S:
self.locked, self.los_prev = True, bearing
if not self.locked:
# Inertial mid-course towards the launch datum.
if math.hypot(self.datum_x - self.x, self.datum_y - self.y) > .05:
self._turn_towards(math.degrees(math.atan2(
self.datum_x - self.x, -(self.datum_y - self.y))) % 360.0,
self.profile["turn_rate_deg_s"], h)
return
if deceived and technique != "false_targets":
# RGPO/VGPO break the seeker's gate for this update.
return
if deceived:
# A coherent phantom is a bounded angular gate displacement.
self._turn_towards((bearing + (25.0 if self.seq % 2 else -25.0)) % 360.0,
missile.max_turn_rate_deg_s(self.speed_kn), h)
self.los_prev = None
return
if self.los_prev is None:
self.los_prev = bearing
rate = missile.pn_turn_rate_deg_s(bearing, self.los_prev, h, self.speed_kn)
# Close the initial heading error inside the seeker cone as well.
pursuit = config.angle_diff_deg(bearing, self.course)
limit = missile.max_turn_rate_deg_s(self.speed_kn)
rate = config.clamp(rate + 0.5 * pursuit, -limit, limit)
self.course = (self.course + rate * h) % 360.0
self.los_prev = bearing
def update(self, dt: float, frigate, world=None, ecm_effect=None,
chaff_target=None) -> None:
if self.state in ("ABGEFANGEN", "TREFFER", "VERLOREN"):
return
run_dt = min(dt, max(0.0, self.life_s - self.age_s))
if self.state == "CHAFF":
# Störblindheit: gerader Kurs weiter, ohne Korrekturen
if self.broken:
run_dt = min(run_dt, max(0.0, self.chaff_left))
self.chaff_left -= dt
elif not self.jamming(frigate):
effectiveness = (max(0.0, min(.7, float(ecm_effect)))
if isinstance(ecm_effect, (int, float))
else max(0.0, min(.7, float(getattr(
ecm_effect, "effectiveness", 0.0)))))
technique = getattr(ecm_effect, "technique", None)
home_on_jam = bool(getattr(ecm_effect, "hoj_exposure", False))
deceived = (effectiveness > 0.0 and not home_on_jam
and self.rng.random() < effectiveness)
desired = math.degrees(math.atan2(frigate.x - self.x,
-(frigate.y - self.y))) % 360.0
if deceived and technique == "false_targets":
# A coherent phantom is represented as a bounded angular gate
# displacement; no hidden target object is introduced.
desired = (desired + (25.0 if self.seq % 2 else -25.0)) % 360.0
if not deceived or technique == "false_targets":
# Noise exposes the transmitting ship to HOJ. RGPO/VGPO break
# the seeker's gate for this substep; false targets pull it.
diff = config.angle_diff_deg(desired, self.course)
self.course = (self.course + config.clamp(
diff, -self.profile["turn_rate_deg_s"] * dt,
self.profile["turn_rate_deg_s"] * dt)) % 360.0
ox, oy = self.x, self.y
self.age_s = min(self.life_s, self.age_s + dt)
step = min(config.kn_to_nm_per_s(self.speed_kn) * run_dt,
max(0.0, self.range_nm - self.travel))
self.x += step * math.sin(math.radians(self.course))
self.y -= step * math.cos(math.radians(self.course))
self.travel += step
if Torpedo._swept_dist(self, frigate, ox, oy) <= self.profile["hit_distance_nm"]:
self.state = "TREFFER"
elif (self.travel >= self.range_nm or self.age_s >= self.life_s
or (world is not None and not (0 <= self.x <= world.size_nm
and 0 <= self.y <= world.size_nm))):
self.state = "VERLOREN"
elif self.state == "CHAFF" and self.chaff_left <= 0.0:
self.state = "VERLOREN" if self.broken else "LAUF"
deceived, technique = (self._ecm_decision(ecm_effect)
if self.state == "LAUF" and self.locked
and ecm_effect is not None else (False, None))
steps = min(1000, max(1, math.ceil(dt / missile.GUIDANCE_SUBSTEP_S - 1e-9)))
h = dt / steps
for _ in range(steps):
run = min(h, max(0.0, self.life_s - self.age_s))
if self.state == "CHAFF":
if self.broken:
run = min(run, max(0.0, self.chaff_left))
if chaff_target is not None and run > 0.0:
# Seduced: the seeker homes on the chaff centroid.
self._turn_towards(math.degrees(math.atan2(
chaff_target.x - self.x, -(chaff_target.y - self.y)))
% 360.0, missile.max_turn_rate_deg_s(self.speed_kn), run)
self.chaff_left -= h
elif run > 0.0:
self._guide(run, frigate, world, deceived, technique)
if self.boosting:
self.speed_kn = missile.speed_step(self.speed_kn, self.cruise_kn, h)
self.boosting = self.speed_kn < self.cruise_kn
self.altitude_m = missile.altitude_step(
self.altitude_m, missile.commanded_altitude_m(
self.distance_nm(frigate)), h)
ox, oy = self.x, self.y
self.age_s = min(self.life_s, self.age_s + h)
step = min(config.kn_to_nm_per_s(self.speed_kn) * run,
max(0.0, self.range_nm - self.travel))
self.x += step * math.sin(math.radians(self.course))
self.y -= step * math.cos(math.radians(self.course))
self.travel += step
if Torpedo._swept_dist(self, frigate, ox, oy) <= self.profile["hit_distance_nm"]:
self.state = "TREFFER"
elif (self.travel >= self.range_nm or self.age_s >= self.life_s
or (world is not None and not (0 <= self.x <= world.size_nm
and 0 <= self.y <= world.size_nm))):
self.state = "VERLOREN"
elif self.state == "CHAFF" and self.chaff_left <= 0.0:
self.state = "VERLOREN" if self.broken else "LAUF"
self.chaff_cloud = None
if self.state != "LAUF" and self.state != "CHAFF":
return
class ESSM:
@@ -154,6 +240,7 @@ class ESSM:
* math.cos(math.radians(self.course)))
if guidance_y is None else guidance_y)
self.seeker_acquired = False
self.los_prev = None
def update(self, dt: float, candidates=None, world=None) -> None:
if self.state != "LAUF":
@@ -183,10 +270,19 @@ class ESSM:
else (self.guidance_x, self.guidance_y))
desired = math.degrees(math.atan2(aim_x - self.x,
-(aim_y - self.y))) % 360.0
diff = config.angle_diff_deg(desired, self.course)
self.course = (self.course + config.clamp(
diff, -self.profile["turn_rate_deg_s"] * dt,
self.profile["turn_rate_deg_s"] * dt)) % 360.0
limit = self.profile["turn_rate_deg_s"] # airframe lateral-g limit
if self.seeker_acquired and self.los_prev is not None and dt > 0.0:
# Terminal proportional navigation on the seeker's LOS rate, plus
# a pursuit term that closes the initial heading error.
los_rate = config.angle_diff_deg(desired, self.los_prev) / dt
rate = config.clamp(missile.PN_GAIN * los_rate + 0.5 * config.angle_diff_deg(
desired, self.course), -limit, limit)
self.course = (self.course + rate * dt) % 360.0
else:
diff = config.angle_diff_deg(desired, self.course)
self.course = (self.course + config.clamp(
diff, -limit * dt, limit * dt)) % 360.0
self.los_prev = desired if self.seeker_acquired else None
ox, oy = self.x, self.y
step = min(config.kn_to_nm_per_s(self.profile["speed_kn"]) * dt,
max(0.0, self.profile["range_nm"] - self.travel))
+82
View File
@@ -0,0 +1,82 @@
"""Chaff clouds: drifting, blooming radar reflectors (own ship softkill).
A rocket lays the cloud beside the ship, off the threat axis, inside the
missile seeker's resolution cell. The dipoles bloom to full cross-section
over a few seconds, drift with the wind and fall out after about 90 s. The
missile decides between cloud and ship when it is launched against (see
``ASM.launch_chaff``); a cloud that has not bloomed by the time the missile
arrives is less likely to win.
"""
from __future__ import annotations
import math
from src.core import config
MAX_CLOUDS = 8
BLOOM_S = 3.0
LIFE_S = 90.0
LAY_DISTANCE_NM = 0.4
LAY_OFFSET_DEG = 60.0
FIELDS = frozenset({"seq", "x", "y", "age_s"})
class ChaffCloud:
def __init__(self, seq: int, x: float, y: float, age_s: float = 0.0):
self.seq = int(seq)
self.x = float(x)
self.y = float(y)
self.age_s = float(age_s)
@property
def active(self) -> bool:
return self.age_s < LIFE_S
def bloom(self) -> float:
"""Fraction of the full cross-section reached."""
return 1.0 - math.exp(-self.age_s / BLOOM_S)
def update(self, dt: float, wind_from_deg: float, wind_speed_kn: float) -> None:
drift = config.kn_to_nm_per_s(wind_speed_kn) * dt
towards = math.radians((wind_from_deg + 180.0) % 360.0)
self.x += drift * math.sin(towards)
self.y -= drift * math.cos(towards)
self.age_s += dt
def to_dict(self) -> dict:
return dict(seq=self.seq, x=self.x, y=self.y, age_s=self.age_s)
def lay_position(ship_x: float, ship_y: float, threat_bearing_deg: float,
seq: int) -> tuple[float, float]:
"""Cloud position off the threat axis (alternating sides)."""
side = LAY_OFFSET_DEG if seq % 2 else -LAY_OFFSET_DEG
bearing = math.radians((threat_bearing_deg + side) % 360.0)
return (ship_x + LAY_DISTANCE_NM * math.sin(bearing),
ship_y - LAY_DISTANCE_NM * math.cos(bearing))
def seduction_probability(defeat_probability: float, arrival_s: float) -> float:
"""Swerling-1 ship echo against the cloud echo at the missile's arrival.
The profiled defeat probability is the fully bloomed case,
P = 1 - exp(-sigma_c / sigma_s); a young cloud has only the bloom
fraction of sigma_c."""
p = max(0.0, min(1.0, defeat_probability))
if p >= 1.0:
return 1.0 if arrival_s > 0.0 else 0.0
ratio = -math.log(1.0 - p)
bloom = 1.0 - math.exp(-max(0.0, arrival_s) / BLOOM_S)
return 1.0 - math.exp(-ratio * bloom)
def valid_row(row) -> bool:
def number(value, low, high):
return (type(value) in (int, float) and math.isfinite(value)
and low <= value <= high)
return (isinstance(row, dict) and set(row) == FIELDS
and type(row["seq"]) is int and 0 < row["seq"] <= 2**63 - 1
and number(row["x"], -1_000_000, 1_000_000)
and number(row["y"], -1_000_000, 1_000_000)
and number(row["age_s"], 0.0, LIFE_S))
+35 -1
View File
@@ -2,6 +2,11 @@
Zustände: HANGAR | AUF (Einsatz) | ZURUECK (Rückkehr).
Bewegung, Treibstoff und Zeitfenster verwenden dieselbe Simulationszeit.
Flight physics: hovering (dipping) needs more power than cruise, so fuel
burns faster; in the hover the wind pushes the aircraft off its hover point
and the pilot holds it back (a small steady downwind offset). Launch and
recovery wait for a deck-motion window (roll/pitch limits).
"""
import math
@@ -31,6 +36,17 @@ class ReleaseDatum:
range_uncertainty_nm: float
HOVER_FUEL_FACTOR = 1.3 # hover power / best-range cruise power
HOVER_DRIFT_FRACTION = 0.1 # un-corrected share of the wind in the hover
HOVER_HOLD_GAIN_PER_S = 0.2 # pilot position-hold gain
DECK_ROLL_LIMIT_DEG = 8.0
DECK_PITCH_LIMIT_DEG = 3.5
def deck_within_limits(roll_deg: float, pitch_deg: float) -> bool:
return abs(roll_deg) <= DECK_ROLL_LIMIT_DEG and abs(pitch_deg) <= DECK_PITCH_LIMIT_DEG
class Helicopter:
SPEED_KN = config.HELO_SPEED_KN
@@ -51,6 +67,8 @@ class Helicopter:
self.dip_depth_target_m = config.HELO_DIP_DEPTH_DEFAULT_M
self.dip_water_depth_m = 0.0
self.dip_ping_cooldown = 0.0
self.hover_x = None
self.hover_y = None
@property
def airborne(self) -> bool:
@@ -161,7 +179,8 @@ class Helicopter:
self.dip_ping_cooldown = max(0.0, self.dip_ping_cooldown - dt)
if not self.airborne:
return
self.fuel_s = max(0.0, self.fuel_s - dt)
self.fuel_s = max(0.0, self.fuel_s - dt * (
HOVER_FUEL_FACTOR if self.hovering else 1.0))
self._update_dipping(dt, world)
home_dist = math.hypot(frigate.x - self.x, frigate.y - self.y)
return_time = home_dist / config.kn_to_nm_per_s(self.SPEED_KN)
@@ -177,7 +196,9 @@ class Helicopter:
self.dip_water_depth_m = 0.0
return
if self.hovering:
self._hold_hover(dt, world)
return
self.hover_x = self.hover_y = None
if self.state == "ZURUECK":
dist = math.hypot(frigate.x - self.x, frigate.y - self.y)
if dist <= config.HELO_RETURN_DIST_NM and recovery_available:
@@ -200,6 +221,19 @@ class Helicopter:
self.x += step * math.sin(math.radians(self.course))
self.y -= step * math.cos(math.radians(self.course))
def _hold_hover(self, dt: float, world) -> None:
if self.hover_x is None or self.hover_y is None:
self.hover_x, self.hover_y = self.x, self.y
wind = getattr(world, "wind_speed_kn", 0.0) if world is not None else 0.0
towards = math.radians((getattr(world, "wind_from_deg", 0.0) + 180.0) % 360.0
if world is not None else 0.0)
drift = config.kn_to_nm_per_s(wind) * HOVER_DRIFT_FRACTION * dt
self.x += drift * math.sin(towards)
self.y -= drift * math.cos(towards)
hold = min(1.0, HOVER_HOLD_GAIN_PER_S * dt)
self.x += (self.hover_x - self.x) * hold
self.y += (self.hover_y - self.y) * hold
def water_entry_clear(self, world=None) -> bool:
"""Require in-world water deep enough for the modeled 5 m entry."""
return (world is None or (
+43 -5
View File
@@ -7,6 +7,12 @@ FLG-Track; die Flak feuert nur gegen frische Radar-Beobachtungen.
Phasenmaschine:
APPROACH -> (Waffenbereich) -> ATTACK -> (Fenster abgelaufen /
Bereich verlassen) -> RETREAT -> (Rausradius / Weltende) -> Despawn
Flight physics: coordinated turns (rate = g tan(bank) / v at the bank
limit) and, for every salvo, a pop-up: the raider climbs from its
sea-skimming approach height to acquire the ship with its fire-control
radar (an ESM-visible emission and a radar-horizon spike), releases after
the lock time and descends again.
"""
import math
@@ -29,6 +35,18 @@ class RaidPhase(str, Enum):
raise ValueError(f"unknown raid phase: {value!r}")
G = 9.80665
MAX_BANK_DEG = 56.0
POPUP_ALTITUDE_M = 300.0
CLIMB_RATE_MPS = 40.0
FC_LOCK_S = 4.0
def coordinated_turn_rate_deg_s(speed_kn: float, bank_deg: float = MAX_BANK_DEG) -> float:
speed = max(speed_kn * 1852.0 / 3600.0, 1.0)
return math.degrees(G * math.tan(math.radians(bank_deg)) / speed)
class Raider:
"""Feindliches Angriffsflugzeug mit ASM-Salvenlast."""
@@ -49,8 +67,10 @@ class Raider:
self.hp = self.profile["hp"]
self.max_hp = self.profile["hp"]
self.evasion = self.profile["evasion"]
self.turn_deg_s = config.RAIDER_TURN_DEG_S
self.turn_deg_s = coordinated_turn_rate_deg_s(self.speed_kn)
self.phase = RaidPhase.APPROACH
# Seconds at pop-up height with the fire-control radar on (-1 = low).
self.popup_t = -1.0
self.attack_t = 0.0
self.salto_cd = 0.0
self.pending_asm = 0
@@ -71,6 +91,14 @@ class Raider:
"""Steuerkurs vom Raider zur Fregatte (Umkehr der Peilung)."""
return (self.bearing_from_frigate(frigate) + 180.0) % 360.0
@property
def fc_radar_on(self) -> bool:
return self.popup_t >= 0.0 and self.altitude_m >= 0.9 * POPUP_ALTITUDE_M
def _climb(self, target_m: float, dt: float) -> None:
step = CLIMB_RATE_MPS * dt
self.altitude_m += config.clamp(target_m - self.altitude_m, -step, step)
# --- Phasenmaschine ---
def update(self, dt: float, frigate, world=None) -> None:
@@ -90,13 +118,23 @@ class Raider:
if self.phase is RaidPhase.ATTACK:
self.attack_t += dt
self.salto_cd -= dt
if self.salto_cd <= 0.0:
self.salto_cd = profile["weapon_cooldown_s"]
lo, hi = profile["salvo"]
self.pending_asm += lo + self.rng.randint(0, hi - lo)
if self.salto_cd <= 0.0 and self.popup_t < 0.0:
self.popup_t = 0.0
if self.popup_t >= 0.0:
self._climb(POPUP_ALTITUDE_M, dt)
if self.fc_radar_on:
self.popup_t += dt
if self.popup_t >= FC_LOCK_S:
self.salto_cd = profile["weapon_cooldown_s"]
lo, hi = profile["salvo"]
self.pending_asm += lo + self.rng.randint(0, hi - lo)
self.popup_t = -1.0
if (self.attack_t >= config.RAIDER_ATTACK_WINDOW_S
or dist > profile["weapon_range_nm"] * 1.25):
self.phase = RaidPhase.RETREAT
self.popup_t = -1.0
if self.popup_t < 0.0:
self._climb(profile["altitude_m"], dt)
if self.phase is RaidPhase.APPROACH:
target = to_frigate
elif self.phase is RaidPhase.ATTACK:
+14 -1
View File
@@ -1,7 +1,11 @@
"""M15: Sonarboje – passiver Hörer mit begrenztem Batterieleben."""
import math
from src.core import config
BUOY_LEEWAY = 0.02 # windage of the float and antenna, fraction of wind
class Sonobuoy:
"""Wird vom HSP-5 ausgesetzt; hört Ziele im Umkreis (Sonar-Update)."""
@@ -21,5 +25,14 @@ class Sonobuoy:
def active(self) -> bool:
return self.battery_s > 0.0
def update(self, dt: float) -> None:
def update(self, dt: float, world=None) -> None:
self.battery_s = max(0.0, self.battery_s - dt)
if world is None:
return
# The float drifts with the surface current (which already carries
# the 3 % wind drift) plus its own windage on the exposed antenna.
u, v = world.current_vec(self.x, self.y)
wind = config.kn_to_nm_per_s(world.wind_speed_kn) * BUOY_LEEWAY
towards = math.radians((world.wind_from_deg + 180.0) % 360.0)
self.x += config.kn_to_nm_per_s(u) * dt + wind * math.sin(towards) * dt
self.y -= config.kn_to_nm_per_s(v) * dt + wind * math.cos(towards) * dt
-1
View File
@@ -440,7 +440,6 @@ RAID_WAVE_SIZE = (1, 2)
RAID_SPAWN_DIST_NM = (110.0, 140.0)
RAID_MAX_CONCURRENT = 3
RAIDER_ATTACK_WINDOW_S = 90.0
RAIDER_TURN_DEG_S = 4.0
# M15: HSP-5 (Sea Lynx)
HELO_SPEED_KN = 120.0
+144 -27
View File
@@ -44,6 +44,8 @@ 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.physics import missile as missile_physics
from src.weapons import ciws as ciws_physics
from src.ship import damage as damage_physics
from src.sensors.platform import MAST_DEPTH_M
from src.world.ocean import OceanEnvironment
@@ -112,7 +114,9 @@ from src.ui.viewport import Viewport
from src.ui.weapons_view import (draw_weapons_overlay, draw_weapons_panel,
weapons_hit_target)
from src.air.asm import ASM, ESSM
from src.air import chaff as chaff_physics
from src.air.helicopter import Helicopter
from src.air import helicopter as helicopter_physics
from src.air.flights import Flight, FlightManager
from src.air.raid import RaidPhase, Raider
from src.air.sonobuoy import Sonobuoy
@@ -638,6 +642,9 @@ class Game:
self.essm_seq = 0
self.softkill_store = make_softkill_store(self._air_defense_loadout)
self.chaff_cd = 0.0
self.chaff_clouds: list = []
self.chaff_seq = 0
self.ciws_mount_deg = 0.0
self.rng_asm = random.Random(seed + 31337)
self.asm_spawned = 0
self.asm_seq = 0
@@ -3307,11 +3314,14 @@ class Game:
and crosswind <= config.HELO_LAUNCH_CROSSWIND_MAX_KN
and weather["visibility_nm"] >= config.HELO_LAUNCH_VISIBILITY_MIN_NM
and weather["sea_state"] <= config.HELO_LAUNCH_SEA_STATE_MAX)
# Launch and recovery also need a deck-motion window (own ship).
deck_safe = helicopter_physics.deck_within_limits(self.ship.roll, self.ship.pitch)
launch_safe = launch_safe and deck_safe
dipping_safe = (
weather["wind_speed_kn"] <= config.HELO_DIP_WIND_MAX_KN
and weather["visibility_nm"] >= config.HELO_DIP_VISIBILITY_MIN_NM
and weather["sea_state"] <= config.HELO_DIP_SEA_STATE_MAX)
return dict(weather, crosswind_kn=crosswind,
return dict(weather, crosswind_kn=crosswind, deck_safe=deck_safe,
launch_safe=launch_safe, dipping_safe=dipping_safe)
def launch_helicopter(self):
@@ -3602,7 +3612,18 @@ class Game:
"sam"]["observation_max_age_s"]
and track.range_nm <= profile["range_nm"]
and self.softkill_store.fire()):
broke = a.launch_chaff(self.rng_asm, profile)
self.chaff_seq += 1
threat = math.degrees(math.atan2(a.x - self.ship.x,
-(a.y - self.ship.y))) % 360.0
cloud = chaff_physics.ChaffCloud(
self.chaff_seq, *chaff_physics.lay_position(
self.ship.x, self.ship.y, threat, self.chaff_seq))
self.chaff_clouds = (self.chaff_clouds + [cloud])[
-chaff_physics.MAX_CLOUDS:]
arrival = (math.hypot(a.x - cloud.x, a.y - cloud.y)
/ max(config.kn_to_nm_per_s(a.speed_kn), 1e-9))
broke = a.launch_chaff(self.rng_asm, profile, cloud_seq=cloud.seq,
arrival_s=arrival)
self.chaff_cd = min(self.softkill_store.loading, default=0.0)
self.announce(message("runtime.chaff.decoyed" if broke
else "runtime.chaff.jammed"), "waffen")
@@ -3952,6 +3973,10 @@ class Game:
if a.state not in ("LAUF", "CHAFF"):
continue
dist = a.distance_nm(self.ship)
# A sea-skimmer is below the radar (and radio) horizon until close.
if dist > config.radar_horizon_nm(config.RADAR_ANTENNA_HEIGHT_M,
a.altitude_m):
continue
if (a.jamming(self.ship) and dist <= config.ESM_RANGE_NM
and not self.world.land_blocks_line(
self.ship.x, self.ship.y, a.x, a.y)):
@@ -5089,7 +5114,7 @@ class Game:
for raider in sorted(self.raiders, key=lambda item: item.seq):
signals = self._radar_signals(
raider, "su_25", enabled=not raider.despawned,
fire_control=raider.phase is RaidPhase.ATTACK)
fire_control=raider.fc_radar_on)
yield from self._signal_measurements(raider, signals)
for asm in self.asms:
emitter = self._asm_seeker_emitter(asm.profile)
@@ -5272,9 +5297,13 @@ class Game:
-(w.sensor_contact[1] - y))) % 360.0
if w.sensor_contact is not None else w.course)
self.warship_asm_seq += 1
# Ship-launched: booster from the launcher's speed; the
# launcher's sensor contact is the inertial datum.
self.asms.append(ASM(
x, y, course, self._next_asm_sequence(), self.rng_asm,
self._air_defense_loadout["asm"]))
self._air_defense_loadout["asm"],
launch_speed_kn=w.speed, altitude_m=10.0,
datum=w.sensor_contact))
def _next_asm_sequence(self) -> int:
self.asm_seq += 1
@@ -5297,8 +5326,11 @@ class Game:
y = config.clamp(self.ship.y + d * math.sin(math.radians(ang)),
0.0, self.world.size_nm)
course = math.degrees(math.atan2(self.ship.x - x, -(self.ship.y - y))) % 360.0
# A wave appears already in cruise flight, aimed by its (unseen)
# launcher at the ship's position at that moment.
self.asms.append(ASM(x, y, course, self._next_asm_sequence(), self.rng_asm,
self._air_defense_loadout["asm"]))
self._air_defense_loadout["asm"],
datum=(self.ship.x, self.ship.y)))
# --- R20: Luftangriff (feindliche Angriffsflugzeug-Wellen) ---
@@ -5432,9 +5464,13 @@ class Game:
pending, raider.pending_asm = raider.pending_asm, 0
for _ in range(pending):
course = raider.course_to_frigate(self.ship)
# Air-launched at the raider's speed and pop-up height; its
# fire-control radar supplied the datum.
self.asms.append(ASM(
raider.x, raider.y, course, self._next_asm_sequence(),
self.rng_asm, self._air_defense_loadout["asm"]))
self.rng_asm, self._air_defense_loadout["asm"],
launch_speed_kn=raider.speed_kn, altitude_m=raider.altitude_m,
datum=(self.ship.x, self.ship.y)))
# --- Waffenzentrale ---
@@ -6112,9 +6148,11 @@ class Game:
and not self.helicopter_weather()["dipping_safe"]):
self.helo.set_dipping(False, self.world)
self.helo.update(dt, self.ship, self.world,
recovery_available=not self.damage.station_down("flightdeck"))
recovery_available=not self.damage.station_down("flightdeck")
and helicopter_physics.deck_within_limits(
self.ship.roll, self.ship.pitch))
for buoy in self.buoys:
buoy.update(dt)
buoy.update(dt, self.world)
self.buoys = [buoy for buoy in self.buoys if buoy.active]
self.softkill_store.update(dt)
self.chaff_cd = min(self.softkill_store.loading, default=0.0)
@@ -6138,9 +6176,14 @@ class Game:
self._auto_ecm_softkill()
# Softkill state is resolved by ASM.update before layered hardkill.
self.ciws_cooldown_s = max(0.0, getattr(self, "ciws_cooldown_s", 0.0) - dt)
for cloud in self.chaff_clouds:
cloud.update(dt, self.world.wind_from_deg, self.world.wind_speed_kn)
self.chaff_clouds = [cloud for cloud in self.chaff_clouds if cloud.active]
clouds = {cloud.seq: cloud for cloud in self.chaff_clouds}
for asm in self.asms:
asm.update(dt, self.ship, self.world,
ecm_effect=self._ecm_effect_against_asm(asm))
ecm_effect=self._ecm_effect_against_asm(asm),
chaff_target=clouds.get(asm.chaff_cloud))
if asm.state == "TREFFER":
hit = self.damage.missile_hit(*self._hull_impact(asm.x, asm.y))
self._emit_sound("explosion")
@@ -6158,6 +6201,21 @@ class Game:
essm.guidance_x, essm.guidance_y = track.x, track.y
essm.update(dt, candidates=self.asms, world=self.world)
ciws = profiles["ciws"]
# CIWS fire control works on its latest own measurement, not on the
# smoothed OPZ track range.
def fc_range(track):
return (track.raw_range_nm if track.raw_range_nm is not None
else track.range_nm)
# The mount slews towards the nearest fresh close-in missile track.
close_tracks = sorted(
(fc_range(track), track.track_id, track) for track in observed_asms.values()
if fc_range(track) is not None and fc_range(track) <= ciws["range_nm"]
and track.position_seen is not None
and self.sim_t - track.position_seen <= ciws["observation_max_age_s"])
if self.ciws_authorized and close_tracks:
self.ciws_mount_deg = ciws_physics.slew(
self.ciws_mount_deg, close_tracks[0][2].bearing, dt)
for asm in self.asms:
track = observed_asms.get(asm.seq)
if (self.ciws_authorized
@@ -6169,23 +6227,26 @@ class Game:
and self.sim_t - track.position_seen
<= ciws["observation_max_age_s"]
and self.ciws_ammo >= ciws["rounds_per_attempt"]
and track.range_nm is not None
and track.range_nm <= ciws["range_nm"]
and fc_range(track) is not None
and fc_range(track) <= ciws["range_nm"]
and self.ciws_cooldown_s <= 0.0
and ciws_physics.on_target(self.ciws_mount_deg, track.bearing)
and not self.damage.station_down("opz")
and not self.world.land_blocks_line(
self.ship.x, self.ship.y, track.x, track.y)):
self.ciws_ammo -= ciws["rounds_per_attempt"]
self.ciws_cooldown_s = ciws["cycle_s"]
self._emit_sound("gunfire")
# Pk composes base kill probability with a range falloff (a
# closing missile is an easier hard-kill target) and a penalty
# while the missile is actively jamming our fire control.
distance_factor = 1.0 - 0.4 * config.clamp(
track.range_nm / max(0.01, ciws["range_nm"]), 0.0, 1.0)
target_jamming = 0.35 if asm.jamming(self.ship) else 0.0
if (self.rng_asm.random()
< ciws["kill_probability"] * distance_factor * (1.0 - target_jamming)):
# Burst physics at the true geometry: dispersion and
# prediction error over the rounds' time of flight; a missile
# that arrives first cannot be stopped by this burst.
distance = asm.distance_nm(self.ship)
time_to_go = distance / max(config.kn_to_nm_per_s(asm.speed_kn), 1e-9)
kill = (0.0 if time_to_go <= ciws_physics.time_of_flight_s(distance)
else ciws_physics.burst_kill_probability(
distance, ciws["rounds_per_attempt"],
asm.jamming(self.ship), ciws["kill_probability"]))
if self.rng_asm.random() < kill:
asm.state = "ABGEFANGEN"
self.audio.play_alert("defense")
self.announce(message("runtime.ciws.intercepted"),
@@ -6807,7 +6868,8 @@ class Game:
phase=r.phase.value, hp=r.hp,
salvo_cd=r.salto_cd,
pending_asm=r.pending_asm,
attack_t=r.attack_t)
attack_t=r.attack_t,
altitude_m=r.altitude_m, popup_t=r.popup_t)
for r in self.raiders],
"raider_seq": self.raid_seq,
"waves_spawned": self.raid_waves_spawned,
@@ -6873,6 +6935,9 @@ class Game:
"vls_cells": self.vls_cells,
"ciws_ammo": self.ciws_ammo,
"ciws_cooldown_s": self.ciws_cooldown_s,
"ciws_mount_deg": self.ciws_mount_deg,
"chaff_clouds": [cloud.to_dict() for cloud in self.chaff_clouds],
"chaff_seq": self.chaff_seq,
"air_picture": self.air_picture.serialize(),
"opz_affiliations": dict(self.opz_affiliations),
"esm": {
@@ -6913,7 +6978,8 @@ class Game:
dip_depth_m=self.helo.dip_depth_m,
dip_depth_target_m=self.helo.dip_depth_target_m,
dip_water_depth_m=self.helo.dip_water_depth_m,
dip_ping_cooldown=self.helo.dip_ping_cooldown),
dip_ping_cooldown=self.helo.dip_ping_cooldown,
hover_x=self.helo.hover_x, hover_y=self.helo.hover_y),
"subs": [dict(id=s.id, x=s.x, y=s.y, depth=s.depth, course=s.course,
state=s.state, speed=s.speed, damage=s.damage,
torpedoes_left=s.torpedoes_left, heard_ping=s.heard_ping,
@@ -7063,7 +7129,11 @@ class Game:
profile_key=a.profile_key,
state=a.state, jammer=a.jammer,
age_s=a.age_s, travel=a.travel,
chaff_left=a.chaff_left, broken=a.broken)
chaff_left=a.chaff_left, broken=a.broken,
speed_kn=a.speed_kn, boosting=a.boosting,
altitude_m=a.altitude_m, datum_x=a.datum_x,
datum_y=a.datum_y, lock_s=a.lock_s, locked=a.locked,
los_prev=a.los_prev, chaff_cloud=a.chaff_cloud)
for a in self.asms],
"essms": [dict(x=e.x, y=e.y, course=e.course, seq=e.seq,
profile_key=e.profile_key,
@@ -7073,7 +7143,8 @@ class Game:
seeker_acquired=(e.seeker_acquired and e.target is not None
and e.target.seq in asm_ids),
target_id=(e.target.seq if e.target is not None
and e.target.seq in asm_ids else None))
and e.target.seq in asm_ids else None),
los_prev=e.los_prev)
for e in self.essms],
"buoys": [dict(x=b.x, y=b.y, seq=b.seq, battery_s=b.battery_s,
mode=b.mode, last_ping_epoch=b.last_ping_epoch)
@@ -7397,6 +7468,8 @@ class Game:
raider.salto_cd = row["salvo_cd"]
raider.pending_asm = row["pending_asm"]
raider.attack_t = row["attack_t"]
raider.altitude_m = row["altitude_m"]
raider.popup_t = row["popup_t"]
self.raiders.append(raider)
self.target = None
self.selected_contact = None
@@ -7457,6 +7530,10 @@ class Game:
self.vls_cells = data["vls_cells"]
self.ciws_ammo = data["ciws_ammo"]
self.ciws_cooldown_s = data["ciws_cooldown_s"]
self.ciws_mount_deg = data["ciws_mount_deg"]
self.chaff_clouds = [chaff_physics.ChaffCloud(**row)
for row in data["chaff_clouds"]]
self.chaff_seq = data["chaff_seq"]
self.air_picture = TrackPicture(
config.RADAR_TRACK_STALE_S, maximum=MAX_AIR_PICTURE_TRACKS)
self.air_picture.restore(data["air_picture"])
@@ -7541,6 +7618,7 @@ class Game:
self.helo.dip_depth_target_m = hd["dip_depth_target_m"]
self.helo.dip_water_depth_m = hd["dip_water_depth_m"]
self.helo.dip_ping_cooldown = hd["dip_ping_cooldown"]
self.helo.hover_x, self.helo.hover_y = hd["hover_x"], hd["hover_y"]
# U-Boote (Phase 2: vollstaendiger KI-Zustand)
self.subs = []
for sd in data["subs"]:
@@ -7799,6 +7877,9 @@ class Game:
asm.broken = a["broken"]
asm.age_s = a["age_s"]
asm.travel = a["travel"]
for key in ("speed_kn", "boosting", "altitude_m", "datum_x", "datum_y",
"lock_s", "locked", "los_prev", "chaff_cloud"):
setattr(asm, key, a[key])
self.asms.append(asm)
self.warship_asm_seq = data["warship_asm_seq"]
self.essms = []
@@ -7813,6 +7894,7 @@ class Game:
essm.travel = e["travel"]
essm.state = e["state"]
essm.seeker_acquired = e["seeker_acquired"]
essm.los_prev = e["los_prev"]
self.essms.append(essm)
self.asm_seq = data["asm_seq"]
for bd in data["buoys"]:
@@ -8944,6 +9026,17 @@ class Game:
return False
if not bounded(data.get("ciws_cooldown_s", 0), 0, 1):
return False
mount = data.get("ciws_mount_deg")
clouds = data.get("chaff_clouds")
if (not bounded(mount, 0, 360) or mount == 360
or type(data.get("chaff_seq")) is not int
or not 0 <= data["chaff_seq"] <= 2**63 - 1
or not isinstance(clouds, list)
or len(clouds) > chaff_physics.MAX_CLOUDS
or not all(chaff_physics.valid_row(row) for row in clouds)
or len({row["seq"] for row in clouds}) != len(clouds)
or any(row["seq"] > data["chaff_seq"] for row in clouds)):
return False
if type(data.get("air_threat_reported", False)) is not bool:
return False
flights = data.get("flights", {})
@@ -8980,10 +9073,15 @@ class Game:
"state", "x", "y", "course", "torps", "torpedo_profile_key",
"buoys_left", "fuel_s", "waypoint_x", "waypoint_y",
"dip_state", "dip_depth_m", "dip_depth_target_m",
"dip_water_depth_m", "dip_ping_cooldown",
"dip_water_depth_m", "dip_ping_cooldown", "hover_x", "hover_y",
}
if set(helo) != required_helo:
return False
if ((helo["hover_x"] is None) != (helo["hover_y"] is None)
or (helo["hover_x"] is not None and (
not bounded(helo["hover_x"], -1_000_000, 1_000_000)
or not bounded(helo["hover_y"], -1_000_000, 1_000_000)))):
return False
if (helo.get("state") not in ("HANGAR", "AUF", "ZURUECK", "VERLOREN")
or not bounded(helo.get("x"), -1_000_000, 1_000_000)
or not bounded(helo.get("y"), -1_000_000, 1_000_000)
@@ -9095,7 +9193,21 @@ class Game:
asm_ids.add(seq)
asm_profile = data["air_defense"]["loadout"]["asm"]
if (set(asm) != {"x", "y", "course", "seq", "profile_key", "state",
"jammer", "age_s", "travel", "chaff_left", "broken"}
"jammer", "age_s", "travel", "chaff_left", "broken",
"speed_kn", "boosting", "altitude_m", "datum_x",
"datum_y", "lock_s", "locked", "los_prev",
"chaff_cloud"}
or not bounded(asm.get("speed_kn"), 0, asm_profile["speed_kn"])
or type(asm.get("boosting")) is not bool
or type(asm.get("locked")) is not bool
or not bounded(asm.get("altitude_m"), 0, 20_000)
or not bounded(asm.get("datum_x"), -1_000_000, 1_000_000)
or not bounded(asm.get("datum_y"), -1_000_000, 1_000_000)
or not bounded(asm.get("lock_s"), 0, 3600)
or (asm.get("los_prev") is not None
and not bounded(asm.get("los_prev"), 0, 360))
or (asm.get("chaff_cloud") is not None
and not identity(asm.get("chaff_cloud")))
or asm.get("profile_key") != asm_profile["key"]
or not bounded(asm.get("x"), -1_000_000, 1_000_000)
or not bounded(asm.get("y"), -1_000_000, 1_000_000)
@@ -9105,8 +9217,10 @@ class Game:
"LAUF", "CHAFF", "ABGEFANGEN", "TREFFER", "VERLOREN")
or type(asm.get("jammer")) is not bool
or type(asm.get("broken")) is not bool
# Powered flight time: range at cruise plus the boost.
or not bounded(asm.get("age_s", 0), 0,
asm_profile["range_nm"] / config.kn_to_nm_per_s(
missile_physics.flight_time_bound_s(
asm_profile["range_nm"],
asm_profile["speed_kn"]))
or not bounded(asm.get("travel", 0), 0, asm_profile["range_nm"])
or not bounded(asm.get("chaff_left"), -3600, 3600)):
@@ -9224,7 +9338,10 @@ class Game:
sam_profile = data["air_defense"]["loadout"]["sam"]
if (set(essm) != {"x", "y", "course", "seq", "profile_key", "state",
"travel", "guidance_x", "guidance_y",
"track_target_id", "seeker_acquired", "target_id"}
"track_target_id", "seeker_acquired", "target_id",
"los_prev"}
or (essm.get("los_prev") is not None
and not bounded(essm.get("los_prev"), 0, 360))
or essm.get("profile_key") != sam_profile["key"]
or (target_id is not None and (not identity(target_id)
or target_id not in asm_ids))
+2 -1
View File
@@ -20,7 +20,8 @@ SAVE_ROOT_FIELDS = frozenset({
"hfdf_fixes", "hfdf_log", "radio_picture", "air_picture",
"opz_affiliations", "air_threat_reported", "esm", "next_entity_ids",
"asm_spawned", "asm_seq", "warship_asm_seq", "torpedo_seq", "buoy_seq",
"ciws_cooldown_s", "schedulers", "rngs", "ui",
"ciws_cooldown_s", "ciws_mount_deg", "chaff_clouds", "chaff_seq",
"schedulers", "rngs", "ui",
"autocrew", "ais",
})
+81
View File
@@ -0,0 +1,81 @@
"""Anti-ship missile flight physics (pure helpers).
Point-mass 3-DOF model: horizontal position/heading, altitude, speed.
* Boost: a ship- or air-launched round accelerates from its launch speed to
the profiled cruise speed at the booster acceleration; the sustainer then
holds cruise speed (thrust = drag). Fuel is the profiled range.
* Altitude: climb/descent to the sea-skimming cruise height at a limited
vertical speed, dropping to the terminal height inside the terminal range.
The missile's own height sets its radar horizon.
* Mid-course: inertial flight towards the launch datum with the profiled
(gentle, waypoint) turn rate.
* Terminal: the active seeker must see the target inside its field of view
for the lock delay; locked, the missile flies proportional navigation
(commanded turn rate = N x line-of-sight rate) limited by its lateral g.
"""
from __future__ import annotations
import math
G = 9.80665
MPS_PER_KN = 1852.0 / 3600.0
BOOST_ACCEL_MPS2 = 60.0
CRUISE_ALTITUDE_M = 20.0
TERMINAL_ALTITUDE_M = 5.0
TERMINAL_RANGE_NM = 5.0
VERTICAL_SPEED_MPS = 30.0
PN_GAIN = 4.0
LATERAL_G_LIMIT = 15.0
SEEKER_FOV_HALF_DEG = 30.0
SEEKER_LOCK_S = 1.5
GUIDANCE_SUBSTEP_S = 0.1
def boost_time_s(launch_kn: float, cruise_kn: float) -> float:
return max(0.0, cruise_kn - launch_kn) * MPS_PER_KN / BOOST_ACCEL_MPS2
def speed_step(speed_kn: float, cruise_kn: float, dt: float) -> float:
if speed_kn >= cruise_kn:
return speed_kn
return min(cruise_kn, speed_kn + BOOST_ACCEL_MPS2 * dt / MPS_PER_KN)
def altitude_step(altitude_m: float, target_m: float, dt: float) -> float:
step = VERTICAL_SPEED_MPS * dt
return altitude_m + max(-step, min(step, target_m - altitude_m))
def commanded_altitude_m(distance_to_target_nm: float) -> float:
return (TERMINAL_ALTITUDE_M if distance_to_target_nm <= TERMINAL_RANGE_NM
else CRUISE_ALTITUDE_M)
def max_turn_rate_deg_s(speed_kn: float) -> float:
"""Lateral-g limit: omega = a / v."""
speed = max(speed_kn * MPS_PER_KN, 1.0)
return math.degrees(LATERAL_G_LIMIT * G / speed)
def in_field_of_view(heading_deg: float, bearing_deg: float) -> bool:
diff = (bearing_deg - heading_deg + 180.0) % 360.0 - 180.0
return abs(diff) <= SEEKER_FOV_HALF_DEG
def pn_turn_rate_deg_s(los_deg: float, los_prev_deg: float | None, dt: float,
speed_kn: float) -> float:
"""Proportional navigation with the airframe's lateral-g limit."""
if los_prev_deg is None or dt <= 0.0:
return 0.0
los_rate = ((los_deg - los_prev_deg + 180.0) % 360.0 - 180.0) / dt
limit = max_turn_rate_deg_s(speed_kn)
return max(-limit, min(limit, PN_GAIN * los_rate))
def flight_time_bound_s(range_nm: float, cruise_kn: float) -> float:
"""Upper bound of the powered flight: range at cruise plus the time lost
accelerating from rest."""
cruise = max(cruise_kn * MPS_PER_KN, 1e-6)
return range_nm * 1852.0 / cruise + cruise / (2.0 * BOOST_ACCEL_MPS2)
+5 -1
View File
@@ -169,7 +169,11 @@ def _valid_raider_row(row, loadout):
profile = loadout["raider"]
if (not isinstance(row, dict)
or set(row) != {"x", "y", "course", "seq", "phase", "hp",
"salvo_cd", "pending_asm", "attack_t"}):
"salvo_cd", "pending_asm", "attack_t",
"altitude_m", "popup_t"}):
return False
if (not _is_finite(row["altitude_m"]) or not 0 <= row["altitude_m"] <= 20_000
or not _is_finite(row["popup_t"]) or not -1 <= row["popup_t"] <= 3600):
return False
if (not _is_finite(row["x"]) or not _is_finite(row["y"])
or not bounded_range(row["x"], -1_000_000, 1_000_000)
+55
View File
@@ -0,0 +1,55 @@
"""Close-in weapon system fire control (pure helpers).
* The mount slews at a finite rate; a burst is fired only once the barrel is
on the predicted bearing.
* Rounds need their time of flight to reach the aim point; a missile that
impacts before the burst arrives cannot be stopped by it.
* Hit probability per round follows the circular-normal miss distance at
the target: gun dispersion (angular, grows with range), the prediction
error of the fire-control track (velocity error x time of flight) and
extra angle noise while the target jams. A round that hits kills with
the profiled kill probability; a burst kills with 1 - (1 - p_hit pk)^n.
``LETHAL_AREA_M2`` is the effective area around the aim point inside which a
round defeats the missile (airframe, seeker and warhead initiation); it is
calibrated so that a single sea-skimmer leaks through CIWS at the 1.0.0 rate
(calibration section ``air``). Most kills therefore happen in the last few
hundred metres, where dispersion and prediction error are small.
"""
from __future__ import annotations
import math
SLEW_DEG_S = 115.0
ON_TARGET_DEG = 2.0
ROUND_MEAN_SPEED_MPS = 950.0
DISPERSION_MRAD = 2.0
TRACK_VELOCITY_ERROR_MPS = 8.0
JAMMING_ANGLE_NOISE_MRAD = 3.0
LETHAL_AREA_M2 = 55.0
def slew(mount_deg: float, bearing_deg: float, dt: float) -> float:
diff = (bearing_deg - mount_deg + 180.0) % 360.0 - 180.0
step = SLEW_DEG_S * dt
return (mount_deg + max(-step, min(step, diff))) % 360.0
def on_target(mount_deg: float, bearing_deg: float) -> bool:
return abs((bearing_deg - mount_deg + 180.0) % 360.0 - 180.0) <= ON_TARGET_DEG
def time_of_flight_s(range_nm: float) -> float:
return max(0.0, range_nm) * 1852.0 / ROUND_MEAN_SPEED_MPS
def burst_kill_probability(range_nm: float, rounds: int, jamming: bool,
kill_given_hit: float = 1.0) -> float:
r = max(range_nm, 0.0) * 1852.0
angular = DISPERSION_MRAD ** 2 + (JAMMING_ANGLE_NOISE_MRAD ** 2 if jamming else 0.0)
sigma2 = (angular * 1e-6 * r * r
+ (TRACK_VELOCITY_ERROR_MPS * time_of_flight_s(range_nm)) ** 2)
p_hit = min(1.0, LETHAL_AREA_M2 / (2.0 * math.pi * max(sigma2, 1e-6)))
p_round = p_hit * max(0.0, min(1.0, kill_given_hit))
return 1.0 - (1.0 - p_round) ** max(0, int(rounds))
+19
View File
@@ -28,6 +28,9 @@ def game():
result = Game(seed=909, start_menu=False, audio_enabled=False)
result.sim_t = 10.0
result.mission.asm_count = 0
# Test missiles sit due east; start with the CIWS mount already slewed
# there so single-update engagements are not waiting on the mount.
result.ciws_mount_deg = 90.0
return result
@@ -425,3 +428,19 @@ def test_integrated_softkill_and_datalink_split_run(game, monkeypatch):
assert current_track.source in ("DATALINK", "RADAR-L")
assert restored_track == current_track
assert restored.save_state()["rngs"]["asm"] == game.save_state()["rngs"]["asm"]
def test_ciws_mount_must_slew_onto_the_track_before_firing(game):
missile = ASM(game.ship.x + 1, game.ship.y, 0, 1, game.rng_asm)
missile.speed_kn = 0
game.asms = [missile]
observe_asm(game, missile)
game.rng_asm.random = lambda: 1.0
game.ciws_mount_deg = 270.0 # pointing the wrong way
before = game.ciws_ammo
game._update_air_defense(.1, publish_picture=False)
assert game.ciws_ammo == before and game.ciws_mount_deg != 270.0
for _ in range(20): # 180 deg at 115 deg/s
observe_asm(game, missile)
game._update_air_defense(.1, publish_picture=False)
assert game.ciws_ammo < before
+220
View File
@@ -0,0 +1,220 @@
"""Phase 12: missile flight physics, chaff clouds, CIWS, raiders, helo, buoys."""
import copy
import json
import math
import random
from types import SimpleNamespace
import pytest
from src.air import chaff
from src.air.asm import ASM
from src.air.helicopter import (DECK_PITCH_LIMIT_DEG, HOVER_FUEL_FACTOR,
Helicopter, deck_within_limits)
from src.air.sonobuoy import Sonobuoy
from src.core import config
from src.core.game import Game
from src.physics import missile
from src.weapons import ciws
def _ocean(**extra):
return SimpleNamespace(size_nm=500.0, land_blocks_line=lambda *args: False,
**extra)
def test_launched_missile_boosts_to_cruise_and_settles_to_sea_skim_height():
ship = SimpleNamespace(x=100.0, y=60.0)
asm = ASM(100.0, 100.0, 0.0, 1, random.Random(1), launch_speed_kn=0.0,
altitude_m=10.0, datum=(100.0, 60.0))
boost = missile.boost_time_s(0.0, asm.cruise_kn)
asm.update(boost / 2, ship, _ocean())
assert 0.0 < asm.speed_kn < asm.cruise_kn and asm.boosting
asm.update(boost, ship, _ocean())
assert asm.speed_kn == asm.cruise_kn and not asm.boosting
for _ in range(30):
asm.update(1.0, ship, _ocean())
assert asm.altitude_m == pytest.approx(missile.CRUISE_ALTITUDE_M)
while asm.distance_nm(ship) > missile.TERMINAL_RANGE_NM - 1.0:
asm.update(1.0, ship, _ocean())
assert asm.altitude_m == pytest.approx(missile.TERMINAL_ALTITUDE_M)
def test_seeker_needs_field_of_view_and_lock_time_then_flies_pn_within_g_limit():
ship = SimpleNamespace(x=110.0, y=100.0)
# Heading north with the ship due east: outside the 30 deg cone.
asm = ASM(100.0, 100.0, 0.0, 1, random.Random(1), datum=(100.0, 50.0))
asm.update(1.0, ship, _ocean())
assert not asm.locked and asm.lock_s == 0.0
asm = ASM(100.0, 100.0, 80.0, 2, random.Random(1), datum=(110.0, 100.0))
asm.update(missile.SEEKER_LOCK_S * 0.5, ship, _ocean())
assert not asm.locked
asm.update(missile.SEEKER_LOCK_S, ship, _ocean())
assert asm.locked
limit = missile.max_turn_rate_deg_s(asm.speed_kn)
for _ in range(40):
before = asm.course
asm.update(0.1, ship, _ocean())
assert abs(config.angle_diff_deg(asm.course, before)) <= limit * 0.1 + 1e-6
def test_proportional_navigation_hits_a_crossing_ship():
class Mover:
def __init__(self):
self.x, self.y = 115.0, 100.0
def step(self, dt):
self.y -= config.kn_to_nm_per_s(28.0) * dt # northbound, crossing
ship = Mover()
asm = ASM(100.0, 100.0, 90.0, 3, random.Random(1), datum=(115.0, 100.0))
for _ in range(2000):
asm.update(0.1, ship, _ocean())
ship.step(0.1)
if asm.state != "LAUF":
break
assert asm.state == "TREFFER"
def test_sea_skimmer_is_below_the_radar_horizon_until_close(monkeypatch):
game = Game(seed=1201, start_menu=False, audio_enabled=False)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
horizon = config.radar_horizon_nm(config.RADAR_ANTENNA_HEIGHT_M,
missile.CRUISE_ALTITUDE_M)
far = ASM(game.ship.x + horizon + 3.0, game.ship.y, 270.0, 5, game.rng_asm)
far.jammer = True # not even the jammer is heard over the horizon
game.asms = [far]
for _ in range(6):
game.sim_t += 4.0
game._update_air_picture(full_scan=True)
assert not game.asm_tracks()
near = ASM(game.ship.x + horizon - 3.0, game.ship.y, 270.0, 6, game.rng_asm)
near.jammer = False
game.asms = [near]
for _ in range(6):
game.sim_t += 4.0
game._update_air_picture(full_scan=True)
assert game.asm_tracks()
def test_chaff_cloud_blooms_drifts_downwind_and_expires():
cloud = chaff.ChaffCloud(1, 100.0, 100.0)
assert cloud.bloom() == 0.0
cloud.update(chaff.BLOOM_S, wind_from_deg=270.0, wind_speed_kn=20.0)
assert cloud.bloom() == pytest.approx(1 - math.exp(-1), rel=1e-6)
assert cloud.x > 100.0 and cloud.y == pytest.approx(100.0) # blown east
cloud.update(chaff.LIFE_S, wind_from_deg=270.0, wind_speed_kn=20.0)
assert not cloud.active
assert chaff.seduction_probability(.4, 0.0) == 0.0
assert chaff.seduction_probability(.4, 60.0) == pytest.approx(.4, abs=1e-6)
assert chaff.seduction_probability(.4, 1.0) < .4
def test_seduced_missile_steers_to_the_cloud():
ship = SimpleNamespace(x=100.0, y=100.0)
cloud = chaff.ChaffCloud(1, 100.4, 99.6)
asm = ASM(104.0, 100.0, 270.0, 7, random.Random(1))
asm.state, asm.chaff_left, asm.broken, asm.chaff_cloud = "CHAFF", 4.0, True, 1
asm.update(2.0, ship, _ocean(), chaff_target=cloud)
bearing = math.degrees(math.atan2(cloud.x - asm.x, -(cloud.y - asm.y))) % 360
assert abs(config.angle_diff_deg(bearing, asm.course)) < 10.0
def test_game_lays_a_cloud_and_saves_it(monkeypatch):
game = Game(seed=1202, start_menu=False, audio_enabled=False)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
asm = ASM(game.ship.x + 6.0, game.ship.y, 270.0, 8, game.rng_asm)
asm.jammer = False
game.asms = [asm]
for _ in range(6):
game.sim_t += 4.0
game._update_air_picture(full_scan=True)
if game.asm_tracks():
break
assert game.launch_chaff_at(game.asm_tracks()[0]) is True
assert len(game.chaff_clouds) == 1 and game.chaff_seq == 1
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 [c.to_dict() for c in restored.chaff_clouds] == [
c.to_dict() for c in game.chaff_clouds]
broken = copy.deepcopy(state)
broken["chaff_clouds"][0]["age_s"] = -1.0
assert not restored._load_save_data(broken)
def test_ciws_burst_physics():
near = ciws.burst_kill_probability(.2, 6, False, .3)
far = ciws.burst_kill_probability(1.4, 6, False, .3)
assert near > far > 0.0
assert ciws.burst_kill_probability(.5, 6, True, .3) < \
ciws.burst_kill_probability(.5, 6, False, .3)
assert ciws.time_of_flight_s(1.5) == pytest.approx(1.5 * 1852 / 950)
assert ciws.slew(0.0, 90.0, .5) == pytest.approx(ciws.SLEW_DEG_S * .5)
assert ciws.on_target(89.0, 90.0) and not ciws.on_target(80.0, 90.0)
def test_missile_state_round_trips_and_age_is_bounded_by_flight_time():
game = Game(seed=1203, start_menu=False, audio_enabled=False)
asm = ASM(game.ship.x + 30.0, game.ship.y, 270.0, 9, game.rng_asm,
launch_speed_kn=100.0, altitude_m=60.0,
datum=(game.ship.x, game.ship.y))
game.asms = [asm]
game.asm_seq = 9
asm.update(3.0, game.ship, game.world)
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.asms[0]
for key in ("speed_kn", "boosting", "altitude_m", "datum_x", "datum_y",
"lock_s", "locked", "los_prev"):
assert getattr(twin, key) == getattr(asm, key)
for dt in (1.0, 1.0, 1.0):
asm.update(dt, game.ship, game.world)
twin.update(dt, restored.ship, restored.world)
assert (twin.x, twin.y, twin.altitude_m) == (asm.x, asm.y, asm.altitude_m)
broken = copy.deepcopy(state)
profile = game._air_defense_loadout["asm"]
broken["asms"][0]["age_s"] = missile.flight_time_bound_s(
profile["range_nm"], profile["speed_kn"]) + 1.0
assert not restored._load_save_data(broken)
def test_helicopter_hover_burns_more_fuel_and_holds_near_its_hover_point():
world = SimpleNamespace(wind_speed_kn=30.0, wind_from_deg=0.0,
depth_m=lambda x, y: 500.0, size_nm=500.0,
on_land=lambda x, y: False)
frigate = SimpleNamespace(x=100.0, y=100.0, course=0.0)
helo = Helicopter(random.Random(1))
helo.launch(frigate)
helo.dip_state = "DEPLOYED"
start_fuel, start = helo.fuel_s, (helo.x, helo.y)
for _ in range(600):
helo.update(1.0, frigate, world)
assert start_fuel - helo.fuel_s == pytest.approx(600 * HOVER_FUEL_FACTOR)
offset = math.hypot(helo.x - start[0], helo.y - start[1])
assert 0.0 < offset < 0.05 and helo.y > start[1] # pushed south
def test_deck_motion_limits_block_launch():
assert deck_within_limits(2.0, 1.0)
assert not deck_within_limits(0.0, DECK_PITCH_LIMIT_DEG + .5)
game = Game(seed=1204, start_menu=False, audio_enabled=False)
game.ship.pitch = DECK_PITCH_LIMIT_DEG + 1.0
assert game.launch_helicopter() == "weather_unsafe"
game.ship.pitch = 0.0
if game.helicopter_weather()["launch_safe"]:
assert game.launch_helicopter() is True
def test_sonobuoys_drift_with_current_and_windage():
world = SimpleNamespace(current_vec=lambda x, y: (1.0, 0.0),
wind_speed_kn=20.0, wind_from_deg=0.0)
buoy = Sonobuoy(100.0, 100.0, 1)
buoy.update(3600.0, world)
assert buoy.x == pytest.approx(101.0) # 1 kn east for an hour
assert buoy.y == pytest.approx(100.0 + 20.0 * 0.02) # windage south
still = Sonobuoy(100.0, 100.0, 2)
still.update(3600.0)
assert (still.x, still.y) == (100.0, 100.0)
+18 -3
View File
@@ -8,7 +8,7 @@ import pygame
import pytest
from src.air.asm import ASM
from src.air.raid import RaidPhase, Raider
from src.air.raid import FC_LOCK_S, POPUP_ALTITUDE_M, RaidPhase, Raider
from src.core import config
from src.core.game import Game
from src.core.station import Station
@@ -64,7 +64,17 @@ def test_raider_lifecycle_approach_attack_retreat_despawn():
if raider.phase is not RaidPhase.APPROACH:
break
assert raider.phase is RaidPhase.ATTACK
assert raider.pending_asm >= profile["salvo"][0]
# Pop-up: climb, lock with the fire-control radar, then release.
fc_seen = False
for _ in range(30):
raider.update(1.0, ship)
fc_seen = fc_seen or raider.fc_radar_on
if raider.pending_asm:
break
assert fc_seen and raider.pending_asm >= profile["salvo"][0]
for _ in range(40):
raider.update(1.0, ship)
assert raider.altitude_m == pytest.approx(profile["altitude_m"])
for _ in range(5000):
raider.update(1.0, ship)
if raider.phase is not RaidPhase.ATTACK:
@@ -88,7 +98,9 @@ def test_raider_turn_rate_is_bounded():
course = raider.course
raider.update(1.0, ship)
assert abs(config.angle_diff_deg(raider.course, course)) <= \
config.RAIDER_TURN_DEG_S + 0.01
raider.turn_deg_s + 0.01
# Coordinated turn at the bank limit: g tan(56 deg) / v ~ 4 deg/s at 400 kn.
assert raider.turn_deg_s == pytest.approx(4.0, abs=.1)
def test_shot_down_raider_stops_moving():
@@ -289,6 +301,9 @@ def test_raider_salvo_drains_into_attack_asms(game):
game.rng_raid, profile["raider"])
raider.phase = RaidPhase.ATTACK
raider.salto_cd = 0.0
# Already popped up and about to complete the fire-control lock.
raider.altitude_m = POPUP_ALTITUDE_M
raider.popup_t = FC_LOCK_S - 0.05
game.raiders = [raider]
game.raid_seq = 1
game._update_raiders(0.1, publish_picture=False)
+9 -5
View File
@@ -189,15 +189,19 @@ def test_noise_exposes_home_on_jam_while_rgpo_breaks_guidance():
game = Game(seed=8032, audio_enabled=False)
profile = game._air_defense_loadout["asm"]
from src.air.asm import ASM
noise = ASM(game.ship.x + 5, game.ship.y, 0, 1, random.Random(10), profile)
rgpo = ASM(game.ship.x + 5, game.ship.y, 0, 2, random.Random(10), profile)
noise.jammer = rgpo.jammer = False
# ECM acts on a seeker in terminal lock: both missiles close on the ship
# (due west) 20 deg off the line of sight with the seeker locked.
noise = ASM(game.ship.x + 5, game.ship.y, 250, 1, random.Random(10), profile)
rgpo = ASM(game.ship.x + 5, game.ship.y, 250, 2, random.Random(10), profile)
for missile in (noise, rgpo):
missile.jammer = False
missile.locked, missile.los_prev = True, 270.0
noise.update(.1, game.ship, ecm_effect=ECMEffect(
.7, "noise", hoj_exposure=True))
rgpo.update(.1, game.ship, ecm_effect=ECMEffect(
.7, "rgpo", range_error_nm=1.0))
assert noise.course != 0.0
assert rgpo.course == 0.0
assert noise.course != 250.0
assert rgpo.course == 250.0
def test_ecm_auto_couples_terminal_threat_to_finite_softkill(monkeypatch):
+1
View File
@@ -668,6 +668,7 @@ def test_ciws_failure_spends_ammo_with_one_second_cadence(game, monkeypatch):
observer_x=game.ship.x, observer_y=game.ship.y,
course=None, quality=1, now=game.sim_t, label="ASM")
game.rng_asm.random = lambda: 1.0
game.ciws_mount_deg = 90.0 # mount already on the east bearing
ammo = game.ciws_ammo
game._update_air_defense(0.1, publish_picture=False)
burst = game._air_defense_loadout["ciws"]["rounds_per_attempt"]