mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-06 12:54:18 +01:00
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tk5v1FfvkLKPYqPVE98DaY
376 lines
16 KiB
Python
376 lines
16 KiB
Python
"""Directional sonar integration: input, observations, audio and persistence."""
|
|
|
|
import random
|
|
from types import SimpleNamespace
|
|
|
|
import numpy as np
|
|
import pygame
|
|
import pytest
|
|
|
|
from src.core import config
|
|
from src.core.game import Game
|
|
from src.core.station import Station
|
|
from src.enemies.civilian import CivilianShip
|
|
from src.enemies.decoy import Decoy
|
|
from src.enemies.sub import Sub
|
|
from src.ship.ship import Ship
|
|
from src.sonar.sonar import SonarSystem
|
|
from src.ui.sonar_view import _waterfall_plot, sonar_click_target, sonar_geometry
|
|
|
|
|
|
def press(game, key, **kwargs):
|
|
game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=key, **kwargs))
|
|
|
|
|
|
@pytest.fixture
|
|
def game():
|
|
game = Game(seed=6, start_menu=False)
|
|
game.station = Station.SONAR
|
|
return game
|
|
|
|
|
|
def test_bearing_controls_and_pages_do_not_change_ship_orders(game):
|
|
course = game.ship.target_course
|
|
press(game, pygame.K_r)
|
|
for key in (pygame.K_3, pygame.K_5, pygame.K_9, pygame.K_PERIOD,
|
|
pygame.K_9, pygame.K_RETURN):
|
|
press(game, key)
|
|
assert game.sonar.listen_bearing == 359.9
|
|
press(game, pygame.K_RIGHT, mod=pygame.KMOD_CTRL)
|
|
assert game.sonar.listen_bearing == pytest.approx(0.0)
|
|
press(game, pygame.K_LEFT, mod=pygame.KMOD_SHIFT)
|
|
assert game.sonar.listen_bearing == pytest.approx(355.0)
|
|
for _ in range(config.SONAR_PAGE_COUNT):
|
|
press(game, pygame.K_PAGEDOWN)
|
|
game.draw()
|
|
assert game.sonar_page == 0
|
|
press(game, pygame.K_DOWN)
|
|
press(game, pygame.K_UP)
|
|
assert not game.held and game.ship.target_course == course
|
|
|
|
|
|
def test_native_display_controls_are_transient_and_do_not_change_analysis(game):
|
|
gain = game.sonar.gain_db
|
|
press(game, pygame.K_c, mod=pygame.KMOD_SHIFT)
|
|
assert game.sonar_display_palette == "amber"
|
|
press(game, pygame.K_i, mod=pygame.KMOD_SHIFT)
|
|
assert game.sonar_display_contrast == 1.4
|
|
press(game, pygame.K_o, mod=pygame.KMOD_CTRL)
|
|
assert game.sonar_display_black == .01
|
|
press(game, pygame.K_h, mod=pygame.KMOD_SHIFT)
|
|
assert game.sonar_display_history == .25
|
|
assert game.sonar.gain_db == gain
|
|
controls = game.save_state()["sonar_controls"]
|
|
assert not any(key.startswith("sonar_display_") for key in controls)
|
|
|
|
|
|
def test_manual_beam_hears_without_selected_contact_and_resets_on_retune():
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sub = Sub(253, 250, 40, 0, "diesel_alt", random.Random(1))
|
|
sonar = SonarSystem(1)
|
|
sonar.set_listen_bearing(90)
|
|
for i in range(8):
|
|
sonar.update(.25, (i + 1) * .25, ship, [sub], world)
|
|
assert sonar.demon_analysis is not None
|
|
on_axis = np.sqrt(np.mean(sonar.listening_samples()**2))
|
|
assert sonar.broadband_history and sonar.lofar_times[-1] == 2.0
|
|
sonar.set_listen_bearing(270)
|
|
assert not sonar.lofar_history and sonar.demon_analysis is None
|
|
assert np.max(np.abs(sonar.receiver.samples)) == 0
|
|
assert sonar.broadband_history # Rundumsicht remains valid when retuning.
|
|
for i in range(8):
|
|
sonar.update(.25, 2.0 + (i + 1) * .25, ship, [sub], world)
|
|
off_axis = np.sqrt(np.mean(sonar.listening_samples()**2))
|
|
assert on_axis > off_axis * 5
|
|
assert sonar.demon_analysis is None
|
|
|
|
|
|
def test_contact_selection_does_not_silently_repoint_manual_beam(game):
|
|
target = game.subs[0]
|
|
contact = game.sonar._get_contact(target)
|
|
contact.bearing = 72.0
|
|
contact.last_seen = game.sim_t
|
|
game.sonar.set_listen_bearing(120)
|
|
press(game, pygame.K_DOWN)
|
|
assert game.selected_contact is contact and game.sonar.listen_bearing == 120
|
|
press(game, pygame.K_RETURN)
|
|
assert game.sonar.focus_locked and game.sonar.listen_bearing == 72
|
|
press(game, pygame.K_LEFT)
|
|
assert not game.sonar.focus_locked
|
|
|
|
|
|
def test_broadband_waterfall_click_sets_manual_listen_bearing(game):
|
|
game.sonar_page = 0
|
|
game.sonar.focus_locked = True
|
|
plot = _waterfall_plot(sonar_geometry(game)["main"], 0)
|
|
target = (plot.x + (plot.w - 1) * .75, plot.centery)
|
|
assert game._handle_sonar_click(sonar_click_target(game, target))
|
|
assert game.sonar.listen_bearing == pytest.approx(270.0)
|
|
assert not game.sonar.focus_locked
|
|
|
|
|
|
def test_lofar_waterfall_click_does_not_set_listen_bearing(game):
|
|
game.sonar_page = 1
|
|
game.sonar.set_listen_bearing(42)
|
|
plot = _waterfall_plot(sonar_geometry(game)["main"], 1)
|
|
target = sonar_click_target(game, plot.center)
|
|
# The click sets the frequency cursor (like Z/X), never the bearing.
|
|
assert target is not None and target["action"] == "cursor_hz"
|
|
game._handle_sonar_click(target)
|
|
assert game.sonar.listen_bearing == 42
|
|
|
|
|
|
def test_lost_track_holds_last_observation_not_target_position():
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sub = Sub(253, 250, 40, 0, "diesel_alt", random.Random(1))
|
|
sonar = SonarSystem(1)
|
|
sonar.focus_locked = True
|
|
sonar.update(.25, .25, ship, [sub], world, focus_tgt=sub)
|
|
bearing = sonar.listen_bearing
|
|
sub.x, sub.y = 0, 0
|
|
sonar.update(.25, 3, ship, [sub], world, focus_tgt=sub)
|
|
assert not sonar.focus_locked
|
|
assert sonar.listen_bearing == bearing
|
|
|
|
|
|
def test_game_passive_population_includes_civilian_and_decoy(game):
|
|
game.ship.speed = 0.0
|
|
game.civilians = [CivilianShip(game.ship.x + 2, game.ship.y, random.Random(2))]
|
|
game.decoys = [Decoy(game.ship.x + 3, game.ship.y, 10, random.Random(3))]
|
|
assert game.civilians[0].id != game.decoys[0].id
|
|
game._update_sensors(.25)
|
|
for target in game.civilians + game.decoys:
|
|
assert target.id in game.sonar.contacts
|
|
assert game._find_target(target.id) is target
|
|
|
|
|
|
def test_audition_band_removes_carrier_without_changing_receiver():
|
|
sonar = SonarSystem()
|
|
t = np.arange(1024) / sonar.receiver.sample_rate
|
|
sonar.receiver.samples = (.1 * np.sin(2 * np.pi * 700 * t)).astype(np.float32)
|
|
original = sonar.receiver.samples.copy()
|
|
sonar.listen_filtered = True
|
|
sonar.listening_samples(sonar.receiver.samples, block_id=1)
|
|
filtered = sonar.listening_samples(sonar.receiver.samples.copy(), block_id=2)
|
|
assert np.max(np.abs(filtered)) < .001
|
|
np.testing.assert_array_equal(sonar.receiver.samples, original)
|
|
|
|
|
|
@pytest.mark.parametrize("gain_db", [12, 24])
|
|
def test_audition_gain_retains_float_headroom_for_playback(gain_db):
|
|
sonar = SonarSystem()
|
|
sonar.receiver.samples[:] = np.linspace(-.2, .2, 1024)
|
|
sonar.gain_db = gain_db
|
|
samples = sonar.listening_samples()
|
|
assert np.isfinite(samples).all()
|
|
assert np.max(np.abs(samples)) == pytest.approx(.2 * 10 ** (gain_db / 20),
|
|
rel=1e-6)
|
|
assert np.max(np.abs(samples)) > (.75 if gain_db == 12 else 3.0)
|
|
|
|
|
|
@pytest.mark.parametrize("action", [pygame.K_F1, pygame.K_j, pygame.K_1])
|
|
def test_audio_stops_on_administration_mute_and_station_change(game, monkeypatch, action):
|
|
calls = []
|
|
monkeypatch.setattr(game.audio, "stop_sonar", lambda *a, **kw: calls.append(kw))
|
|
press(game, action)
|
|
assert calls
|
|
assert calls[-1] == {"immediate": True}
|
|
|
|
|
|
def test_sonar_page_cycle_via_hotkey_keeps_audio_stream(game, monkeypatch):
|
|
stops = []
|
|
monkeypatch.setattr(game.audio, "stop_sonar",
|
|
lambda *args, **kwargs: stops.append(kwargs))
|
|
game.sonar_page = 0
|
|
game._sonar_audio_sequence = 42
|
|
press(game, pygame.K_2)
|
|
assert game.station is Station.SONAR
|
|
assert game.sonar_page == 1
|
|
assert stops == []
|
|
assert game._sonar_audio_sequence == 42
|
|
|
|
|
|
def test_sonar_audio_uses_receiver_samples_and_only_new_blocks(game, monkeypatch):
|
|
calls = []
|
|
game.sonar.receiver.update([], 0, 12, .2, 2, 6)
|
|
expected = game.sonar.listening_samples().copy()
|
|
monkeypatch.setattr(game.audio, "play_sonar", lambda samples, rate, volume, **kwargs:
|
|
calls.append((samples.copy(), rate, volume)) or True)
|
|
game._update_audio(.25)
|
|
game._update_audio(.25)
|
|
assert len(calls) == 1
|
|
np.testing.assert_allclose(calls[0][0], expected)
|
|
assert calls[0][1] == game.sonar.receiver.sample_rate
|
|
assert calls[0][2] == game.sonar_volume
|
|
|
|
|
|
def test_sonar_controls_and_surface_focus_survive_slot_save(game):
|
|
civilian = game.civilians[0]
|
|
contact = game.sonar._get_contact(civilian)
|
|
assert contact.id != contact.target_id
|
|
game.selected_contact = contact
|
|
game.sonar_page = 2
|
|
game.sonar.set_listen_bearing(123.4)
|
|
game.sonar.listen_filtered = True
|
|
game.sonar_audio_enabled = False
|
|
game.sonar_volume = .3
|
|
game.save_to_slot(1)
|
|
game.reset(game.seed)
|
|
assert game.load_from_slot(1)
|
|
assert game.sonar.listen_bearing == 123.4
|
|
assert game.sonar.listen_filtered and game.sonar_page == 2
|
|
assert not game.sonar_audio_enabled and game.sonar_volume == .3
|
|
assert game.selected_contact.id == contact.id
|
|
assert game.selected_contact.target_id == civilian.id
|
|
assert game.selected_contact is game.sonar.contacts[civilian.id]
|
|
assert game.sonar.demon_analysis is None # DSP warms up instead of inventing state.
|
|
|
|
|
|
def test_history_and_peak_hold_are_bounded():
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sonar = SonarSystem()
|
|
sonar.peak_hold = True
|
|
for i in range(config.LOFAR_HISTORY_COLS + 5):
|
|
sonar.update(.25, (i + 1) * .25, ship, [], world)
|
|
assert len(sonar.lofar_history) == len(sonar.broadband_history) == config.LOFAR_HISTORY_COLS
|
|
assert len(sonar.lofar_times) == len(sonar.lofar_bearings) == config.LOFAR_HISTORY_COLS
|
|
assert len(sonar.peak_spectrum) == config.LOFAR_BINS
|
|
assert sonar.history_times == sorted(sonar.history_times)
|
|
assert len(sonar.broadband_long_history) == (
|
|
(config.LOFAR_HISTORY_COLS + 5)
|
|
// round(config.SONAR_BROADBAND_LONG_SAMPLE_S / sonar.receiver.block_s))
|
|
assert len(sonar.demon_history) == min(
|
|
config.LOFAR_HISTORY_COLS + 5, config.SONAR_DEMON_HISTORY_ROWS)
|
|
assert sonar.broadband_long_times == sorted(sonar.broadband_long_times)
|
|
assert sonar.demon_times == sorted(sonar.demon_times)
|
|
|
|
|
|
def test_display_histories_are_bounded_and_long_broadband_is_decimated():
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sonar = SonarSystem()
|
|
block_count = (config.SONAR_BROADBAND_LONG_ROWS + 4) * round(
|
|
config.SONAR_BROADBAND_LONG_SAMPLE_S / sonar.receiver.block_s)
|
|
for index in range(block_count):
|
|
sonar.update(.25, (index + 1) * .25, ship, [], world)
|
|
|
|
assert len(sonar.broadband_long_history) == config.SONAR_BROADBAND_LONG_ROWS
|
|
assert len(sonar.broadband_long_times) == config.SONAR_BROADBAND_LONG_ROWS
|
|
assert len(sonar.demon_history) == config.SONAR_DEMON_HISTORY_ROWS
|
|
assert all(len(row) == 180 for row in sonar.broadband_long_history)
|
|
assert all(len(row) == 80 for row in sonar.demon_history)
|
|
|
|
|
|
def test_bathythermograph_and_towed_depth_are_operator_controls(game):
|
|
assert game.sonar.bt_profile is None
|
|
press(game, pygame.K_e)
|
|
profile = game.sonar.bt_profile
|
|
assert profile is not None
|
|
assert len(profile["depths_m"]) == len(profile["speeds_m_s"]) == 21
|
|
# Convergence zones follow the measured profile: bounded sorted bands, possibly none.
|
|
bands = profile["cz_bands_nm"]
|
|
assert isinstance(bands, list) and len(bands) <= 4
|
|
assert all(0.0 < near < far for near, far in bands)
|
|
assert game.sonar.bt_cooldown == config.SONAR_BT_COOLDOWN_S
|
|
|
|
game.sonar.tow_state = game.sonar.STREAMED
|
|
game.sonar.tow_payout = 1.0
|
|
before = game.sonar.towed_depth_target_m
|
|
press(game, pygame.K_v)
|
|
assert game.sonar.towed_depth_target_m == before + 10.0
|
|
game.sonar.update(1.0, 1.0, game.ship, [], game.world)
|
|
assert before < game.sonar.towed_depth_m < game.sonar.towed_depth_target_m
|
|
|
|
|
|
def test_towed_array_below_layer_improves_deep_target_range():
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sub = Sub(255, 250, 160, 0, "diesel_alt", random.Random(4))
|
|
sonar = SonarSystem(4)
|
|
sonar.tow_state = sonar.STREAMED
|
|
sonar.tow_payout = 1.0
|
|
sonar._tow_settle_s = config.SONAR_TOWED_SETTLE_S
|
|
sonar.towed_depth_m = 50.0
|
|
shadowed = sonar.passive_range_nm(sub, 5.0, ship, world, 1.0, "TOWED")
|
|
sonar.towed_depth_m = 150.0
|
|
same_layer = sonar.passive_range_nm(sub, 5.0, ship, world, 1.0, "TOWED")
|
|
assert same_layer > shadowed * 2.0
|
|
|
|
|
|
@pytest.mark.parametrize("offset,status", [
|
|
(1.0, "BESTAETIGT"),
|
|
(12.0, "DIVERGENT / GEISTERKONTAKT?"),
|
|
])
|
|
def test_hms_tas_fusion_uses_separate_observed_bearings(offset, status):
|
|
ship = Ship(250, 250, speed_kn=0)
|
|
world = SimpleNamespace(sea_state=0, thermocline_depth_m=lambda x, y: 100)
|
|
sub = Sub(252, 250, 40, 0, "diesel_alt", random.Random(5))
|
|
sonar = SonarSystem(5)
|
|
sonar.tow_state = sonar.STREAMED
|
|
sonar.tow_payout = 1.0
|
|
sonar._tow_settle_s = config.SONAR_TOWED_SETTLE_S
|
|
sonar._observed_bearing = lambda target, true, frigate, quality, mode, t: \
|
|
true + (offset if mode == "TOWED" else 0.0)
|
|
sonar.update(.25, .25, ship, [sub], world)
|
|
contact = sonar.contacts[sub.id]
|
|
assert set(contact.array_observations) == {"BOW", "TOWED"}
|
|
assert contact.fusion_status == status
|
|
assert contact.fusion_delta_deg == pytest.approx(offset)
|
|
|
|
|
|
def test_environment_and_fusion_state_survive_save_load(game):
|
|
press(game, pygame.K_e)
|
|
game.sonar.towed_depth_m = 87.0
|
|
game.sonar.towed_depth_target_m = 110.0
|
|
contact = game.sonar._get_contact(game.subs[0])
|
|
contact.array_observations = {
|
|
"BOW": {"bearing": 20.0, "quality": .5, "snr": 4.0,
|
|
"last_seen": game.sim_t}}
|
|
contact.fusion_status = "NUR BOW"
|
|
data = game.save_state()
|
|
restored = Game(seed=99, start_menu=False)
|
|
restored.load_state(data)
|
|
assert restored.sonar.bt_profile == game.sonar.bt_profile
|
|
assert restored.sonar.towed_depth_m == 87.0
|
|
assert restored.sonar.towed_depth_target_m == 110.0
|
|
loaded = restored.sonar.contacts[contact.target_id]
|
|
assert loaded.array_observations == contact.array_observations
|
|
assert loaded.fusion_status == "NUR BOW"
|
|
|
|
|
|
def test_contact_row_click_selects_and_trains_the_beam_on_it(game):
|
|
"""A click on a contact card picks it and listens to it at once (Up/Down
|
|
then Enter), so the waterfall and the sound switch to that contact."""
|
|
from src.ui import layout
|
|
first, second = game.subs[0], game.civilians[0]
|
|
for entity, bearing in ((first, 40.0), (second, 200.0)):
|
|
contact = game.sonar._get_contact(entity)
|
|
contact.bearing = bearing
|
|
contact.last_seen = game.sim_t
|
|
game.sonar.set_listen_bearing(120)
|
|
with layout.capture_geometry() as drawn:
|
|
game.draw()
|
|
rows = {item["title"]: item["rect"] for item in drawn
|
|
if item["kind"] == "sonar-contact"}
|
|
picked = game.sonar.contacts[second.id]
|
|
rect = rows[f"sonar:contact:{picked.id}"]
|
|
game.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=rect.center))
|
|
game.handle_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=rect.center))
|
|
assert game.selected_contact is picked
|
|
assert game.sonar.focus_locked
|
|
assert game.sonar.listen_bearing == pytest.approx(200.0)
|
|
|
|
|
|
def test_contact_row_click_on_a_stale_contact_only_selects_it(game):
|
|
contact = game.sonar._get_contact(game.subs[0])
|
|
contact.bearing = 72.0
|
|
contact.last_seen = game.sim_t
|
|
game.sim_t += 5.0
|
|
game.sonar.set_listen_bearing(120)
|
|
assert game._handle_sonar_click({"action": "contact", "value": contact.id, "safe": True})
|
|
assert game.selected_contact is contact
|
|
assert not game.sonar.focus_locked and game.sonar.listen_bearing == 120
|