Compare commits

..

58 Commits

Author SHA1 Message Date
chexit a02b7d1177 Update the AirDef development handoff
build / mod (push) Successful in 30m50s
2026-12-02 18:53:16 +03:00
chexit fc04adcd39 Keep live object rows readable during dense raids 2026-12-02 18:53:16 +03:00
chexit f6303fe4d4 Keep heavy AirDef batteries available for confirmed missile threats 2026-12-02 18:52:41 +03:00
chexit 20fdb23b39 Show live Horizon terrain and radar views in the web panel 2026-12-02 18:52:41 +03:00
chexit 7612d15963 Finish AirDef catalog, route, stock and observation fixes
build / mod (push) Successful in 30m46s
Refs #91, #114, #118, #135. Show the latest recorded unit decision in the native card (#153).
2026-12-02 18:22:22 +03:00
chexit 9e0cec13f2 Add battle timeline markers and incremental web map updates (#153)
build / mod (push) Successful in 30m14s
2026-12-02 11:54:02 +03:00
chexit 906159b17f Add the AirDef tablet web panel and battle archive (#153) 2026-12-02 00:46:18 +03:00
chexit dfb306edd7 Record unit decisions and show their replay moments (#153) 2026-12-02 00:01:03 +03:00
chexit b882dc3c2b Open the unit card from the visible model (#153) 2026-12-01 23:43:14 +03:00
chexit 5e3907aa99 Keep battle reviews reachable and tied to the recorded outcome (#148, #153) 2026-12-01 23:03:40 +03:00
chexit bf558c024e Add a command post and shared unit cards (#153) 2026-12-01 22:55:45 +03:00
chexit 7e6d9d8b9a Add village defense campaign and breakthrough reports
Co-Authored-By: Codex <noreply@openai.com>
2026-11-26 01:12:38 +03:00
chexit aa842d8a1f Fix raid gameplay, finite ammunition and truck routing
Check launch terrain, reserve ballistic targets for marked objectives, tune in-game reach and fallback fire, and support bounded terrain work on supply routes.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-25 18:53:17 +03:00
chexit 61c4fa5cee Pin the HD light masks and record RTX 3060 benchmarks (#147)
build / mod (push) Failing after 18s
Measure matching DLSS and native TAAU modes on Windows before and after the renderer changes. On the 480-light graphics fixture, the masks improve 37.0 to 41.6 FPS with DLSS. The same candidate reaches about 58 FPS with TAAU in fullscreen.

Verified the GPU output on the RTX 3060 with a static capture, 36 HD tests including shader translation, and the separate Metal TAAU test.
2026-11-24 19:40:42 +03:00
chexit aaf72ef171 Fix HD benchmark reporting and record renderer A/B results (#147)
build / mod (push) Failing after 17s
Resolve benchmark input paths before switching to the disposable game home and report startup failures without a missing screenshot traceback. Capture the executable hash and keep report environment metadata limited to benchmark settings.

Record the earlier light and smoke measurements and the repeated idle A/B runs. Verified with 18 Python benchmark tests, 36 Horizon HD tests, the Metal TAAU smoke test, and the real idle launch and error paths.
2026-11-24 18:24:00 +03:00
chexit 4b8fef6d8a Point horizon at the HD light-tile and smoke-skip fixes (#147)
build / mod (push) Failing after 10s
The engine's kimi-work-124 moves b4c68a78b..4215e8999:

- The light tiles keep the whole screen's lights in one global list instead
  of a copy per tile, and the tile lists no longer overflow into "every
  light on every pixel". In a raid the render phase of the window thread was
  27-83 ms of CPU a frame on an M5 at 1440p (tile_lists 21-25% of the thread
  in a sample); it is 5-13 ms now.
- The fog's march skips the steps that stay inside an empty brick of the
  smoke grid: about -11% of the GPU time where a raid's replay still has
  smoke, nothing where it has none.

Neither changes the picture: on one paused frame of a recorded raid, with
and without each (the smoke-skip and light-tiles diagnostics), the pixels
that do not depend on the wall clock are the same to the frame-to-frame
flicker of one level. The water is not compared: it moves with the clock.

Not explained: in the early windows of a replay some frames take 100-230 ms
with 45-55 ms of GPU and 20-30 ms of CPU. The engine before the fixes shows
it too.
2026-11-24 17:09:08 +03:00
chexit 9b8ef1bcc8 CI: keep the per-push job inside the runner's disk (#102)
build / mod (push) Failing after 9s
Run 140, the first green build since 2 November, knocked Gitea's database
over: from 19:42:52 UTC, right after the mod test binaries were written,
the API answered 500 and 401 and ssh said 'the database system is in
recovery mode' until 19:53:28, eighteen seconds after the job had ended and
its workspace was gone. The tests themselves are innocent (ground_oom peaks
at 113 MiB RSS); what the job leaves behind is not. rustup installed stable
and then the pinned 1.99.1 on top of it (about 1.1 GB), and the debug test
targets of the core and of the mod (669 MB for the mod alone) stayed on
disk through the release build. The runner shares that disk with Gitea and
its database; on 6 November release.yml found 1 GB free there.

The job now installs only the channel pinned in rust-toolchain.toml, deletes
each test target directory once its step is done, and refuses to start with
less than 4 GB free, with the same ::error:: wording as release.yml, after
printing df and free into the log. Both test suites stay complete.

Not verified on the server (no access there). The log now shows the free
space at the start, so the next run confirms or corrects the diagnosis.
2026-11-23 23:08:04 +03:00
chexit d9431468c1 gen_models --check: compare PNGs by their pixels, not their bytes (#92)
build / mod (push) Has been cancelled
With Pillow installable again, build.yml failed one step later: on the Linux
runner 171 generated PNGs (every item icon) differed from the committed
files. Their pixels are identical (sha256 of the decoded rasters matches
the macOS ones byte for byte); only the deflate stream differs, because the
zlib inside the Pillow wheel is built per platform and Python version. The
manifest's byte hashes are not portable, so the check could only pass where
the assets had been generated.

--check now treats a PNG whose bytes differ as unchanged when it decodes to
the same mode, size and pixels, and only while the file still matches its
manifest row: a hand-edited file stays a conflict. Writing (a run without
--check) and the manifest stay byte-exact.

Verified: a copy of airdef-mod with all 175 manifest PNGs re-encoded
(stored blocks) and the manifest rows updated passes --check; the real tree
still reports no differences; tools/test_gen_assets.py OK (13 tests, two
new: a re-encoded icon is accepted and then rewritten by a real run, another
picture and a hand-edited icon are still reported).
2026-11-23 22:31:21 +03:00
chexit 5ac72287f4 CI: let pip install the pinned Pillow into the externally managed runner Python (#102)
build / mod (push) Failing after 39s
Since 2 November build.yml has failed before its first test: gen_models.py
--check needs Pillow, and python3 -m pip install --user refuses the system
Python of the catthehacker/ubuntu:act-latest image (PEP 668,
externally-managed-environment). The job container is disposable, so
--break-system-packages with --user is safe here.

No step order or limit changes; the checkout, fork and Rust steps already
passed and are untouched.
2026-11-23 21:56:22 +03:00
chexit 6616d58a3e Resolution Scale: 100% is DLAA (1:1), monotonic; docs + test-dlss.bat
build / mod (push) Failing after 33s
Point horizon at b4c68a78b (the slider is monotonic: 100% renders 1:1 DLAA,
80% no longer renders larger than 100%). Update the scale docs and pin
test-dlss.bat to HORIZON_HD_SCALE=0.67 for the upscaling A/B (empty would now
be DLAA at the slider's 100%).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-22 12:24:27 +03:00
chexit b8049674bb engine: the Resolution Scale slider drives HD render scale (DLSS included)
build / mod (push) Failing after 33s
Pin horizon to 4e441de6a (agent/resolution-scale): hd::scale_override used
to pin the HD world at 2/3 whenever DLSS was enabled and its SDK open, so
the Resolution Scale slider (50-200%) was ignored — pixel-identical image
and unchanged FPS at every step. Now the slider drives the world target and
the DLSS render size live, no restart: film quality, then HORIZON_HD_SCALE,
then the slider; with DLSS the render scale caps at the output (100% keeps
the 2/3 auto ratio, above 100% renders at the output — supersampling is
native TAAU's with DLSS off), without DLSS the slider applies as-is
including above 1. The jitter and motion globals match the new size on the
very frame it changes; the NGX context is kept while the render size fits
its dynamic-resolution range, and the histories reset on every scale
change. The #143 motion/jitter contract (MVJittered, render-pixel jitter,
MV scale [1,1]) is intact.

Verified on Mac (M5/Metal, no DLSS device): lib suite 1243 passed, new GPU
test the_world_target_follows_the_resolution_slider (50/100/200% target
sizes + live resize + hd_scale precedence), taau_gpu_smoke_still_surface_ab,
non-dlss build, and a Windows-gnu cross-check of the dlss-gated code against
the NGX v310.9.1 headers. DLSS evaluation awaits RTX.

Docs: DLSS-TESTING.md documents the scale semantic, the live-update
mechanism and the RTX verification checklist (slider changes the DLSS
render size + FPS, no shaking regression, context reuse, fallback logs);
HD-RENDERER.md's scale references follow the slider.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-22 12:05:45 +03:00
chexit 24f3485ebb save: assemble the air section with write! instead of += &format!
build / mod (push) Failing after 30s
Sim::air_text built the save text with `head += &format!(...)` per contact
and `line += &format!(...)` per relief run, and Drone::air_line did the same
for a route point. Each of those allocated a temporary String and re-copied
the whole growing buffer, so the cost was quadratic in the section's size.
The head is not covered by the fits check (only the drone/queue body is): up
to 8 relief grids of 40k run-length tokens each plus 4096 contact lines. On a
heavy raid the autosave's tick therefore exhausted its 300M fuel while
formatting — the crash was in Sim::air_text.

Format directly into the buffer now (std::fmt::Write, push_str, push), which
grows it amortized with no per-token temporary. Nothing else changes: the
format, every MAX_* bound and the byte-budget logic are untouched.

The output is byte-identical: the same air_text over a relief-heavy raid
state and over the 600-drone byte-bound state hashes and measures the same
before and after (64a1787d37047447, 894 and 747942 bytes).
2026-11-21 18:46:19 +03:00
chexit 5737b47dc5 record: thin track points on the caller's grid; extreme-load test; re-pin the stale budget stats
build / mod (push) Failing after 59s
The points budget first gated on (recording tick - first) % step, but a strike
carrier's samples fall on its flight-age grid, offset from the recording's
ticks — the gate skipped them (physical_strike_track_keeps_muzzle... failed).
Count the sampling calls per track instead (Track::due): at STEP it pushes
every call exactly as before, and the thinning doubles the interval without
touching the track's phase. Track::points_len exposes the count for diagnostics.

tests/ground_oom.rs gains the continuous extreme load (eight overlapping
40-Oreshnik waves, 1118 objects airborne at once — well past the crash's >200):
peak 26.3 MiB steady + 5.5 MiB rehash transient, the flight tracks thin to
step 16 (91k points, 2.3 MiB) under their 2 MiB budget, the journal and poses
stay within theirs, and the fight still resolves (157 intercepts). The radar
picture itself (11.5 MiB at 1118 airborne) scales with the sky — it is the
simulation's state, not a cache, and is ~3 MiB at the crash's >200 load.

The WASM budget fixture's final /airdef stats pin was stale at the base commit
already: it was measured on engine 8e711f969, and the base pins acfb379aa,
whose host answers shift the two late Smart raids (417/2463, 7 in the air).
Verified identical on the pristine base and on this branch — the memory bounds
do not move that fight; the tick-2102 checkpoint (184/325/2011) is unchanged.
Re-pinned to the measured string and updated BUDGET_ASSERTED_SHA256 so the
raid/snapshot assertions stay active. test-budgets: 283 steps ok, tick fuel
max 184.7M/300M, 0 failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:57:51 +03:00
chexit dc87c0b98a sim: bound the ground cache and the recording under the 64 MiB WASM budget
The fullscreen-map OOM (rust_oom in hashbrown reserve_rehash under
Ground::answer during a large raid): the mod's whole state shares one
64 MiB linear memory, and three consumers grew without an effective bound.

Measured on a native replica of the crash load (tests/ground_oom.rs: 64
complexes, six all-sides Oreshnik raids plus a smart raid over 10000 ticks,
304 objects airborne at once, a wide map query walk; render answers exactly
as the WASM host gives them): peak 45.5 MiB steady + 21.9 MiB rehash
transient = 67 MiB, over the cap. The bulk: kept replays 23.2 MiB (the scene
journal 4.6 MiB each, filled with per-radar track transitions), Ground.known
10.9 MiB (277k columns; the old sweep only ran above 300k and kept everything
younger than 2000 ticks, so a wide query pattern grew it without bound and
the next rehash doubled the table), the live recording 7.5 MiB, radar tracks
3.2 MiB.

Bounds, derived from the 64 MiB budget (Sim::memory reports each consumer):
- Ground.known: KNOWN_MAX 100_000 columns (~2.7 MiB steady, ~8.2 MiB through
  a rehash at 24 B + control byte per entry, 7/8 load). Over the cap the
  oldest answers go down to three quarters (a sweep is not every tick),
  ordered by (age, column) so the sweep is deterministic; heights past
  SWEEP_AGE go with them. Evicted columns are asked again when next needed —
  the cache is reconstructible, no target, frequency or precision is cut.
- Scene journal: MAX_SCENE_EVENTS 65_536 -> 24_576 (~1.7 MiB), and the track
  transitions (acquire/handoff/lock/lost — they grow with systems x contacts,
  the journal's bulk under a large raid) get their own 8_192 budget; beyond
  it the later ones are not recorded. Launches, fires and outcomes keep the
  rest of the journal; chains() already tolerates missing steps.
- Flight track points: MAX_TRACK_POINTS 2 MiB per recording; over it every
  other point is kept and the ticks between points double (Track::step, the
  #142 decimation pattern for the systems' poses). Replay readers use the
  track's own step.

Replica peak after: 24.5 MiB steady + 5.5 MiB transient = 30 MiB, under the
48 MiB headroom target; the fight resolves (376 intercepts, sky clears) and
the same seed replays the same ordered trace. The saturation checkpoint is
untouched (314 / 2022 / 184): its cache stays under the cap.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:55:54 +03:00
chexit 4dbe103f5b sim: account where the mod's memory goes (Sim::memory, per-cache bytes)
The fullscreen-map OOM (Ground::answer rehash under a large raid) needs a
measured breakdown, not a guess: Sim::memory estimates each consumer's
allocated capacity (hashbrown tables with their control bytes, vec capacities,
BTreeMap nodes) — Ground.known, WorldCache.secs and rays, the sim vectors and
radar tracks, the recording and kept replays, Intel/recon, routes, sites,
strikes, the raid plan. MemoryReport::rehash_headroom names the transient a
rehash adds (old + new table of the biggest map). Ground::known_len exposes the
column count the budget tests guard.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:55:54 +03:00
chexit dca35dc9a2 Point horizon at the 512 MiB mod-memory cap; re-baseline the budget final stats
build / mod (push) Failing after 30s
The larger memory cap shifts the heavy scenario's final stats slightly
(417/2463, fewer pending sections); deterministic across runs, fuel
failures still 0. The tick-2102 checkpoint is unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:53:20 +03:00
chexit 3a992e7369 Point horizon at the DLSS temporal-stability fix; document the RTX checks
build / mod (push) Failing after 31s
Engine agent/dlss-temporal-stability (a791e8439 -> acfb379aa):
- f536fa958 DLSS: declare the jittered motion vectors (MVJittered). The create flags left
  MVJittered unset, so NGX applied the jitter offset on top of the already-jittered motion
  buffer — the camera jitter counted twice, the severe shaking. Contract verified against the
  DLSS Programming Guide (31 March 2026) §3.6.1-3.6.3/§3.7.3/§3.8.1, nvsdk_ngx_defs.h and
  Streamline's dlssEntry.cpp (pixel-space vectors take MV.Scale 1.0; the {1/w,1/h} advice is
  Streamline's own constant, scaled back by its plugin).
- 26ee82398 Native TAA: a reactive mask for water (its own depth, binding 7; less history where
  the waves/glint animate fastest, faded to 96 blocks) + the wind-motion contract test.
- acfb379aa Wind-blown leaves and plants carry their own motion vectors (previous frame's wind
  time/strength in Globals.hd_motion.zw, terrain.wgsl wind_offset_at).

Verified on Mac (no RTX): horizon-client --lib 1242 passed / 0 failed; taau_gpu_smoke on Metal
(fixed decode at the spatial filter's error floor, phase spread 0.0029 vs legacy 0.0156); naga
validation + HLSL translation of every HD shader and terrain/entity; frame/global layouts;
deterministic jitter/reprojection fixtures; non-dlss binary build; clippy clean on the touched
files. NGX evaluation itself awaits RTX — docs/DLSS-TESTING.md has the verification steps and
three fallback variants (jitter sign/axes, Streamline-style scale, non-jittered conversion pass).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:56:38 +03:00
chexit f7ec0a3373 Docs: battery variants deploy by remote or command, not the removed N-menu page
build / mod (push) Failing after 30s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:48:01 +03:00
chexit 4d7815834d Give each battery variant its own placeable remote
build / mod (push) Failing after 28s
Every catalog variant now has a `airdef:deploy_<id>` remote in `give` and
in the hotbar: deploy_radar_search, deploy_radar_track, deploy_radar_height,
deploy_s400_launcher and deploy_s500_launcher. The variant rows carry their
remote item in the generated catalog, and the inventory appends them after
the existing remotes so no ordinary remote changes slot.

Placing a remote now resolves the item back to its (kind, mode, role)
configuration and settles the system, the same path `/airdef deploy <key>`
already used. The base remotes keep deploying the ordinary integrated,
multifunction system; the radar remotes place Search/Engagement/Height
profiles, so radar_track gets fire authority and the others do not.

The N menu's battery-deploy page is removed entirely (button, page and its
handlers); variants remain available through `/airdef deploy` and now the
remotes. Items, icons (aliased to the unit silhouettes), lang entries and
generated assets are regenerated from the content catalog.

Checks: gen_catalog.py --check, gen_models.py --check, test_gen_assets (11),
airdef-mod lib 115 + integration suites, airdef-core 327, cargo build.
2026-11-21 16:44:23 +03:00
chexit b735458dd8 Point horizon at the DLSS colour filterable-texture fix (#124)
build / mod (push) Failing after 29s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 16:08:53 +03:00
chexit 74baf8b4e2 Document the libclang auto-install
build / mod (push) Failing after 29s
The zero-step Windows+RTX toolchain now also covers libclang: LLVM is no
longer a build prerequisite, the detected or downloaded directory is
passed as LIBCLANG_PATH, and the cache layout gains
.horizon-cache/libclang/<version>/. Manual override (winget install
LLVM.LLVM + LIBCLANG_PATH) and the Unable to find libclang troubleshooting
note remain.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:55:14 +03:00
chexit 67e8a19e2b Auto-install libclang for bindgen on Windows + NVIDIA RTX
The DLSS build failed on Windows at dlss_wgpu's bindgen step: libclang.dll
is neither in the DLSS SDK nor in the Vulkan headers. It is now part of the
same zero-manual toolchain.

Detection first, download last: an explicit LIBCLANG_PATH (directory with
libclang.dll or clang.dll) wins and disables auto-install; otherwise PATH,
Program Files\LLVM\bin (both Program Files roots) and LLVM shipped with
Visual Studio (vswhere -find VC\Tools\Llvm\x64\bin\libclang.dll) are
checked, then the cache.

When nothing is found, the NuGet package libclang.runtime.win-x64 is
downloaded (~34 MB, version from the flat-container index with pinned
23.1.5 fallback) and only runtimes/win-x64/native/libclang.dll (~89 MB) is
extracted to .horizon-cache/libclang/<version>/ behind the existing
staging + airdef-install.json marker pattern. The resolved directory is
passed to cargo as LIBCLANG_PATH.

libclang is resolved only when the DLSS SDK and Vulkan headers are already
available, so a missing SDK never triggers a useless download. Any
detection/download/extract failure warns and degrades to mods/TAAU, and
non-Windows/non-RTX still returns before any network access.

Tests cover PATH/Program Files/vswhere detection, explicit precedence,
numeric NuGet version choice and fallback, selective extraction and marker,
cache hit, damaged cache reinstall, package without the DLL, plan env
wiring and failure to mods-only.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:55:12 +03:00
chexit e61b2e8f64 Cover mixed explicit-env and auto-download DLSS resolution
build / mod (push) Failing after 29s
A valid DLSS_SDK must not block the Vulkan header auto-download, and vice
versa; assert that only the missing component is fetched.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:44:12 +03:00
chexit 97d97eb37c Keep a broken DLSS cache directory from failing the build
Scanning .horizon-cache/dlss-sdk is best-effort: a permissions error or a
missing directory now means "nothing cached" and the normal install path
runs, instead of an exception escaping before the mods fallback.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:43:48 +03:00
chexit 84e9d6ab60 Document the zero-step DLSS toolchain install
The quick-start build section no longer asks for an NVIDIA DLSS SDK or a
LunarG Vulkan SDK: `airdef.py all` downloads only the headers, static libs
and nvngx_dlss.dll it needs, caches them under .horizon-cache with a
version marker, and copies the fresh DLL beside horizon-client.exe. Keeps
the explicit DLSS_SDK/VULKAN_SDK override, the offline/failure fallback to
mods with native TAAU, and the remaining LLVM/clang build prerequisite.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:40:00 +03:00
chexit 88757d05f8 Auto-install the DLSS toolchain on Windows + NVIDIA RTX
`airdef.py game` no longer needs manual SDK setup. On Windows with an RTX
adapter, when neither DLSS_SDK nor VULKAN_SDK is set, it downloads only the
files dlss_wgpu reads:

- NVIDIA/DLSS at the newest stable v310.9.x tag (GitHub API; pinned v310.9.1
  when the API fails): include/*.h, both x64 static libs and the runtime
  rel/nvngx_dlss.dll (~67 MB once), laid out under
  .horizon-cache/dlss-sdk/<tag>/ exactly as valid_dlss_sdk expects.
- KhronosGroup/Vulkan-Headers include/ under
  .horizon-cache/vulkan-headers/<tag>/Include/, since build.rs uses headers
  only and links no Vulkan library.

The resolved roots are passed to cargo as DLSS_SDK/VULKAN_SDK, and after a
successful dlss build the fresh nvngx_dlss.dll is copied beside the built
horizon-client.exe. Explicit DLSS_SDK/VULKAN_SDK (and the sdk argument)
keep priority and disable auto-download for that component. Any network or
layout failure warns and falls back to --features mods/native TAAU instead
of failing the build; non-Windows and non-RTX take the old mods path with
no network access.

valid_dlss_sdk now looks for the real nvsdk_ngx*.h names instead of the
nonexistent nvngx*.h glob, so a genuine SDK (and the downloaded cache) is
recognised at all.

Tests cover tag selection and fallback, selective layout + marker cache
hit, damaged/partial caches, streamed download and truncation, Vulkan
Include layout, plan env wiring, explicit-env precedence, failure to mods,
and DLL placement beside the client.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:39:56 +03:00
chexit 8d716eccaf Point the DLSS build hint at the mod settings toggle
build / mod (push) Failing after 30s
The build auto-detect hint still said HORIZON_DLSS=1 enables the backend;
the player-facing control is now the mod settings toggle (default on),
with HORIZON_DLSS=1|0 as an override.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:08:03 +03:00
chexit e85e7a18d0 DLSS on/off toggle in the mod settings, persisted per world
The More page (N → Огонь, ремонт, эффекты…) gains a DLSS row next to
Акустика. Default on: a world without a saved choice leaves the engine's
own default (on where supported). The row reads render.dlss-status (API
level 33): with a DLSS device it toggles live; without one it says
«недоступен», and an on-request is kept and applied at the next launch —
a graceful no-op, never an error. The request is saved in the world's
layout (`dlss true|false`, older saves load unchanged) and re-applied on
world load; the engine persists it in horizon-graphics.txt for the next
start's device opening. /airdef capabilities reports the DLSS state too.

Graphics-only: no resolution control (the player's own Horizon settings
stay in charge) and no sim changes. Engine gitlink → b2cc11c45
(agent/dlss-toggle): the dlss graphics setting, the live evaluation gate,
the dlss control command and the level-33 SDK imports.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:06:25 +03:00
chexit 11238c4a03 Add dlss to the game build on Windows + NVIDIA RTX with the SDK
build / mod (push) Failing after 29s
tools/airdef.py game always built with --features mods, so an RTX user had
to run the manual cargo line from docs/DLSS-TESTING.md. The feature string
now comes from dlss_build_features(): dlss is added only when the OS is
Windows, a Win32_VideoController name has both NVIDIA and RTX, the DLSS SDK
has include/nvngx*.h and lib/Windows_x86_64/x64 (DLSS_SDK, a repo DLSS/ dir
or %ProgramFiles%\NVIDIA\DLSS), and VULKAN_SDK has Include/vulkan/vulkan.h
(dlss_wgpu's build script needs both SDKs). Otherwise the build stays
mods-only; on Windows + RTX without the SDK it prints how to get v310.9.1
instead of failing. GPU/SDK probe errors mean "no DLSS" and never abort the
build; the HORIZON_DLSS runtime switch is untouched.

Tests: tools/test_airdef_build.py covers non-Windows, no RTX, missing DLSS
SDK, missing Vulkan SDK, the full toolchain, a failed GPU probe, the SDK
layout check and the feature string reaching cargo. python3 tools/airdef.py
game still builds mods-only on macOS (fresh target dir: 3m11s, exit 0).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 14:21:20 +03:00
chexit d8d9913770 Issue #126 point 4: same-tick A/B parity and timing record
build / mod (push) Failing after 29s
The temporary in-session shader switch (harness build, reverted) renders the
same frozen tick with both effects.wgsl versions: old-vs-new differs by at
most 1-2/255, no pixel over 5/255, and no more than two frames of the same
shader differ. Frame time is below the in-game noise floor on M5 (32
screen-filling late-life fireballs: +0.37 ms median, sigma 3.6). Includes
the hd_bench polygon_noon run and test counts.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:51:13 +03:00
chexit 8fb849f195 Skip the fireball raymarch when its fade is zero (#126 point 4)
In the HD smoke path fade = 1 - smoothstep(0.08, 0.28, k) is exactly 0
from k = 0.28: every step's density is zero, absorb is 0, so the march
adds no light and leaves transmittance alone while still sampling fbm
and shading the volume. Wrap the loop in an `if fade > 0.0` guard; the
glow after it is untouched (heat is still live there) and is itself
skipped once its heat is spent. Density, steps, sampling and lighting
are unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:51:13 +03:00
chexit 1a82742744 CPU timeline profile of the battle frame (#147 step 3.1, #126 D/E)
build / mod (push) Failing after 28s
Measure-first profile naming the culprit with data; no worker implemented
(step 3.2 is out of scope). docs/measurements/issue-147-cpu-profile/: README +
report-server.json (default server-thread path) + report-inframe.json
(--in-frame control), M5/Metal 2560x1440 HD, same-recording battle with
overlapping raids + explosions + dense smoke, each run serialized under the
shared flock /tmp/airdef-bench.lock (earlier concurrent runs discarded).

Instrumentation: host per-tick tick_mods spans (ground/world/snapshot/wasm/
models/output/total, HORIZON_MOD_CPU_PROFILE=1, attributed by tick+frame),
mod Sim::step phase timing via an adapter-injected monotonic clock
(game.monotonic-nanos, API level 32; airdef-core stays SDK-free), raid_bench
--scheduler + per-frame span/frame correlation + mod phase delta.

Findings: on the default path the battle frame is GPU-bound (GPU avg 73.7ms ~
frame p95 88ms; 127/128 frames >33ms); the mod path is ~2.5ms/tick, per-frame
p99 7.7ms, 0 frames >25ms, host world answers <0.1ms, model prep ~0.05ms; the
872ms CPU spike is a render/GPU hitch (mod 2.15ms). In-frame is CPU-bound
(CPU p99 175ms); the mod path reaches >25ms in 27 frames, and step_drones
dominates Sim::step (52%, max 47ms/tick), A* only 15%. The schedulers' mod
peaks do not coincide; only the render-dominated catch-up spike is common.

Recommendation: a pure A* route worker and a world-snapshot worker are NOT
justified (A* leads only the tiny default-path mod; world answers never lead).
Default-path peaks are GPU -> steps 1-2 (GPU/geometry) apply, a CPU worker
would not help. If targeting in-frame CPU, the unit is the whole Sim::step
(Wasmtime on its own thread), not a route worker — still not implemented.

Harness fix (engine gitlink 48eff0fcb): control-socket chat/chat-log now reach
the client mod on the server-thread path (chat-box parity), enabling the
required default-path battle measurement; sim rules untouched.

Tests: airdef-core 326 passed/0 failed/8 ignored; airdef-mod 113+1+2+5 passed
incl. same_seed_same_result and combat_trace_is_deterministic;
tools/test_raid_bench.py 11 passed; horizon-mods suite + wasm ABI test ok.

Engine: d073783f5 (spans + clock) + 48eff0fcb (chat harness) on
agent/126-cpu-profile. Parent: 92c058f60 (profiler + driver) + this commit.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 13:35:32 +03:00
chexit 92c058f606 Sim::step phase timing and the CPU-profile bench driver (#147 step 3.1)
Mod side: Sim::step times plan_step, adapt, step_drones, step_moves,
update_sight, step_sams and record, plus the whole step and its untimed
remainder, through sim::profile. The simulation stays SDK-independent (also
built as airdef-core): the adapter installs the host monotonic clock
(game.monotonic-nanos) in init, native tests use std::time::Instant. The
counters are fixed-size, per-thread, read no randomness and change no
decision; /airdef stats reports them as PROFILE chat lines, reset per world.

Driver: raid_bench gains --scheduler in-frame|server-thread (the two
single-player paths, measured separately), HORIZON_MOD_CPU_PROFILE=1, the
per-tick mod-path spans joined to the frame trace (per-frame totals, >25/33 ms
counts, what the worst CPU frames carry), and the mod phase profile read at
idle and battle end with the battle delta. report.json carries mod_cpu,
mod_cpu_ticks, mod_phases_* and the derived correlation. Tests for the new
helpers.

Engine gitlink: mod-path CPU spans + game.monotonic-nanos (API level 32).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 12:29:22 +03:00
chexit c08b737296 Reproducible raid/replay render bench and #147 instancing measurements
build / mod (push) Failing after 32s
tools/raid_bench.py (+ tests): the #147 step-0 driver replaces the #126
scratch script. One battle at fixed ticks (waves inside resident terrain —
far waves stall at the unknown-chunk edge and no fight happens), fingerprint
chat lines at control ticks, then the raid's own recording replayed. Both
render paths are benched on the SAME recording in ONE process via the
engine's diagnostic `model-instancing off|on` toggle (cross-process battles
diverge in event timing: 16 vs 32 kills at one control tick), pairs in
alternating order; idle cold/warm, mid-battle window, reload (F3+T), replay
seek, away-camera checks, and static off/on stills for pixel parity
(hd_bench motion-mask methodology). report.json carries gitlinks, device,
mod_models counters, CPU/GPU p50/p95/p99/max, raw frame times, >25/33 ms
frame counts, guest fuel and streaming queues.

Engine gitlink: one mass mod-model group GPU-instanced (retained mesh per
pack generation, current/previous pose/id/light instance stream shared by
main, motion and shadow passes, per-vertex fallback to parity, runtime
diagnostic toggle, stats raw + guest fuel reporting).

Measurements: docs/measurements/issue-147-instancing/ (M5/Metal, 2560x1440;
RTX 3060 pending). docs/REPO-MAP.md and docs/ENGINE.md pin updated.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 11:39:43 +03:00
chexit 32748b116c Smart v2 on top of #146: one public picture, mark prices, bounded refresh, bearing window (#149)
build / mod (push) Failing after 30s
Re-applied the genuinely new #149 features onto kimi-work, REUSING the already-integrated
#146 infrastructure (KnowledgeSnapshot { tick, contacts, marks }, knowledge_now(),
Plan.knowledge, RouteJob.known, versioned price_grid_known and restore). No #146 scaffolding
is duplicated: one snapshot per order, prices over known.tick, versioned restore are kept
exactly as they were. The only additive change to KnowledgeSnapshot is observations().

New #149 layer:
- observe::Observation + observe::merge: Contact and Mark become one public hint, matched by
  public features only (area overlap + exact category); coarse Unknown/contradicting marks stay
  separate, the contact's kind/fix are never rewritten, recon.truth and real ids are not used.
  One Observation::rank scale replaces the two ranks in radar_strikes, choose_target and the
  adaptive picks (kimi-work's slice signatures kept).
- price_grid_known prices marks: a trusted launcher/gun/jammer mark prices its published
  category envelope weighted by confidence (Confirmed x1, Probable x0.5); a radar mark feeds
  the network belief; a mark matched to a contact is priced once through the contact; a
  doubtful mark prices nothing.
- Bounded refresh of the unreleased portion: ew::Refresh with absolute deadline
  REFRESH_WINDOW=600; step_refresh re-aims queued Plan/Sead drones once on a report (typed
  Intent::Refresh, SEAD priority) within SWITCH_CAP and assignment budgets; no report never
  delays a launch.
- Bearing window: Intel.outcomes bounded VecDeque (48 entries, 12000-tick window); best_bearing
  adapts exploration share by typed BearingReason (few/stale/conditions-changed/exploiting);
  conditions are a fingerprint of the public picture, never hidden state. bearing_report() and
  bearing/refresh_*/observations fields in EnemyPictureReport. Legacy fixed share kept.
- examples/smart_bench runner (simple/current/candidate, seeds 1/7/42, open/hills/config-change/
  recon-lost, JSON+lines); Sim::smart_legacy reproduces current Smart; harness::run_with_hook.
  Light modes and bounded jobs unchanged; policy reads no health/charges/hidden switches/positions.

Tests: smart_tests + observe::tests (metamorphic hidden-layout, public dedup, marks in prices,
one version per order in both modes, bounded refresh fires-once/never-pauses, bearing window and
reasons, durable window + Intent::Refresh). The relief-version regression fixture's wall is
widened in z so it crosses any east-west route after the candidate's assignment-order change.
cargo test passes: airdef-core 326 lib + 8 scenarios; airdef-mod 113 lib + core_boundary + 5 scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 10:57:04 +03:00
chexit b796a439df Restore the saturated intercept count by uncueing the embedded radar (#145)
build / mod (push) Failing after 31s
The heavy WASM scenario (wasm_flat_budget, 64 integrated complexes vs two
`airdef wave oreshnik 40 2600`) lost intercepts at the tick-2102 checkpoint:
522 (main) -> 302 (#133) -> 243 (#134). Decomposed by A/B on one fixture, one
host (2bcce64), one SDK, each slice built from its own commit:

- 522 -> 302 (#133): Track.vel became an estimate from noisy measured places
  (it was the target's true velocity); the forecast, the aim lead and the
  interceptor's launch Fix all read it. Forcing the class estimate to Unknown
  leaves the count unchanged (native 296 ~= 294), so class/roles is not the
  cause. The pre-#133 522 used the target's true velocity, which the #133
  contract "class and speed only from measurements" forbids; this portion is
  the intentional cost of honest measurement-only tracks and is kept.

- 302 -> 243 (#134): the network cue was extended from the separate engagement
  radar to every fire-quality radar, including each weapon's embedded radar.
  Cueing every relayed contact each tick flooded the embedded fire control with
  one-tick plots whose noisy velocity degraded guidance. Restricting the cue
  back to separate radars recovers the whole drop: 243 -> 325.

- own_fire_within / FIRE_QUALITY / channels are NOT causes here: relaxing the
  own-fire gate or the channel limit each changed nothing (243 -> 243). Embedded
  radars always measure Fire plots of quality >= 64 and have no channel limit.

- #140 does not affect this loadout, by fact: the fixture deploys no separate
  radar, so every profile is embedded with channels = 0; the channel-age bug
  binds only where a profile has channels, and the channels-off A/B was flat.

Fix: the cue looks only through a separate fire-quality radar
(sam.kind == SamKind::Radar); the embedded radar keeps its beam/revisit/lock
acquisition as before #134. All radar profiles, channel limits, own-fire
authority and the measurement-only class/speed contract are preserved; no
target truth is injected.

Measured after the fix (WASM, fuel budget 300M/tick): checkpoint 325 intercepts
/ 2011 hits, fuel max 118M; final (tick 3302, two late Smart raids) 385 / 2472,
fuel max 176M; zero fuel failures. The first late raid reports the #135 recon
flight ("Разведка противника: впереди налёта высланы разведчики"); the second
is silent (recon budget spent) — the fixture now expects exactly that instead
of the stale empty chat that stopped the scenario.

Tests:
- airdef-mod/tests/saturation.rs: deterministic native replica of the checkpoint
  (same sim, host block tracer) asserting the restored count and a regression
  threshold, plus the #140 loadout fact (no separate radar, channels = 0).
- Sim::launch_audit (why.rs): on-demand tolerance diagnostic counting why each
  (system, drone) pair holds fire — no track / stale / no authority / role /
  doctrine / reach / claimed / not ready / not aimed / terrain / ready.
- sensor_tests: a network plot cues a separate fire radar but not the embedded one.
- wasm_flat_budget baselines re-measured with provenance comments; the asserted
  fixture SHA in tools/airdef.py updated.

Verification: `python3 tools/airdef.py test-budgets` passes both stages and the
two late raids (283 steps, fuel failures = 0). airdef-core 292 + 8, mod lib 104,
mod scenarios 5, saturation 2 — all green. A/B record:
docs/measurements/issue-145-intercept-regression.json.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>

Integration note (shipped engine 8e711f969): the tick-2102 checkpoint baseline is
unchanged and passes on the shipped engine (325 intercepts / 2011 hits). The final
stats baseline was re-measured on the shipped engine with #146 integrated (one
knowledge snapshot per Smart order changes the two late raids): 414 / 2463, world
8885 sections / 420671 rays / 3442845 cells. The asserted fixture SHA in
tools/airdef.py was updated to match. python3 tools/airdef.py test-budgets passes
all 283 steps with zero fuel failures (tick max 184608537 / 300000000).
2026-11-21 10:32:11 +03:00
chexit c76f620642 Point horizon at the TAAU motion-buffer jitter fix (#143)
build / mod (push) Failing after 28s
Engine a3045b61b: the motion buffer's coordinate contract is explicit and
decoded per history grid — native TAAU's stable history no longer receives
the two frames' jitter difference (a still surface reads the same output
pixel on every phase), 1:1 TAA keeps the correction its jittered history
needs, and the NGX input and flags are untouched for separate verification
on the DLSS path (#137). Numerical reprojection tests on all jitter phases
plus an ignored GPU A/B smoke on the real fs_taau.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 10:09:12 +03:00
chexit 63ebd4ac6c Plan one Smart order on one knowledge snapshot (#146)
build / mod (push) Failing after 25s
order_raid read one picture and one list of recon marks for the whole
order, but the Plan kept neither: plan_step priced each kind's first
route on whatever picture_of_defences() held at the tick the budget
reached that kind, so one raid could hold several versions of the map
at once. A retarget job carried its version's contacts, yet
price_grid_known aged them at self.tick, so two jobs of one version
reached on different ticks could disagree about a contact's own sensor.

KnowledgeSnapshot fixes the observation tick together with the contacts
and marks read at it. The plan stores the order's snapshot and passes it
explicitly to price_grid_on/price_grid_known; radar_strikes takes the
order's marks instead of re-reading the recon memory. A retarget job
shares its adaptive tick's snapshot and prices age at the snapshot's
tick, never at the current one: current time still cancels a stale job
(prune_air, job_live), separately from the version's own arithmetic, and
an explicitly new retarget gets a new snapshot and may use a fresh
report. The save rebuilds each version's snapshot from the contacts and
the marks reported by it; the section format is unchanged. Nothing here
reads the force: only published kinds and the contacts' own observations.

SDK-free regressions: a Smart order of two kinds whose land answers
starve while a visible contact is disclosed mid-wait keeps every kind's
targets and routes on the order's snapshot (and differs from an order
that knew the contact from the start); two jobs of one version worked
out across the emission-belief boundary price the same world, a new
version with a fresh report believes again, and a new version without
one does not.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:54:47 +03:00
chexit f2bc8550f5 Tie a radar's refine/fire channel to its own plot's freshness (#140)
build / mod (push) Failing after 28s
A station counted any own plot, however old, as a busy refine/fire
channel: a network heartbeat kept a stale contact's track fresh, so two
long-expired own fire plots still held both channels of the engagement
radar and a new contact nearby got only a coarse search plot, even with
the search radar running.

Channel occupancy now follows the station's own tracking.
Track::holds_channel requires an own (never relayed) refine/fire plot no
older than the station's track_ttl — three missed turns, the same value
that already bounds a contact without a fresh measurement. The planner
counts channels with the same Sam::own_channels_used(now) the panel,
monitor, map and "why" views read, so the UI and the allocation cannot
disagree about a stale channel. A stale channel frees for a new contact
without the network's survey track being removed; the hard per-profile
limit and the own measurement's provenance are unchanged, and a relayed
plot still never holds a channel.

Test: two contacts take both channels at the station, then leave its
reach while the search radar beside them keeps relaying them; a third
contact arrives nearby and gets its own fire channel (the test fails on
the old counting), and the relayed survey tracks of the old contacts
stay.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:53:43 +03:00
chexit 5f00a2a16b Read replay events by their time ranges, not the whole journal (#150)
The replay's sounds, the raid map's counts and the struck objects now read
the recording's event and scene journals by time instead of every pass over
the whole journal: partition points over the journals (with a stable time
index built at close only when a journal is out of order), the map's kill
and hit prefix indices, each object's first hit, and marker/time-line paths
that stop at the map's shape cap. Blasts, smoke, debris and the fire replay
read bounded windows back from the moment.

The sets, order and names stay exactly as they were: tests compare every
reader against the full journal filter, including tied times, out-of-order
journals and arbitrary forward and back seeks. The replay_bench example
measures a 10-minute raid with nearly full journals (playback, reverse seek,
pause, MP4); its result is docs/measurements/issue-150-replay-ranges.json.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:52:20 +03:00
chexit 7f52c40d99 Bump horizon to the DLSS command-order and history fix (#137)
build / mod (push) Failing after 21s
Engine 1cadd6338: the DLSS frame now submits world+linearize -> NGX ->
delinearize -> film/tonemap/UI/capture/present in one queue.submit with no
CPU sync, so the final frame, screenshot and export read the current
resolved frame instead of the previous one. Native TAA history readiness
is tracked separately from NGX, so the first fallback frame after DLSS
does not blend a stale or empty native history; a cut/resize clears both.

HD-RENDERER.md records the corrected order and the history separation.

Real-RTX acceptance (docs/DLSS-TESTING.md) is still pending: no RTX is
available here, so this is verified by the ordering/history unit tests and
the native horizon-client + horizon-mods suites, not a DLSS GPU capture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:45:20 +03:00
chexit 8afe691301 Add typed battle reasons and short engagement chains (#148)
build / mod (push) Failing after 32s
A battery's "why" now starts with one typed reason shared by the monitor,
the HUD and the chat: only observation, waiting for a track, busy channels,
no ammunition, or ready. It carries the age and the station of the mark it
is about, and `/airdef why <n> source` moves the monitor to that station.
The reason is computed from the same predicates the launch decision uses,
and the detailed decision settles it, so a headline cannot promise or deny
a shot the simulation does not take.

The after-action review builds 4-5 measured steps per contact from the
recording's scene journal and events: mark, handoff, lock, launch, outcome.
The menu lists them per battery with a filter and opens a replay frame on
a click (the outcome clip, else the map held at the launch or mark);
`/airdef chains [battery]` prints the same list. Missing transitions stay
missing and marked as no launch, never guessed, and the normal HUD still
shows only the battery's own picture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:42:10 +03:00
chexit bd2d8f4fed Release an unreachable optical contact and serve ready posts fairly (#138)
build / mod (push) Failing after 22s
An automatic optical contact is kept only within the optics' own reach and let go after a few failed probes. It stays out of the next picks for a while, so a visible alternative can be tried without constant switching; unknown world geometry gets a longer, still bounded wait. A player's command still waits for its contact and says so in the status line.

Ready posts are now served oldest-probe first through a simulation-wide probe sequence, so posts whose phases coincide all advance under the unchanged CHECKS_PER_TICK budget.

Tests: an out-of-range contact with a visible alternative, a blocked contact with a visible alternative, five same-phase posts, the bounded unknown-geometry wait, and the manual pin's status and out-of-reach behaviour.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:27:02 +03:00
chexit 41ab52e802 Keep replay transitions through the SAM pose decimation (#142)
build / mod (push) Failing after 36s
Sampling slowed by the pose budget skipped whole short stages: the six-tick
tube cover opening, the ejection and the radar switch fell between samples,
and thinning then halved already recorded transitions along with poses.

Poses still share the adaptive sam_step grid and the unchanged 32768-key
budget, but the recording is now sampled every tick for facts: a discrete
change (spent_cells, cap_cell, radar_on, mode, role) and every frame of the
cover's own movement are kept on the tick they happen, with the stage's start
backdated one tick so the opening still spans exactly OPEN_TICKS. These keys
carry an event mark and decimation halves poses only, keeping events, the
first and the last key.

Events get their own explicit 4096-key budget instead of raising the pose
budget: when it runs out the oldest stop being critical and thin as poses
while the newest stay exact.

Test: 64 turning radars plus an S-400 at sam_step 16, ejection on tick 4103
(cover 0.8333333 a tick before, spent cell on the ejection tick), a cancelled
opening and a radar switch off the pose grid, all surviving further thinning;
a 64-radar chattering recording stays exactly at the event budget with the
newest switch exact.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:23:41 +03:00
chexit 433e1500e2 Do not treat a cooling jammer as an active emitter (#139)
build / mod (push) Failing after 37s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:20:46 +03:00
chexit 01765027b1 Fix the recon picture's wrecks and its emission sources (#139)
build / mod (push) Failing after 29s
A look no longer reports a wreck as a lead: a first look at one makes no
mark, and one the picture already held is radioed home as destroyed and
takes its mark out of the picture. A hidden kill still never rewrites a
mark, so the old assessment stands until its age runs out.

The channel now follows actual work, not a switch: a radar emits only
while radar_up, a jammer only while its transmitter is on the air. A
silent, packed, failed or destroyed station is just a unit the flyby saw.

A pending wreck observation is durable; older saves without its flag read
as before, every look being of a unit alive when it was seen.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:12:35 +03:00
chexit 24b8cce11b Update the WASM contract for radars configured at deployment (#144)
build / mod (push) Failing after 1m21s
The real-.hmod scenario still expected the pre-#134 role switch to
retune radar 4 and return its role as feedback. After #134 the profile
is chosen at deployment and dispatch refuses the old syntax, so step 14
failed with no feedback.

Both stale checks now expect the intended refusal, naming
deploy radar_search|radar_track|radar_height and on/off. The deployed
station is not transformed back for the test.

Verified with python3 tools/airdef.py test-wasm on the pinned host
2bcce64236 and the real airdef.hmod: 30 steps pass.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 08:57:53 +03:00
chexit 502d94c528 Spend the world overlay's marker budget on targets in frame (#141)
The overlay clipped the network's tracks to the nearest 64 by distance
before projecting them, and the truth and interceptor layers the same way.
A crowd behind the camera filled the budget, so a raid could show nothing
even with a target right in front of the player; the native reproduction
(one contact ahead, 64 behind) came out with zero markers and a header
saying all 65 were out of frame.

Now visibility comes before the draw budget. Each layer orders its
candidates nearest first, projects at most MAX_SCAN = 4 x MAX_MARKERS of
them (bounded work, no sort of the whole picture beyond that prefix), skips
those the frame does not hold without spending a marker, and draws the
nearest MAX_MARKERS visible ones. Each layer keeps its own draw budget, so
the interceptors and the truth markers cannot crowd out the network's.

The header separates the two ways a target stays unmarked: "за кадром"
(behind the camera or past an edge) and "сверх бюджета" (past the scan or
draw budget), alongside "в кадре".

Regression tests: 64 behind plus one ahead for the network, truth and
interceptor layers; a mixed crowd proving the nearest visible keep the
markers and the farthest is budget-capped, not offscreen; the projection
count bounded by MAX_SCAN; every case stays inside the HUD's 1024 shapes.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 08:57:53 +03:00
135 changed files with 65341 additions and 1611 deletions
+19 -2
View File
@@ -1,6 +1,8 @@
# На каждый пуш: только мод (.hmod, один для всех ОС) и релиз build-<номер> с ним. # На каждый пуш: только мод (.hmod, один для всех ОС) и релиз build-<номер> с ним.
# Раннер живёт на одной машине с Gitea и другими сервисами (2 ядра, 4 ГБ): сборка мода лёгкая — # Раннер живёт на одной машине с Gitea и другими сервисами (2 ядра, 4 ГБ): сборка мода лёгкая —
# один поток компиляции, низший приоритет, без системных пакетов и без кэша target. # один поток компиляции, низший приоритет, без системных пакетов и без кэша target.
# Диск у раннера тоже общий с базой Gitea: 23.11.2026, дойдя до тестов, джоба уронила базу до конца прогона.
# Поэтому один закреплённый тулчейн вместо stable поверх него и без каталогов target тестов к моменту сборки мода.
# Игра-форк здесь не собирается: только по тегу версии (release.yml, Windows) и вручную (game.yml Linux, desktop.yml macOS). # Игра-форк здесь не собирается: только по тегу версии (release.yml, Windows) и вручную (game.yml Linux, desktop.yml macOS).
name: build name: build
@@ -22,9 +24,19 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
# Не начинать, когда места мало: иначе сборка займёт диск до конца, а база Gitea на нём падает.
- name: Ресурсы раннера
run: |
df -h / | tail -1
free -m | sed -n '1,2p'
FREE=$(df --output=avail -BM / | tail -1 | tr -dc 0-9)
if [ "$FREE" -lt 4000 ]; then echo "::error::на сервере свободно ${FREE} МБ, нужно хотя бы 4000"; exit 1; fi
# Только закреплённый тулчейн из rust-toolchain.toml: stable ставился раньше и лежал мёртвым грузом.
- name: Rust - name: Rust
run: | run: |
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --target wasm32-unknown-unknown CHANNEL=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)
if [ -z "$CHANNEL" ]; then echo "::error::rust-toolchain.toml: не прочитан channel"; exit 1; fi
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain "$CHANNEL" --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
# Без actions/cache: кэш-сервер раннера из контейнеров задач недоступен — восстановление # Без actions/cache: кэш-сервер раннера из контейнеров задач недоступен — восстановление
# падало по таймауту, а сохранение вешало «Complete job» на пару минут. Инструмент собирается заново. # падало по таймауту, а сохранение вешало «Complete job» на пару минут. Инструмент собирается заново.
@@ -32,23 +44,28 @@ jobs:
run: nice -n 19 python3 tools/airdef.py fork run: nice -n 19 python3 tools/airdef.py fork
- name: Проверка закреплённого checkout - name: Проверка закреплённого checkout
run: python3 -m unittest discover -s tools -p test_engine_checkout.py run: python3 -m unittest discover -s tools -p test_engine_checkout.py
# Системный Python образа — externally managed (PEP 668): без --break-system-packages pip отказывает,
# и тесты со сборкой ниже вообще не запускаются. Контейнер задачи одноразовый, так что --user безопасен.
- name: Проверка generated assets - name: Проверка generated assets
run: | run: |
python3 -m pip install --user -r tools/requirements.txt python3 -m pip install --user --break-system-packages -r tools/requirements.txt
python3 tools/gen_catalog.py --check python3 tools/gen_catalog.py --check
python3 -m unittest discover -s tools -p test_sound_catalog.py python3 -m unittest discover -s tools -p test_sound_catalog.py
python3 tools/gen_models.py --check python3 tools/gen_models.py --check
python3 -m unittest discover -s tools -p test_model_bounds.py python3 -m unittest discover -s tools -p test_model_bounds.py
# После тестов их каталог target не нужен (модуль собирается под wasm заново), а на диске его место.
- name: Тесты ядра без SDK - name: Тесты ядра без SDK
working-directory: airdef-core working-directory: airdef-core
run: | run: |
HOST=$(rustc -vV | sed -n 's/^host: //p') HOST=$(rustc -vV | sed -n 's/^host: //p')
nice -n 19 cargo test --target "$HOST" nice -n 19 cargo test --target "$HOST"
rm -rf target
- name: Тесты мода - name: Тесты мода
working-directory: airdef-mod working-directory: airdef-mod
run: | run: |
HOST=$(rustc -vV | sed -n 's/^host: //p') HOST=$(rustc -vV | sed -n 's/^host: //p')
nice -n 19 cargo test --target "$HOST" nice -n 19 cargo test --target "$HOST"
rm -rf target
- name: Мод - name: Мод
run: nice -n 19 python3 tools/airdef.py mod run: nice -n 19 python3 tools/airdef.py mod
- name: Релиз - name: Релиз
+86 -33
View File
@@ -60,27 +60,44 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
| Развернуть Patriot / Гепард / Панцирь-С1 / С-400 / С-500 | ставит комплекс на блок под прицелом, носом по взгляду | | Развернуть Patriot / Гепард / Панцирь-С1 / С-400 / С-500 | ставит комплекс на блок под прицелом, носом по взгляду |
| Свернуть ПВО | убирает ближайший комплекс у точки под прицелом | | Свернуть ПВО | убирает ближайший комплекс у точки под прицелом |
**Командный пункт:** клавиша **N** или `/airdef menu`. В нём список комплексов: выбери комплекс и включай или выключай классы целей **Меню AirDef:** клавиша **N** или `/airdef menu`. В разделе «Классы целей» можно включить или выключить
(дроны, реактивные дроны, крылатые, сверхзвуковые, баллистика), есть сброс по умолчанию. Там же кнопки «Командный классы для каждого типа комплекса и сбросить их по умолчанию. В меню также открываются командный пункт,
пункт» (сетка), «Налёт…» и «Огонь, ремонт, эффекты…» (огонь ПВО, ремонт всех, эффекты, разрушения). налёты, повторы и настройки.
**Налёт (меню N → «Налёт: состав и запуск…»):** на первой странице состав — клик по типу листает число **Налёт (меню N → «Налёт: состав и запуск…»):** на первой странице состав — клик по типу листает число
(0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40); на второй — готовый вариант («Рой Шахедов», «Массированный удар», (0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40); на второй — готовый вариант («Рой Шахедов», «Массированный удар»,
«Баллистика», «Гиперзвук», «Орешник с прикрытием», «Подавление ПВО»), откуда (один сектор, два, со всех сторон, «Баллистика», «Гиперзвук», «Орешник с прикрытием», «Подавление ПВО»), откуда (один сектор, два, со всех сторон,
волнами по типам), дальность старта, цели и **ПУСК**. Цели: волнами по типам), дальность старта, цели и **ПУСК**. Цели:
- *только объекты* — всё летит по отмеченным объектам (или по игроку, если их нет); - *только объекты* — всё летит по отмеченным объектам (или по игроку, если их нет);
- *объекты и ПВО* — треть ударных средств бьёт по случайным комплексам; - *объекты и ПВО* — часть ударных аппаратов бьёт по случайным комплексам. Баллистика летит по отмеченным объектам;
- *умный противник* — планировщик использует наблюдённые контакты и последние известные позиции комплексов: ведёт дроны и крылатые ракеты - *умный противник* — планировщик использует наблюдённые контакты и последние известные позиции комплексов: ведёт дроны и крылатые ракеты
маршрутами в обход зон поражения, низко, за рельефом и через мёртвые зоны; «Герберы» прилетают на 15 с раньше, маршрутами в обход зон поражения, низко, за рельефом и через мёртвые зоны; «Герберы» прилетают на 15 с раньше,
чтобы оттянуть ракеты; «Ланцеты» идут по Гепардам и Панцирям, Х-22/Циркон и часть баллистики — по дальнобойным чтобы оттянуть ракеты. На технику вместе с наблюдёнными РЛС выделяется до четверти большого налёта.
комплексам; на наблюдённые РЛС дальнего обнаружения выделяются 2–3 быстрых ударника (Х-22, Циркон, Искандер, Кинжал, затем Х-101, Баллистика и остальная ударная группа идут по отмеченным объектам. В режиме волн группы прибывают с интервалами.
Герань-3, Ланцет, Шахед; не больше четверти налёта); всё остальное стартует со сдвигом так, чтобы прилететь одновременно.
После налёта приходит отчёт: сколько сбито и прорвалось, ракет ПВО потрачено, комплексов потеряно, урон объектам. После налёта приходит отчёт: сколько сбито и прорвалось, ракет ПВО потрачено, комплексов потеряно, урон объектам.
**Оборона деревни** доступна из меню N или через `/airdef scenario village normal`
(`easy` и `hard` меняют бюджет и состав волн). Встаньте в деревне и выберите сложность.
Если целей ещё нет, мод отметит три точки по высотам местности рядом с игроком.
Можно заранее отметить ровно три целых объекта самостоятельно. По порядку отметок это штаб, лазарет и укрытие.
Расставьте технику и выберите «Начать оборону» или `/airdef scenario village start`.
Стоимость техники показывает `/airdef scenario village prices`. Через пять секунд начинается первая из трёх волн.
В паузах по 30 секунд можно тратить остаток бюджета. Боезапас, урон и запас складов сохраняются между волнами.
Для победы нужны уцелевший штаб и минимум 65 баллов. Целые объекты дают 50, 30 и 20 баллов соответственно,
повреждённые дают долю от этих значений. При потере всех трёх объектов сценарий заканчивается досрочно.
Сценарий можно остановить командой `/airdef scenario village stop`.
Она оставляет расстановку и уже начатый налёт в мире.
**Разбор прорывов** доступен из меню деревни, из меню повторов или командой `/airdef breaches [страница]`.
В истории текущего сеанса остаются последние 128 попаданий. Видны время первого замера РЛС, число запущенных
перехватчиков и состояние ближайших комплексов в момент перед ударом. После перезахода часть данных по
уже летящим аппаратам может быть неизвестна.
**Обнаружение.** РЛС видит цель не дальше, чем позволяют: **Обнаружение.** РЛС видит цель не дальше, чем позволяют:
- её размер: дальность растёт как корень четвёртой степени из ЭПР — Х-101 и Ланцет видно примерно вдвое ближе, чем Х-22; - её размер: дальность растёт как корень четвёртой степени из ЭПР — Х-101 и Ланцет видно примерно вдвое ближе, чем Х-22;
- радиогоризонт: низколетящую цель видно поздно (Шахед на 25 м — с ~250 м, баллистику — издалека); - радиогоризонт: низколетящие цели обнаруживаются ближе, чем цели на большой высоте;
- рельеф и лес: за холмом цель не видна (каждый комплекс строит свой горизонт по 48 лучам; рельеф известен в - рельеф и лес: за холмом цель не видна (каждый комплекс строит свой горизонт по 48 лучам; рельеф известен в
прогруженных чанках); прогруженных чанках);
- вблизи (24 м) видно всё. - вблизи (24 м) видно всё.
@@ -96,7 +113,7 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
**Сеть ПВО.** Единицы обмениваются измеренными треками в пределах игровой связи; повреждение связи **Сеть ПВО.** Единицы обмениваются измеренными треками в пределах игровой связи; повреждение связи
сокращает её дальность. Можно поставить несколько С-400/С-500 без собственной РЛС и общие радары сокращает её дальность. Можно поставить несколько С-400/С-500 без собственной РЛС и общие радары
поиска, сопровождения и мачтового обзора: N → «Разместить элементы батареи…». поиска, сопровождения и мачтового обзора — отдельными пультами (`/airdef give` выдаёт `deploy_radar_search`, `deploy_radar_track`, `deploy_radar_height`) или командой `/airdef deploy radar_search|radar_track|radar_height`.
Поисковый радар даёт подсказку; огневой должен сам измерить цель, прежде чем разрешить пуск. Поисковый радар даёт подсказку; огневой должен сам измерить цель, прежде чем разрешить пуск.
Старая сборная конфигурация сохранена. [Команды, источники и ограничения](docs/BATTERIES-AND-COLD-LAUNCH.md). Старая сборная конфигурация сохранена. [Команды, источники и ограничения](docs/BATTERIES-AND-COLD-LAUNCH.md).
P1-SUN также использует чужие данные. Пушкам (Гепард, P1-SUN также использует чужие данные. Пушкам (Гепард,
@@ -107,10 +124,13 @@ P1-SUN также использует чужие данные. Пушкам (Г
не заменяет обязательное собственное сопровождение. Выключение не стирает старые сведения противника: не заменяет обязательное собственное сопровождение. Выключение не стирает старые сведения противника:
он продолжает использовать последнюю наблюдённую позицию, а пуски и РЭБ могут снова раскрыть технику. он продолжает использовать последнюю наблюдённую позицию, а пуски и РЭБ могут снова раскрыть технику.
**Логистика.** Пока нет ни одного склада, магазины пополняются сами, как раньше. Как только поставлен склад, **Логистика.** Боекомплект конечный с момента размещения техники. Комплекс с пустым боекомплектом показывает
боекомплект считается: комплекс без ракет пишет «ЖДЁТ БК»; в 60 м от склада он перезаряжается прямо с него, а «ЖДЁТ БК». В 60 блоках от склада он перезаряжается прямо с него, а
дальние обслуживают **ТЗМ**: заправляются на складе (2 перезарядки), сами едут к ждущим комплексам, ближайшим дальние обслуживают **ТЗМ**: заправляются на складе (2 перезарядки), сами едут к ждущим комплексам, ближайшим
первым, и возвращаются. Запас склада — 30 перезарядок, он виден в сводке. Склад и ТЗМ детонируют всем грузом. первым, и возвращаются. ТЗМ ищет проезд с любой стороны получателя. Если объезда нет, машина может
уложить короткий мост или пандус из булыжника и расчистить до двух слоёв мягкого грунта. Строительство
требует разрешения на команды изменения мира. Запас склада — 30 перезарядок, он виден в сводке.
Склад и ТЗМ детонируют всем грузом.
Ударная **RM48U у С-400** — отдельный условный игровой боеприпас, который делит четыре ячейки Ударная **RM48U у С-400** — отдельный условный игровой боеприпас, который делит четыре ячейки
с ракетами ПВО. `/airdef ground-stock <склад> <количество>` задаёт конечный начальный запас с ракетами ПВО. `/airdef ground-stock <склад> <количество>` задаёт конечный начальный запас
@@ -135,8 +155,9 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
**Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий **Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий
налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта
перенацеливает ещё не взлетевшие Ланцеты и Шахеды на них; если цель-комплекс уничтожен, дроны идут к может перенацелить часть ещё не взлетевших аппаратов. Удары по технике занимают до четверти большого
следующему известному. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках: налёта. Баллистика на всех этапах сохраняет отмеченный объект. Если цель-комплекс уничтожена, выделенные
на удар по технике аппараты могут выбрать другой известный комплекс. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без
маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле. маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле.
@@ -158,7 +179,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
Это относится к ракетам ПВО, RM48U, крылатым, сверхзвуковым и баллистическим средствам; Это относится к ракетам ПВО, RM48U, крылатым, сверхзвуковым и баллистическим средствам;
дым пожаров и слабая дымка винтовых дронов остались прежними. дым пожаров и слабая дымка винтовых дронов остались прежними.
**Сетка J** после сбития ещё 3,5 с держит камеру на сбитой цели, и комплекс в это время не пропадает из сетки. **Сетка камер** после сбития ещё 3,5 с держит камеру на сбитой цели, и комплекс в это время не пропадает из сетки.
**Повреждения.** Взрыв рядом с комплексом повреждает его: он хуже поворачивается, хуже видит и попадает, **Повреждения.** Взрыв рядом с комплексом повреждает его: он хуже поворачивается, хуже видит и попадает,
дымит, ниже 35% горит. Уничтоженный остаётся горящим остовом, его боекомплект детонирует: чем больше ракет дымит, ниже 35% горит. Уничтоженный остаётся горящим остовом, его боекомплект детонирует: чем больше ракет
@@ -177,10 +198,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- камера комплекса: настоящий вид мира из точки комплекса (второй рендер форка), с зумом на цель — тепловизор - камера комплекса: настоящий вид мира из точки комплекса (второй рендер форка), с зумом на цель — тепловизор
при сопровождении, в поиске днём цвет, ночью ПНВ; рамка захвата, дальность, высота, скорость и пеленг. при сопровождении, в поиске днём цвет, ночью ПНВ; рамка захвата, дальность, высота, скорость и пеленг.
**Командный пункт ПВО (сетка):** клавиша **J** (или `/airdef grid`, или кнопка в меню N) — на весь экран сетка **Командный пункт ПВО:** клавиша **J** или строка «Командный пункт» в меню **N** открывает прокручиваемый список
до 8 комплексов: у каждого состояние, РЛС, живая камера, прочность и боекомплект. Если комплексов больше, показываются всей развёрнутой техники. Кнопка фильтра перебирает роли и состояния. Для поиска по названию или номеру используйте
самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда. `/airdef post Панцирь` или `/airdef post 12`. Нажатие на строку открывает карточку. В ней видны текущая причина,
Повторное J закрывает. отметка и её источник. Из карточки можно открыть карту, камеру, историю решений и закрепить технику.
История показывает отказы на проверке, фактические выстрелы и известные исходы с отметкой, которая была у комплекса
на тот момент. По записи завершившегося налёта можно открыть соответствующий кадр повтора.
История живёт вместе с повторами текущей игровой сессии. В ней доступны последние 128 записей выбранного комплекса.
Та же карточка доступна с выбранного маркера на карте **M** и по **I** при открытом мониторе **K**.
В мире от первого лица наведите прицел на видимую часть техники на расстоянии до 24 блоков и нажмите **I**.
Если между прицелом и моделью есть блок, карточка по наведению не откроется.
**Веб-пульт для планшета:** живая карта, карточки техники, архив налётов и запуск сценариев с отдельным доступом
оператора. Запуск на ПК командой `python3 tools/airdef.py web`. [Подключение планшета и режимы доступа](docs/WEB-PANEL.md).
**Сетка камер** открывается отдельной кнопкой в списке или командой `/airdef grid`. В ней до восьми живых
камер со статусом, РЛС, прочностью и боекомплектом. Камеры подбираются по активности каждые две секунды.
Закреплённый комплекс получает приоритет, а при отсутствии закрепления приоритет у выбранного на мониторе K.
**Тактическая карта:** клавиша **M** открывает общую карту. Цели обозначены крупными отметками с классом, **Тактическая карта:** клавиша **M** открывает общую карту. Цели обозначены крупными отметками с классом,
курсом и измеренной траекторией; наведение мыши показывает дистанцию, тип, состояние трека и перехват. курсом и измеренной траекторией; наведение мыши показывает дистанцию, тип, состояние трека и перехват.
@@ -193,8 +227,10 @@ API мода `render.set-lights` (до 512, плавно интерполиру
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`, клавишу — метки исчезли. Метки достаются ближайшим из видимых целей: цель за камерой или за краем
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется. экрана бюджет кадра не тратит, а заголовок показывает, сколько целей в кадре, сколько за кадром и сколько
не поместилось в бюджет. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки камер, монитора K и карты M обзор не рисуется.
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто **Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
(хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**: (хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**:
@@ -204,7 +240,12 @@ API 31 форка) и следуют за взглядом покадрово;
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется; целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость; - **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения - **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты. объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты;
- **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка
«отметка → передача → захват → пуск → исход» с записанными шагами и их временем. Можно отобрать
цепочки по комплексу, прорывы и контакты без записи пуска. В длинном списке можно листать страницы.
Нажатие на строку открывает клип исхода или карту налёта на моменте пуска или отметки.
Текстовый список открывается командой `/airdef chains [номер батареи]`.
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент), показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
@@ -214,7 +255,7 @@ API 31 форка) и следуют за взглядом покадрово;
Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт
(48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт». (48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт».
Клавиши N, K, J, R, U и C (обзор целей, удержание) можно переназначить в «Настройки → Моды». Клавиши N, K, J, I, R, U и C (обзор целей, удержание) можно переназначить в «Настройки → Моды».
Команды: Команды:
- `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Дальность старта — от 60 до 4000 блоков (в меню: 200–4000); землю для площадок, которой нет в загруженных чанках, игра подгружает сама (API 22, `render.load-chunks`, пока идёт поиск), а где подгрузить нельзя (сервер) или нет пригодного места, дроны всё равно стартуют: «за картой», с высоты полёта на заказанной дальности, без площадки. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»); - `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Дальность старта — от 60 до 4000 блоков (в меню: 200–4000); землю для площадок, которой нет в загруженных чанках, игра подгружает сама (API 22, `render.load-chunks`, пока идёт поиск), а где подгрузить нельзя (сервер) или нет пригодного места, дроны всё равно стартуют: «за картой», с высоты полёта на заказанной дальности, без площадки. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»);
@@ -227,9 +268,21 @@ API 31 форка) и следуют за взглядом покадрово;
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность. - `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности. - `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
- `/airdef ground-stock <номер склада> <количество>` — задать остаток RM48U для sandbox-сценария (по умолчанию 0). `/airdef ground-load <номер С-400>` загружает одну ракету у склада либо заказывает ТЗМ; `ground-unload` возвращает её у склада либо заказывает вывоз; `ground-cancel` отменяет ожидающую заявку. Доставка и обратный вывоз через ТЗМ реализованы, запас и груз сохраняются. [Пошаговый пример](docs/GROUND-STRIKES.md). Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft. - `/airdef ground-stock <номер склада> <количество>` — задать остаток RM48U для sandbox-сценария (по умолчанию 0). `/airdef ground-load <номер С-400>` загружает одну ракету у склада либо заказывает ТЗМ; `ground-unload` возвращает её у склада либо заказывает вывоз; `ground-cancel` отменяет ожидающую заявку. Доставка и обратный вывоз через ТЗМ реализованы, запас и груз сохраняются. [Пошаговый пример](docs/GROUND-STRIKES.md). Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md). - `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также выдаются отдельными пультами (`/airdef give`) и ставятся на блок как обычные пульты. `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`; - `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48). - `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
- `/airdef why <номер>` — почему комплекс стреляет или нет. Сразу под строкой состояния — одна typed-причина:
«есть только обзор», «ждёт сопровождения», «каналы заняты», «нет боезапаса» или «готов к пуску», вместе с возрастом и
источником отметки (своя РЛС или сеть, РЛС №N). «Есть только обзор» — на картине лишь поисковая или
сетевая отметка, своё подтверждённое измерение пуск не разрешает; «ждёт сопровождения» — своя РЛС ещё
уточняет контакт или пусковая ждёт огневой трек поддерживающей РЛС; «каналы заняты» — все каналы
сопровождения заняты другими контактами; «нет боезапаса» — нет ракет и снарядов или идёт перезарядка.
`/airdef why <номер> source` переводит монитор K на станцию, которая поставила отметку. Подробные
проверки (роли, доктрина, дальность, наведение) идут ниже и не расходятся с этой причиной. В обычном
HUD — только картина самой батареи: класс по оценке, без истинного типа и скрытых данных.
- `/airdef chains [номер батареи]` — короткие цепочки последнего налёта: «отметка → передача → захват →
пуск → исход» с временем шагов; без номера — все батареи. Строка кликабельна в меню N → «Повторы…» →
«Цепочки боя» и открывает кадр повтора.
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой; - `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
- `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов; - `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов;
- `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы); - `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы);
@@ -279,19 +332,19 @@ HUD не выводится. Простые пресеты налёта фазу
| ПВО | Вооружение | Дальность | | ПВО | Вооружение | Дальность |
|---|---|---| |---|---|---|
| Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–450 | | Patriot | 4 × PAC-3, пусковая разворачивается на цель | 10–950 |
| Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 135 (слежение с 195) | | Гепард | 2 × 35 мм, башня и стволы со слежением и упреждением, 160 очередей | 180 (слежение с 260) |
| Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–225, пушки 90 | | Панцирь-С1 | 12 × 57Э6 и 2 × 30 мм; модуль поворачивается, пакеты и стволы поднимаются | ракеты 25–330, пушки 125 |
| С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–720 | | С-400 | 4 × 48Н6, вертикальный холодный старт, РЛС обзора на прицепе | 30–1300 |
| С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1050 | | С-500 | 2 × 77Н6, холодный старт, самые быстрые ракеты | 40–1850 |
| IRIS-T SLM | 8 ракет, вертикальный пуск, быстрые и манёвренные | 15–600 | | IRIS-T SLM | 8 ракет, вертикальный пуск, быстрые и манёвренные | 15–600 |
| NASAMS | 6 × AMRAAM, наводимая пусковая на прицепе | 10–450 | | NASAMS | 6 × AMRAAM, наводимая пусковая на прицепе | 10–450 |
| Бук-М2 | 4 × 9М317 на направляющих, башня с РЛС подсвета | 20–675 | | Бук-М2 | 4 × 9М317 на направляющих, башня с РЛС подсвета | 20–675 |
| Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–240 | | Тор-М2 | 8 × 9М338 вертикально из башни, быстрая реакция против дронов | 8–350 |
| P1-SUN | 8 дронов-перехватчиков против Шахедов и Герань; своей РЛС нет — стреляет по данным сети | 5–675 | | P1-SUN | 8 дронов-перехватчиков против Шахедов и Герань; своей РЛС нет — стреляет по данным сети | 5–675 |
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`, Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`), базовая дальность обзора 3800 блоков до поправок на класс цели, высоту и рельеф), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс **станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека, контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`. свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
@@ -311,8 +364,8 @@ HUD не выводится. Простые пресеты налёта фазу
нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю. нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю.
**Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей **Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 10 с и на ней ещё нет (С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 6 с, на ней ещё нет
ничьего перехватчика. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс». ничьего перехватчика и готовый комплекс меньшей дальности не успевает её обстрелять. Комплексу с пустыми ролями (огонь запрещён) это не касается. `/airdef why` пишет «последний шанс».
**Дальний пуск по РЛС.** С-400, С-500 и Patriot могут стрелять дальше своей дальности (до 1,6×) по цели, которую держит **Дальний пуск по РЛС.** С-400, С-500 и Patriot могут стрелять дальше своей дальности (до 1,6×) по цели, которую держит
свежим треком РЛС дальнего обнаружения в радиусе связи: не чаще раза в 15 с, при не менее чем половине боезапаса, только по свежим треком РЛС дальнего обнаружения в радиусе связи: не чаще раза в 15 с, при не менее чем половине боезапаса, только по
+2
View File
@@ -9,5 +9,7 @@ glam = "0.30"
[features] [features]
test-fixtures = [] test-fixtures = []
# Counts the events the by-time journal readers hand out (the `replay_bench` example).
bench-counters = []
[workspace] [workspace]
+197
View File
@@ -2,13 +2,22 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "airdef" name = "airdef"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"airdef-core", "airdef-core",
"glam", "glam",
"horizon-assets",
"horizon-mod-sdk", "horizon-mod-sdk",
"horizon-mods",
"serde_json",
] ]
[[package]] [[package]]
@@ -24,18 +33,75 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.13.2" version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.3" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.2.0" version = "0.2.0"
@@ -63,6 +129,22 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "horizon-assets"
version = "0.1.0"
dependencies = [
"horizon-core",
"serde",
"serde_json",
]
[[package]]
name = "horizon-core"
version = "0.1.0"
dependencies = [
"libm",
]
[[package]] [[package]]
name = "horizon-mod-sdk" name = "horizon-mod-sdk"
version = "0.1.0" version = "0.1.0"
@@ -70,6 +152,17 @@ dependencies = [
"wit-bindgen", "wit-bindgen",
] ]
[[package]]
name = "horizon-mods"
version = "0.1.0"
dependencies = [
"log",
"serde",
"serde_json",
"toml",
"zip",
]
[[package]] [[package]]
name = "id-arena" name = "id-arena"
version = "2.3.0" version = "2.3.0"
@@ -100,6 +193,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.34" version = "0.4.34"
@@ -112,6 +211,16 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]] [[package]]
name = "prettyplease" name = "prettyplease"
version = "0.2.37" version = "0.2.37"
@@ -153,6 +262,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [ dependencies = [
"serde_core", "serde_core",
"serde_derive",
] ]
[[package]] [[package]]
@@ -188,6 +298,21 @@ dependencies = [
"zmij", "zmij",
] ]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.119" version = "2.0.119"
@@ -210,6 +335,45 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "toml"
version = "1.2.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.27" version = "1.0.27"
@@ -250,6 +414,12 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]] [[package]]
name = "wit-bindgen" name = "wit-bindgen"
version = "0.60.0" version = "0.60.0"
@@ -339,8 +509,35 @@ dependencies = [
"wasmparser", "wasmparser",
] ]
[[package]]
name = "zip"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.23" version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
+11
View File
@@ -8,13 +8,24 @@ description = "AirDef: long-range drones and air defence for the AirDef fork of
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[features]
# Counts the events the by-time readers hand out (the `replay_bench` example); off in the mod build.
bench-counters = ["airdef-core/bench-counters"]
[dependencies] [dependencies]
airdef-core = { path = "../airdef-core" } airdef-core = { path = "../airdef-core" }
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" } horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
glam = "0.30" glam = "0.30"
serde_json = "1"
[build-dependencies]
horizon-assets = { path = "../horizon/crates/horizon-assets" }
[dev-dependencies] [dev-dependencies]
airdef-core = { path = "../airdef-core", features = ["test-fixtures"] } airdef-core = { path = "../airdef-core", features = ["test-fixtures"] }
# The host's own block tracer, so the saturation replica answers render rays exactly as the
# WASM test host does (no runtime: just `world_query`).
horizon-mods = { path = "../horizon/crates/horizon-mods", default-features = false }
[profile.release] [profile.release]
opt-level = "s" opt-level = "s"
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_height"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_search"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_radar_track"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_s400_launcher"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_s500_launcher"
}
}
+13 -8
View File
@@ -98,13 +98,16 @@
"block.airdef.searchlight_burnt": "Прожектор (остов)", "block.airdef.searchlight_burnt": "Прожектор (остов)",
"block.airdef.searchlight_head_burnt": "Голова прожектора (остов)", "block.airdef.searchlight_head_burnt": "Голова прожектора (остов)",
"item.airdef.designator": "Целеуказатель", "item.airdef.designator": "Целеуказатель",
"item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)",
"item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)",
"item.airdef.deploy_radar_search": "Развернуть РЛС обзора",
"item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения",
"item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
"item.airdef.launch_shahed": "Пуск: Шахед-136", "item.airdef.launch_shahed": "Пуск: Шахед-136",
"item.airdef.launch_geran3": "Пуск: Герань-3", "item.airdef.launch_geran3": "Пуск: Герань-3",
"item.airdef.deploy_patriot": "Развернуть Patriot",
"item.airdef.deploy_gepard": "Развернуть Гепард",
"item.airdef.deploy_pantsir": "Развернуть Панцирь-С1",
"item.airdef.deploy_s400": "Развернуть С-400",
"item.airdef.deploy_s500": "Развернуть С-500",
"item.airdef.launch_lancet": "Пуск: Ланцет-3", "item.airdef.launch_lancet": "Пуск: Ланцет-3",
"item.airdef.launch_kh101": "Пуск: Х-101", "item.airdef.launch_kh101": "Пуск: Х-101",
"item.airdef.launch_kalibr": "Пуск: Калибр", "item.airdef.launch_kalibr": "Пуск: Калибр",
@@ -113,6 +116,11 @@
"item.airdef.launch_iskander": "Пуск: Искандер-М", "item.airdef.launch_iskander": "Пуск: Искандер-М",
"item.airdef.launch_kinzhal": "Пуск: Кинжал", "item.airdef.launch_kinzhal": "Пуск: Кинжал",
"item.airdef.launch_oreshnik": "Пуск: Орешник", "item.airdef.launch_oreshnik": "Пуск: Орешник",
"item.airdef.deploy_patriot": "Развернуть Patriot",
"item.airdef.deploy_gepard": "Развернуть Гепард",
"item.airdef.deploy_pantsir": "Развернуть Панцирь-С1",
"item.airdef.deploy_s400": "Развернуть С-400",
"item.airdef.deploy_s500": "Развернуть С-500",
"item.airdef.deploy_irist": "Развернуть IRIS-T SLM", "item.airdef.deploy_irist": "Развернуть IRIS-T SLM",
"item.airdef.deploy_nasams": "Развернуть NASAMS", "item.airdef.deploy_nasams": "Развернуть NASAMS",
"item.airdef.deploy_buk": "Развернуть Бук-М2", "item.airdef.deploy_buk": "Развернуть Бук-М2",
@@ -124,9 +132,6 @@
"item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор", "item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост", "item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
"item.airdef.cam_shahed": "Шахед-136", "item.airdef.cam_shahed": "Шахед-136",
"item.airdef.cam_geran3": "Герань-3", "item.airdef.cam_geran3": "Герань-3",
"item.airdef.cam_lancet": "Ланцет-3", "item.airdef.cam_lancet": "Ланцет-3",
+13 -8
View File
@@ -98,13 +98,16 @@
"block.airdef.searchlight_burnt": "Прожектор (остов)", "block.airdef.searchlight_burnt": "Прожектор (остов)",
"block.airdef.searchlight_head_burnt": "Голова прожектора (остов)", "block.airdef.searchlight_head_burnt": "Голова прожектора (остов)",
"item.airdef.designator": "Целеуказатель", "item.airdef.designator": "Целеуказатель",
"item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)",
"item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)",
"item.airdef.deploy_radar_search": "Развернуть РЛС обзора",
"item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения",
"item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
"item.airdef.launch_shahed": "Пуск: Шахед-136", "item.airdef.launch_shahed": "Пуск: Шахед-136",
"item.airdef.launch_geran3": "Пуск: Герань-3", "item.airdef.launch_geran3": "Пуск: Герань-3",
"item.airdef.deploy_patriot": "Развернуть Patriot",
"item.airdef.deploy_gepard": "Развернуть Гепард",
"item.airdef.deploy_pantsir": "Развернуть Панцирь-С1",
"item.airdef.deploy_s400": "Развернуть С-400",
"item.airdef.deploy_s500": "Развернуть С-500",
"item.airdef.launch_lancet": "Пуск: Ланцет-3", "item.airdef.launch_lancet": "Пуск: Ланцет-3",
"item.airdef.launch_kh101": "Пуск: Х-101", "item.airdef.launch_kh101": "Пуск: Х-101",
"item.airdef.launch_kalibr": "Пуск: Калибр", "item.airdef.launch_kalibr": "Пуск: Калибр",
@@ -113,6 +116,11 @@
"item.airdef.launch_iskander": "Пуск: Искандер-М", "item.airdef.launch_iskander": "Пуск: Искандер-М",
"item.airdef.launch_kinzhal": "Пуск: Кинжал", "item.airdef.launch_kinzhal": "Пуск: Кинжал",
"item.airdef.launch_oreshnik": "Пуск: Орешник", "item.airdef.launch_oreshnik": "Пуск: Орешник",
"item.airdef.deploy_patriot": "Развернуть Patriot",
"item.airdef.deploy_gepard": "Развернуть Гепард",
"item.airdef.deploy_pantsir": "Развернуть Панцирь-С1",
"item.airdef.deploy_s400": "Развернуть С-400",
"item.airdef.deploy_s500": "Развернуть С-500",
"item.airdef.deploy_irist": "Развернуть IRIS-T SLM", "item.airdef.deploy_irist": "Развернуть IRIS-T SLM",
"item.airdef.deploy_nasams": "Развернуть NASAMS", "item.airdef.deploy_nasams": "Развернуть NASAMS",
"item.airdef.deploy_buk": "Развернуть Бук-М2", "item.airdef.deploy_buk": "Развернуть Бук-М2",
@@ -124,9 +132,6 @@
"item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор", "item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост", "item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
"item.airdef.cam_shahed": "Шахед-136", "item.airdef.cam_shahed": "Шахед-136",
"item.airdef.cam_geran3": "Герань-3", "item.airdef.cam_geran3": "Герань-3",
"item.airdef.cam_lancet": "Ланцет-3", "item.airdef.cam_lancet": "Ланцет-3",
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_s400"
}
}
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_s500"
}
}
+65
View File
@@ -0,0 +1,65 @@
use horizon_assets::{
bake::{BlockModelTransform, bake_block_model},
model::CuboidModel,
resolve::ModelLibrary,
};
use std::{collections::BTreeMap, env, fmt::Write, fs, path::PathBuf};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let models = PathBuf::from("assets/airdef/models/block");
println!("cargo:rerun-if-changed={}", models.display());
let output = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo sets OUT_DIR"));
let mut decoded = BTreeMap::new();
for entry in fs::read_dir(models)? {
let path = entry?.path();
if path.extension().is_some_and(|ext| ext == "json") {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.expect("UTF-8 model name");
let model = CuboidModel::from_json(&fs::read_to_string(&path)?)
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
decoded.insert(format!("airdef:block/{name}"), model);
}
}
// Use the same cuboid baker as the client so element rotations, omitted faces and
// model coordinates match. Include only positions, with offsets for the local AABBs.
let names: Vec<_> = decoded.keys().cloned().collect();
let library = ModelLibrary::new(decoded)?;
let transform = BlockModelTransform::new([0; 3], false);
let mut bytes = Vec::new();
let mut table = String::from("&[\n");
for name in names {
let model = library.resolve(&name)?;
let faces = bake_block_model(&model, transform)?;
if faces.is_empty() {
continue;
}
let start = bytes.len();
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for face in faces {
for position in face.positions {
for (i, coordinate) in position.into_iter().enumerate() {
let centred = coordinate - 0.5;
min[i] = min[i].min(centred);
max[i] = max[i].max(centred);
bytes.extend_from_slice(&centred.to_le_bytes());
}
}
}
let id = name.replace(":block/", ":");
let extent = std::array::from_fn::<_, 3, _>(|i| min[i].abs().max(max[i].abs()));
let radius = extent.iter().map(|value| value * value).sum::<f32>().sqrt();
writeln!(
table,
" ({id:?}, Mesh {{ min: {min:?}, max: {max:?}, radius: {radius:?}, start: {start}, end: {} }}),",
bytes.len()
)?;
}
table.push_str("]\n");
fs::write(output.join("inspect-meshes.rs"), table)?;
fs::write(output.join("inspect-faces.bin"), bytes)?;
Ok(())
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
+261
View File
@@ -0,0 +1,261 @@
//! Replay hot-path benchmark (#150): a 10-minute raid with its journals almost full.
//!
//! Plays the recording the ways a player does — ordinary playback, reverse seeks, a pause and
//! an MP4 export (the director's film) — and reports the CPU per frame (p50/p95/p99) and the
//! events the by-time readers handed out. Run it with the counters built in:
//!
//! cargo run --release --example replay_bench --features bench-counters
//!
//! Without `bench-counters` the scanned-events numbers read 0. Native timings compare runs on
//! one machine; they say nothing about the WASM build or the GPU.
use airdef::film::{Film, Which};
use airdef::replay::{Control, Mode, Player};
use airdef::sim::record::{Event, EventKind, Recording, SceneEvent, SceneJournal, SceneKind, StrikeResult, What};
use airdef::sim::{DroneKind, Ground, MissileKind, Out, SamKind, Sim};
use glam::DVec3;
use std::time::{Duration, Instant};
/// The longest recording, ticks (10 minutes at 20 a second).
const TICKS: u32 = 12_000;
/// The event journal's cap, and the scene journal's (`MAX_SCENE_EVENTS`), nearly reached.
const EVENTS: usize = 64_000;
const SCENE: usize = 65_000;
/// Frames measured per mode (20 a second, half a minute of playback; a film frame is 0.05 s).
const FRAMES: usize = 600;
const LISTENER: DVec3 = DVec3::new(0.0, 70.0, 0.0);
/// A 10-minute raid's recording: 200 flights, a nearly full event journal and scene journal,
/// the objects, systems, tracks and the fires — the journal a busy raid leaves.
fn recording() -> Recording {
let mut rec = Recording::blank(TICKS);
rec.number = 1;
rec.len = TICKS;
rec.origin = DVec3::ZERO;
rec.sams = (0..8).map(|i| (10 + i, SamKind::S400, DVec3::new(i as f64 * 120.0, 64.0, 400.0))).collect();
rec.objects = (0..8).map(|i| DVec3::new(i as f64 * 90.0, 70.0, 0.0)).collect();
// 200 flights, each a few hundred ticks of the raid (a point every 2 ticks): the map and
// the ghosts draw them, the sounds read their launches.
for k in 0..200u32 {
let first = k * 55 % (TICKS - 700);
let last = first + 600;
let what = match k % 4 {
0 => What::Drone(DroneKind::Geran3),
1 => What::Drone(DroneKind::Shahed),
2 => What::Missile(MissileKind::M48n6, 10 + k % 8),
_ => What::Strike,
};
rec.straight(1000 + k, what, first, last, DVec3::new(-2000.0, 100.0, k as f64 * 5.0), DVec3::new(500.0, 70.0, k as f64 * 5.0));
}
// The events: interceptions, hits, losses and splits spread through the raid.
rec.events = (0..EVENTS)
.map(|i| {
let at = (i as u64 * u64::from(TICKS) / EVENTS as u64) as u32;
let drone = 1000 + (i as u32 * 7 % 200);
let pos = DVec3::new((i % 40) as f64 * 10.0, 95.0, (i % 17) as f64 * 12.0);
let kind = match i % 10 {
0 | 1 => EventKind::Kill { drone, kind: DroneKind::Geran3, sam: 10, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() },
2 | 3 => EventKind::Hit { drone, kind: DroneKind::Geran3, power: (i % 5) as u32, object: Some(i % 8), sam: None },
4 | 5 => EventKind::Crash { drone, kind: DroneKind::Geran3, power: (i % 5) as u32 },
6 => EventKind::SamLost { sam: 10 + (i % 8) as u32, kind: SamKind::S400, index: i % 8 },
7 => EventKind::Split { drone },
_ => EventKind::Strike { site: 1, result: StrikeResult::Destroyed },
};
Event { at, pos, kind }
})
.collect();
// The scene journal: launches and ignitions (the exact sounds), track changes and fires.
let mut scene = SceneJournal::default();
for i in 0..SCENE {
let at = (i as u64 * u64::from(TICKS) / SCENE as u64) as u32;
let missile = 5000 + (i as u32 % 300);
let pos = DVec3::new((i % 30) as f64 * 8.0, 66.0, 300.0);
let kind = match i % 100 {
// Fires are a small share of a raid's transitions (hundreds over ten minutes).
0 => SceneKind::FireStarted { fire: (i / 100) as u32, age: 0, life: 4000, size: 1.0, quiet: false, shown: true, water: Some(false) },
1 => SceneKind::FireEnded { fire: (i / 100) as u32 },
2 | 3 => SceneKind::MissileLaunch { missile, sam: 10, target: 2000, kind: MissileKind::M48n6, sound: "airdef:launch.s400", pitch: 1.0 },
4 | 5 => SceneKind::MotorIgnition { missile, kind: MissileKind::M48n6, sound: Some("airdef:launch.s400") },
6 => SceneKind::MotorBurnout { missile, kind: MissileKind::M48n6 },
7 => SceneKind::MotorEnergyLost { missile, kind: MissileKind::M48n6, speed: 4.0 },
8 | 9 => SceneKind::TrackAcquired { sam: 10, target: 2000 + (i as u32 % 200), ever_own: true },
_ => SceneKind::TrackLost { sam: 10, target: 2000 + (i as u32 % 200) },
};
scene.fixture_push(SceneEvent { at, pos, kind });
}
rec.scene = Some(scene);
rec.close();
rec
}
/// Answers the ground queries the replays make with a flat 70-block land, as the game would.
fn settle(ground: &mut Ground, now: u64) {
let wanted = ground.take_wanted();
if !wanted.is_empty() {
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 70)).collect(), now);
}
}
fn percentile(sorted: &[Duration], p: f64) -> f64 {
if sorted.is_empty() {
return 0.0;
}
let i = (((sorted.len() - 1) as f64) * p).round() as usize;
sorted[i].as_secs_f64() * 1e6
}
struct Measured {
mode: &'static str,
frames: usize,
scanned: u64,
cpu: Vec<Duration>,
}
impl Measured {
fn cpu_p(&self, p: f64) -> f64 {
let mut sorted = self.cpu.clone();
sorted.sort_unstable();
percentile(&sorted, p)
}
fn json(&self, rec: &Recording, sim: &Sim) -> String {
let events_bytes = rec.events.capacity() * std::mem::size_of::<Event>();
let scene_events = rec.scene.as_ref().map_or(0, |s| s.events().len());
let scene_bytes = scene_events * std::mem::size_of::<SceneEvent>();
let index_bytes: usize = sim.replays.iter().map(Recording::index_bytes).sum();
format!(
"{{\"mode\":\"{}\",\"frames\":{},\"journal_events\":{},\"journal_scene\":{},\
\"scanned_events\":{},\"scanned_per_frame\":{:.1},\"full_pass_events\":{},\
\"p50_us\":{:.1},\"p95_us\":{:.1},\"p99_us\":{:.1},\"max_us\":{:.1},\
\"events_bytes\":{},\"scene_bytes\":{},\"index_bytes\":{}}}",
self.mode,
self.frames,
rec.events.len(),
scene_events,
self.scanned,
self.scanned as f64 / self.frames.max(1) as f64,
// One whole-journal pass per frame: what the readers did before the ranges (#150).
(rec.events.len() + scene_events) as u64 * self.frames as u64,
self.cpu_p(0.50),
self.cpu_p(0.95),
self.cpu_p(0.99),
self.cpu.iter().copied().max().unwrap_or_default().as_secs_f64() * 1e6,
events_bytes,
scene_bytes,
index_bytes,
)
}
}
/// Steps the replay's clock to `t` the way the wheel does (5 s a press), so the seek resets the
/// sound cursor and the shot as a player's would.
fn seek_to(p: &mut Player, rec: &Recording, t: f64) {
for _ in 0..((t.max(0.0) / 100.0) as usize) {
p.control(Control::Forward, rec);
}
}
fn sim_with(rec: Recording) -> (Sim, u64) {
let mut sim = Sim::new(1);
sim.replays.push(rec);
(sim, 1)
}
/// Ordinary playback from a moment near the end of the raid, time running at ×2.
fn playback() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 - 1_200.0);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "playback", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// Reverse seeks: five seconds back every frame, then a frame of playback.
fn reverse_seek() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 - 200.0);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.control(Control::Back, rec);
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "reverse_seek", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// A pause held while frames keep coming (the HUD and the ghosts stay, nothing sounds).
fn paused() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let mut p = Player::new(1, Mode::Full, &sim);
seek_to(&mut p, rec, rec.len as f64 * 0.75);
p.control(Control::Pause, rec);
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "pause", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
/// An MP4 export: the director's film, its frames prepared and drawn as the game records them.
fn mp4() -> Measured {
let (sim, mut tick) = sim_with(recording());
let rec = &sim.replays[0];
let film = Film::build(rec, Which::Best).expect("the raid has moments to film");
let mut p = Player::new(1, Mode::Film(Box::new(film)), &sim);
p.wait = true;
p.clean = true;
let mut ground = Ground::default();
let mut out = Out::default();
let _ = airdef::sim::record::scanned_events();
let mut cpu = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let started = Instant::now();
p.tick(&sim, &mut ground, LISTENER, &mut out);
settle(&mut ground, tick);
tick += 1;
cpu.push(started.elapsed());
out = Out::default();
}
Measured { mode: "mp4", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
}
pub fn main() {
let (playback, reverse_seek, paused, mp4) = (playback(), reverse_seek(), paused(), mp4());
let (sim, _) = sim_with(recording());
let rec = &sim.replays[0];
if !airdef::sim::record::scan_counters() {
eprintln!("replay_bench: scanned events read 0; rerun with --features bench-counters");
}
let rows = [playback.json(rec, &sim), reverse_seek.json(rec, &sim), paused.json(rec, &sim), mp4.json(rec, &sim)];
println!("[");
println!("{}", rows.join(",\n"));
println!("]");
}
+41 -1
View File
@@ -72,6 +72,9 @@ pub struct Scenario {
pub ew: bool, pub ew: bool,
/// Ticks a truck on a job may stand still before it counts as stuck. /// Ticks a truck on a job may stand still before it counts as stuck.
pub stuck_after: u64, pub stuck_after: u64,
/// The smart enemy runs the legacy picks (#149's comparison runner): separate hint lists,
/// the lifetime bearing tally, no mark pricing and no refresh of the unreleased portion.
pub legacy: bool,
} }
impl Scenario { impl Scenario {
@@ -87,6 +90,7 @@ impl Scenario {
stop_at_end: true, stop_at_end: true,
ew: false, ew: false,
stuck_after: 600, stuck_after: 600,
legacy: false,
} }
} }
pub fn unit(&mut self, kind: SamKind, x: f64, z: f64) -> &mut Unit { pub fn unit(&mut self, kind: SamKind, x: f64, z: f64) -> &mut Unit {
@@ -138,6 +142,18 @@ pub struct Report {
pub intents: String, pub intents: String,
/// The most aim switches one drone went through. /// The most aim switches one drone went through.
pub switches_max: u16, pub switches_max: u16,
/// Smart drones seen over the run (#149's comparison).
pub smart_seen: u32,
/// The share of them whose last aim was a live public hint when last seen (#149).
pub useful_share: f64,
/// Distinct aim units over the smart drones seen, per drone (#149).
pub diversity: f64,
/// The share of smart drones switched twice or more (#149's jitter).
pub jittery_share: f64,
/// The bearing picker's last typed reason (#149).
pub bearing_reason: String,
/// Aims the bounded refresh re-chose (#149).
pub refresh_applied: u32,
} }
/// The last intent every smart drone of the run was seen carrying, as `name:count`. /// The last intent every smart drone of the run was seen carrying, as `name:count`.
@@ -146,7 +162,7 @@ fn intent_counts(seen: &HashMap<u32, &'static str>) -> String {
for name in seen.values() { for name in seen.values() {
*counts.entry(*name).or_insert(0usize) += 1; *counts.entry(*name).or_insert(0usize) += 1;
} }
["plan", "sead", "react", "replace"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::<Vec<_>>().join(",") ["plan", "sead", "react", "replace", "refresh"].iter().map(|k| format!("{k}:{}", counts.get(*k).copied().unwrap_or(0))).collect::<Vec<_>>().join(",")
} }
fn finite(v: DVec3) -> bool { fn finite(v: DVec3) -> bool {
@@ -154,7 +170,14 @@ fn finite(v: DVec3) -> bool {
} }
pub fn run(sc: &Scenario) -> Report { pub fn run(sc: &Scenario) -> Report {
run_with_hook(sc, &mut |_, _| {})
}
/// The same, with a hook called after every tick (#149's comparison runner): a scenario may
/// change the defence between waves or shoot a recon flight down before its report.
pub fn run_with_hook(sc: &Scenario, hook: &mut dyn FnMut(u64, &mut Sim)) -> Report {
let mut sim = Sim::new(sc.seed); let mut sim = Sim::new(sc.seed);
sim.smart_legacy = sc.legacy;
sim.damage = false; // explosions would change the land the height function describes sim.damage = false; // explosions would change the land the height function describes
for u in &sc.units { for u in &sc.units {
let id = sim.id(); let id = sim.id();
@@ -183,6 +206,8 @@ pub fn run(sc: &Scenario) -> Report {
let mut standing: HashMap<u32, (DVec3, u64)> = HashMap::new(); let mut standing: HashMap<u32, (DVec3, u64)> = HashMap::new();
// drone id -> the last structured intent it carried (#127). // drone id -> the last structured intent it carried (#127).
let mut intents_seen: HashMap<u32, &'static str> = HashMap::new(); let mut intents_seen: HashMap<u32, &'static str> = HashMap::new();
// drone id -> (last aim unit, whether the picture held it live then, switches) (#149).
let mut decisions: HashMap<u32, (u32, bool, u16)> = HashMap::new();
let mut out = Out::default(); let mut out = Out::default();
for now in 1..=sc.ticks { for now in 1..=sc.ticks {
// Raids come in order: one is ordered once the previous one has been sent. // Raids come in order: one is ordered once the previous one has been sent.
@@ -205,6 +230,7 @@ pub fn run(sc: &Scenario) -> Report {
ground.world.serve(&sc.terrain, sections, now); ground.world.serve(&sc.terrain, sections, now);
let dt = t.elapsed(); let dt = t.elapsed();
times.push(dt); times.push(dt);
hook(now, &mut sim);
if planning { if planning {
r.planning += dt; r.planning += dt;
r.planning_ticks += 1; r.planning_ticks += 1;
@@ -220,6 +246,8 @@ pub fn run(sc: &Scenario) -> Report {
for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) { for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) {
if d.alive() && d.smart() { if d.alive() && d.smart() {
intents_seen.insert(d.id, d.intent().name()); intents_seen.insert(d.id, d.intent().name());
let unit = d.aim_unit();
decisions.insert(d.id, (unit, unit != 0 && sim.known_live(unit), d.aim_switches()));
} }
} }
// The air section a save would take, sampled when the sky is fullest (writing it every tick // The air section a save would take, sampled when the sky is fullest (writing it every tick
@@ -271,6 +299,18 @@ pub fn run(sc: &Scenario) -> Report {
r.raids_ended = ended.iter().filter(|o| **o).count(); r.raids_ended = ended.iter().filter(|o| **o).count();
r.all_ended = r.raids_ended == sc.raids.len(); r.all_ended = r.raids_ended == sc.raids.len();
r.intents = intent_counts(&intents_seen); r.intents = intent_counts(&intents_seen);
r.smart_seen = decisions.len() as u32;
if !decisions.is_empty() {
let n = decisions.len() as f64;
r.useful_share = decisions.values().filter(|(_, live, _)| *live).count() as f64 / n;
let mut units: Vec<u32> = decisions.values().map(|(u, _, _)| *u).collect();
units.sort_unstable();
units.dedup();
r.diversity = units.len() as f64 / n;
r.jittery_share = decisions.values().filter(|(_, _, s)| *s >= 2).count() as f64 / n;
}
r.bearing_reason = sim.bearing_report().reason.name().to_string();
r.refresh_applied = sim.refresh_applied();
r.tick_total = times.iter().sum(); r.tick_total = times.iter().sum();
times.sort(); times.sort();
if !times.is_empty() { if !times.is_empty() {
+187
View File
@@ -0,0 +1,187 @@
//! Smart v2 comparison runner (#149): the simple mode, the current (legacy) Smart and the
//! candidate, on fixed seeds and one scenario set — open map, hills, a configuration changed
//! between waves, and a recon flight shot down before its report.
//!
//! It prints one JSON array of rows: the share of useful decisions (a smart drone whose last
//! aim was a live public hint), the diversity of aims, the reasons (intents) on the review,
//! the share of jittery drones (two switches or more), the bearing picker's typed reason, the
//! refresh count, and the CPU/worst-job figures. The goal is interesting counterplay and clear
//! mistakes, not a maximised hit count — read the reasons and the jitter beside the losses.
//!
//! cargo run --release --example smart_bench
#[path = "sim_run/harness.rs"]
mod harness;
use airdef::sim::{Aim, Approach, DroneKind, Sam, SamKind, Sim};
use glam::DVec3;
use harness::{Report, Scenario, Terrain};
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Simple,
Current,
Candidate,
}
impl Mode {
fn name(self) -> &'static str {
match self {
Mode::Simple => "simple",
Mode::Current => "current",
Mode::Candidate => "candidate",
}
}
fn apply(self, sc: &mut Scenario) {
sc.legacy = self == Mode::Current;
let aim = match self {
Mode::Simple => Aim::ObjectsAndSams,
_ => Aim::Smart,
};
for raid in &mut sc.raids {
raid.aim = aim;
}
}
}
fn esc(s: &str) -> String {
s.chars().flat_map(|c| match c {
'"' => "\\\"".chars().collect::<Vec<_>>(),
'\\' => "\\\\".chars().collect::<Vec<_>>(),
c => vec![c],
}).collect()
}
fn row(sc: &str, mode: Mode, r: &Report) -> String {
format!(
"{{\"scenario\":\"{}\",\"mode\":\"{}\",\"seed\":{},\"ticks\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"fired\":{},\"sams_lost\":{},\"smart_seen\":{},\"useful_share\":{:.3},\"diversity\":{:.3},\"jittery_share\":{:.3},\"intents\":\"{}\",\"bearing_reason\":\"{}\",\"refresh_applied\":{},\"switches_max\":{},\"retargets_max\":{},\"tick_p95_ms\":{:.3},\"tick_max_ms\":{:.3},\"planning_ms\":{:.1},\"air_bytes\":{}}}",
esc(sc),
mode.name(),
r.seed,
r.ticks_run,
r.all_ended,
r.launched,
r.kills,
r.hits,
r.fired,
r.sams_lost,
r.smart_seen,
r.useful_share,
r.diversity,
r.jittery_share,
esc(&r.intents),
esc(&r.bearing_reason),
r.refresh_applied,
r.switches_max,
r.retargets_max,
r.tick_p95.as_secs_f64() * 1000.0,
r.tick_max.as_secs_f64() * 1000.0,
r.planning.as_secs_f64() * 1000.0,
r.air_bytes,
)
}
/// An open map: a ring of systems on flat land, one combined strike.
fn open() -> Scenario {
let mut sc = Scenario::new("open");
sc.terrain = Terrain::Flat(70);
for i in 0..18 {
let a = i as f64 * 2.399_963;
let r = 120.0 + (i as f64 / 18.0) * 320.0;
let kind = [SamKind::Radar, SamKind::S400, SamKind::Pantsir, SamKind::Ew, SamKind::Tor][i % 5];
sc.unit(kind, a.sin() * r, a.cos() * r).heading = a;
}
sc.raids.push(harness::RaidSpec {
kinds: vec![(DroneKind::Gerbera, 6), (DroneKind::Shahed, 10), (DroneKind::Kh101, 3), (DroneKind::Kh22, 2), (DroneKind::Lancet, 3)],
approach: Approach::AllSides,
aim: Aim::Smart,
dist: 500.0,
at: 1,
});
sc.ticks = 20 * 60 * 6;
sc
}
/// Hills: the standard big smart scenario's terrain and force.
fn hills() -> Scenario {
let mut sc = harness::big_smart();
sc.name = "hills".into();
sc.ticks = 20 * 60 * 6;
sc
}
/// Two waves with the defence changed between them: a radar moves unobserved, the EW stations
/// switch on, and a fresh battery appears. The second wave's picture must earn what it knows.
fn config_change() -> Scenario {
let mut sc = open();
sc.name = "config-change".into();
sc.raids.push(harness::RaidSpec {
kinds: vec![(DroneKind::Shahed, 8), (DroneKind::Geran3, 4), (DroneKind::Kh22, 2), (DroneKind::Iskander, 2)],
approach: Approach::TwoSectors,
aim: Aim::Smart,
dist: 600.0,
at: 4200,
});
sc.ticks = 20 * 60 * 10;
sc
}
/// A recon flight shot down before its report: the strike must fly on the picture it had, and
/// the bounded refresh must never hold the raid waiting for a report that will not come.
fn recon_lost() -> Scenario {
let mut sc = open();
sc.name = "recon-lost".into();
sc.ticks = 20 * 60 * 6;
sc
}
pub fn main() {
let seeds = [1u64, 7, 42];
let scenarios: [(&str, fn() -> Scenario); 4] = [("open", open), ("hills", hills), ("config-change", config_change), ("recon-lost", recon_lost)];
let modes = [Mode::Simple, Mode::Current, Mode::Candidate];
let mut rows = Vec::new();
for (name, make) in scenarios {
for mode in modes {
for &seed in &seeds {
let r = run(mode, name, make, seed);
rows.push(row(name, mode, &r));
eprintln!("{name} {} seed {seed}: useful {:.2} diversity {:.2} jitter {:.2} kills {} hits {} reasons {} bearing {} refresh {}", mode.name(), r.useful_share, r.diversity, r.jittery_share, r.kills, r.hits, r.intents, r.bearing_reason, r.refresh_applied);
}
}
}
println!("[{}]", rows.join(",\n"));
}
fn run(mode: Mode, name: &str, make: fn() -> Scenario, seed: u64) -> Report {
let mut sc = make();
sc.seed = seed;
mode.apply(&mut sc);
match name {
"config-change" => {
let mut changed = false;
harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| {
if !changed && now >= 3600 && !sim.planning() {
changed = true;
if let Some(radar) = sim.sams.iter_mut().find(|s| s.kind == SamKind::Radar) {
radar.pos += DVec3::new(300.0, 0.0, -200.0);
}
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(-200.0, 70.0, 250.0), 0.0));
sim.set_ew(true);
}
})
}
"recon-lost" => {
let mut killed = false;
harness::run_with_hook(&sc, &mut |now, sim: &mut Sim| {
if !killed && now >= 120 {
let recon: Vec<u32> = sim.drones.iter().filter(|d| sim.is_recon_drone(d.id)).map(|d| d.id).collect();
if !recon.is_empty() {
sim.drones.retain(|d| !recon.contains(&d.id));
killed = true;
}
}
})
}
_ => harness::run(&sc),
}
}
+17 -2
View File
@@ -119,8 +119,13 @@ d8ac6a9258e2fc2e0791bbce18a3a07a72e471fbc72b6be7b5ca545c53f8d633 assets/airdef/
e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json
68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json 68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json
d93b6bf77de4aed1f1955e76353661729f06445788ad7a6654ed6af1a67fc48d assets/airdef/items/deploy_radar.json d93b6bf77de4aed1f1955e76353661729f06445788ad7a6654ed6af1a67fc48d assets/airdef/items/deploy_radar.json
84306c42dd25300f1cef69c83e3211ccc921fa606046157295a4ca3e3d568a0a assets/airdef/items/deploy_radar_height.json
28f6b71116bdc911e70d2382807c86edff40adae44acd256f798360dc60bd572 assets/airdef/items/deploy_radar_search.json
0e470cfa2a13383fadb74336c5333449f4079659d9d83596dcfcf2d592521a4c assets/airdef/items/deploy_radar_track.json
0b9445f3b54a9e958da0b9bd4243a41d85fc8f12b5c4e56bbc070edb8f1bf618 assets/airdef/items/deploy_s400.json 0b9445f3b54a9e958da0b9bd4243a41d85fc8f12b5c4e56bbc070edb8f1bf618 assets/airdef/items/deploy_s400.json
77355fc96ed50feb117bc6e7f7f70e9559bc69174a7a84afe7e3121db65efbfd assets/airdef/items/deploy_s400_launcher.json
dd7478f447d87dcad42e1a7e6dcb5fae555c832e933a3722022d0e10e2de011e assets/airdef/items/deploy_s500.json dd7478f447d87dcad42e1a7e6dcb5fae555c832e933a3722022d0e10e2de011e assets/airdef/items/deploy_s500.json
47dabb117d3e6fb44005f4be8c2be2b6c4f8d7e06ff5ed2d426ac1e58e6408ce assets/airdef/items/deploy_s500_launcher.json
14e9a20dcddee5a6262ef624783900576dac2bd16e5079e731cf6115f13c76ec assets/airdef/items/deploy_tor.json 14e9a20dcddee5a6262ef624783900576dac2bd16e5079e731cf6115f13c76ec assets/airdef/items/deploy_tor.json
d4ff57f630ca92bf52ba228d8c6fd5292928b685d6bb5a9c9b9dc0c3d586fc2e assets/airdef/items/deploy_tzm.json d4ff57f630ca92bf52ba228d8c6fd5292928b685d6bb5a9c9b9dc0c3d586fc2e assets/airdef/items/deploy_tzm.json
044fc626ad99ff8be6db0800f96dc743fc80606d813bd59abad531396bf9d8ce assets/airdef/items/designator.json 044fc626ad99ff8be6db0800f96dc743fc80606d813bd59abad531396bf9d8ce assets/airdef/items/designator.json
@@ -137,8 +142,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json 489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json 6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json 177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/en_us.json c10367467f45c274e92d534199c2851520140507903a5d4287f12ed403c92be5 assets/airdef/lang/en_us.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/ru_ru.json c10367467f45c274e92d534199c2851520140507903a5d4287f12ed403c92be5 assets/airdef/lang/ru_ru.json
b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json
c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json
a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json
@@ -260,8 +265,13 @@ e80ee81085241b9712e024bbef73ef744ef5493eebb88770f4912d8aae138fe6 assets/airdef/
8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json 8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json
d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar.json 332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_height.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_search.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_radar_track.json
9ee1dfa7d2c2587c85a8f73554962a02a06f1969a9a56c56110162dd93db7301 assets/airdef/models/item/deploy_s400.json 9ee1dfa7d2c2587c85a8f73554962a02a06f1969a9a56c56110162dd93db7301 assets/airdef/models/item/deploy_s400.json
9ee1dfa7d2c2587c85a8f73554962a02a06f1969a9a56c56110162dd93db7301 assets/airdef/models/item/deploy_s400_launcher.json
55f1dae5cd7f0126533825c9da3ed3ee316e74d4be8f9bb217a3ebc6f827d24d assets/airdef/models/item/deploy_s500.json 55f1dae5cd7f0126533825c9da3ed3ee316e74d4be8f9bb217a3ebc6f827d24d assets/airdef/models/item/deploy_s500.json
55f1dae5cd7f0126533825c9da3ed3ee316e74d4be8f9bb217a3ebc6f827d24d assets/airdef/models/item/deploy_s500_launcher.json
aca5ea765ca0d84ed12444bf433c024b57d6ea9b9b7cf06449dfbd6892a66ae6 assets/airdef/models/item/deploy_tor.json aca5ea765ca0d84ed12444bf433c024b57d6ea9b9b7cf06449dfbd6892a66ae6 assets/airdef/models/item/deploy_tor.json
67912cc711c2f1514e6e2f8f17aa340fa9a99534fbbaeb2b8e319aa6ef80f38d assets/airdef/models/item/deploy_tzm.json 67912cc711c2f1514e6e2f8f17aa340fa9a99534fbbaeb2b8e319aa6ef80f38d assets/airdef/models/item/deploy_tzm.json
d0976d990130c6398f4adf5d3086e9cf50e5a2adbec081e4682e810af368c332 assets/airdef/models/item/designator.json d0976d990130c6398f4adf5d3086e9cf50e5a2adbec081e4682e810af368c332 assets/airdef/models/item/designator.json
@@ -574,8 +584,13 @@ cc0877f40434365b45b03429222926aa0cf135e504017311be53263fd27c5f8f data/airdef/ho
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_height.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_search.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_radar_track.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s400.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s400.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s400_launcher.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s500.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s500.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_s500_launcher.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tor.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tor.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tzm.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_tzm.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/designator.json 2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/designator.json
+26 -19
View File
@@ -209,26 +209,33 @@ fn post(uv: vec2<f32>, pixel: vec2<f32>) -> vec4<f32> {
let on_screen = radius / max(length(centre), 1.0); let on_screen = radius / max(length(centre), 1.0);
let steps = i32(clamp(on_screen * 40.0, 6.0, 14.0)); let steps = i32(clamp(on_screen * 40.0, 6.0, 14.0));
let ds = (t1 - t0) / f32(steps); let ds = (t1 - t0) / f32(steps);
for (var s = 0; s < steps; s++) { // At zero fade every step's density is zero: absorb is 0, so the march adds no light and
if trans < 0.02 { break; } // leaves the transmittance alone. Skip it (the HD smoke path fades out by k = 0.28) instead
let p = dir * (t0 + (f32(s) + 0.5) * ds); // of sampling the noise and shading a volume that cannot be seen.
let local = (p - centre) / radius; if fade > 0.0 {
let r = length(local); for (var s = 0; s < steps; s++) {
let n = fbm(local * 2.4 + seed + vec3<f32>(0.0, -age * 0.06, age * 0.02)); if trans < 0.02 { break; }
let shape = smoothstep(1.0, 0.25, r + (n - 0.5) * 1.1); let p = dir * (t0 + (f32(s) + 0.5) * ds);
if shape <= 0.0 { continue; } let local = (p - centre) / radius;
let density = shape * (1.2 + n * 2.0) * fade; let r = length(local);
let absorb = 1.0 - exp(-density * ds * 1.4 / max(radius * 0.25, 0.5)); let n = fbm(local * 2.4 + seed + vec3<f32>(0.0, -age * 0.06, age * 0.02));
// Hot inside, soot outside; smoke lit from above by the sky. let shape = smoothstep(1.0, 0.25, r + (n - 0.5) * 1.1);
let core = heat * (1.0 - r) * (0.6 + n); if shape <= 0.0 { continue; }
let smoke = vec3<f32>(0.10, 0.095, 0.09) * (0.5 + 0.8 * sun * (0.5 + local.y * 0.5)); let density = shape * (1.2 + n * 2.0) * fade;
let c = mix(smoke, fire(core * 1.6), clamp(core * 2.2, 0.0, 1.0)); let absorb = 1.0 - exp(-density * ds * 1.4 / max(radius * 0.25, 0.5));
lit += trans * absorb * c; // Hot inside, soot outside; smoke lit from above by the sky.
trans *= 1.0 - absorb; let core = heat * (1.0 - r) * (0.6 + n);
let smoke = vec3<f32>(0.10, 0.095, 0.09) * (0.5 + 0.8 * sun * (0.5 + local.y * 0.5));
let c = mix(smoke, fire(core * 1.6), clamp(core * 2.2, 0.0, 1.0));
lit += trans * absorb * c;
trans *= 1.0 - absorb;
}
}
// Light thrown round by the fire (zero once its heat is spent).
if heat > 0.0 {
let d = length(centre);
glow += vec3<f32>(1.0, 0.5, 0.15) * heat * heat * size * 0.05 / (1.0 + d * 0.03);
} }
// Light thrown round by the fire.
let d = length(centre);
glow += vec3<f32>(1.0, 0.5, 0.15) * heat * heat * size * 0.05 / (1.0 + d * 0.03);
} }
color = color * trans + lit; color = color * trans + lit;
+15 -15
View File
@@ -39,7 +39,7 @@ pub fn status(status: BatteryStatus) -> String {
} }
/// One system's line in the summary panel and on the map. /// One system's line in the summary panel and on the map.
pub fn sam_status(sam: &Sam) -> String { pub fn sam_status(sam: &Sam, now: u64) -> String {
let spec = sam.kind.spec(); let spec = sam.kind.spec();
let mut text = spec.name.to_string(); let mut text = spec.name.to_string();
if !sam.alive() { if !sam.alive() {
@@ -67,7 +67,7 @@ pub fn sam_status(sam: &Sam) -> String {
let channels = if profile.channels == 0 { let channels = if profile.channels == 0 {
"без уточнения".to_string() "без уточнения".to_string()
} else { } else {
format!("каналы {}/{}", sam.own_channels_used(), profile.channels) format!("каналы {}/{}", sam.own_channels_used(now), profile.channels)
}; };
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len()); return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
} }
@@ -100,7 +100,7 @@ pub fn sam_status(sam: &Sam) -> String {
text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20)); text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20));
} else { } else {
if let Some(magazine) = sam.kind.missile_magazine() { if let Some(magazine) = sam.kind.missile_magazine() {
if sam.kind == SamKind::S400 { if sam.kind.supports_rm48u() {
text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells()); text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells());
if sam.ground_return { text += " · ожидает вывоза RM48U"; } if sam.ground_return { text += " · ожидает вывоза RM48U"; }
} else { } else {
@@ -126,20 +126,20 @@ mod tests {
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0); let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
s400.missiles = 1; s400.missiles = 1;
s400.ground_rounds = 2; s400.ground_rounds = 2;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек"); assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
s400.ground_return = true; s400.ground_return = true;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U"); assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0); let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
pantsir.missiles = 7; pantsir.missiles = 7;
pantsir.bursts = 100; pantsir.bursts = 100;
assert_eq!(sam_status(&pantsir), "Панцирь-С1 ракеты 7/12 очереди 100"); assert_eq!(sam_status(&pantsir, 0), "Панцирь-С1 ракеты 7/12 очереди 100");
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0); let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
worn.health = 0.5; worn.health = 0.5;
worn.comps.0[Part::Sensor as usize] = 0.4; worn.comps.0[Part::Sensor as usize] = 0.4;
worn.reloading = 21; worn.reloading = 21;
assert_eq!(sam_status(&worn), "Patriot (50%) [РЛС 40%] перезарядка 2с"); assert_eq!(sam_status(&worn, 0), "Patriot (50%) [РЛС 40%] перезарядка 2с");
} }
#[test] #[test]
@@ -147,41 +147,41 @@ mod tests {
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0); let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
radar.own.push(7); radar.own.push(7);
radar.comps.0[Part::Sensor as usize] = 0.0; radar.comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3"); assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0); let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
depot.cargo = 2; depot.cargo = 2;
depot.ground_stock = 3; depot.ground_stock = 3;
depot.air_48n6_stock = 1; depot.air_48n6_stock = 1;
assert_eq!(sam_status(&depot), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1"); assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0); let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
tzm.cargo = 1; tzm.cargo = 1;
tzm.return_cargo = true; tzm.return_cargo = true;
assert_eq!(sam_status(&tzm), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад"); assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0); let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
ew.ew_on = true; ew.ew_on = true;
ew.heat = 0.5; ew.heat = 0.5;
assert_eq!(sam_status(&ew), "Станция РЭБ: ГЛУШИТ, нагрев 50%"); assert_eq!(sam_status(&ew, 0), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0); let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
light.target = Some(1); light.target = Some(1);
assert_eq!(sam_status(&light), "Прожектор: в луче цель"); assert_eq!(sam_status(&light, 0), "Прожектор: в луче цель");
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0); let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
assert_eq!(sam_status(&optical), "Оптический пост: ищет"); assert_eq!(sam_status(&optical, 0), "Оптический пост: ищет");
} }
#[test] #[test]
fn renders_moving_and_destroyed_systems_in_existing_format() { fn renders_moving_and_destroyed_systems_in_existing_format() {
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0); let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
moving.state = SamState::Moving; moving.state = SamState::Moving;
assert_eq!(sam_status(&moving), "С-400 на марше"); assert_eq!(sam_status(&moving, 0), "С-400 на марше");
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0); let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
dead.health = 0.0; dead.health = 0.0;
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН"); assert_eq!(sam_status(&dead, 0), "С-400 УНИЧТОЖЕН");
} }
#[test] #[test]
+6 -1
View File
@@ -95,6 +95,7 @@ pub fn diagnostics() -> String {
let lights = render::point_lights_status(); let lights = render::point_lights_status();
let sources = render::sound_sources_status(); let sources = render::sound_sources_status();
let cameras = render::camera_status(); let cameras = render::camera_status();
let dlss = render::dlss_status();
let smoke_reason = match smoke.reason { let smoke_reason = match smoke.reason {
render::SmokeReason::AwaitingFrame => "awaiting-frame", render::SmokeReason::AwaitingFrame => "awaiting-frame",
render::SmokeReason::Disabled => "disabled", render::SmokeReason::Disabled => "disabled",
@@ -102,7 +103,7 @@ pub fn diagnostics() -> String {
render::SmokeReason::Ready => "ready", render::SmokeReason::Ready => "ready",
}; };
[ [
"Возможности движка (API 31; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(), "Возможности движка (API 33; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
line( line(
"Дым", "Дым",
smoke.generation, smoke.generation,
@@ -149,6 +150,10 @@ pub fn diagnostics() -> String {
capture.prepared, capture.prepared,
reason(capture.reason), reason(capture.reason),
), ),
format!(
"DLSS: устройство={}, включено={} (выкл — родной TAAU; вкл без устройства — при следующем запуске)",
dlss.available, dlss.enabled
),
] ]
.join("\n") .join("\n")
} }
+24 -6
View File
@@ -56,8 +56,15 @@ pub fn tree() -> Tree {
), ),
Node::lit("list").runs(), Node::lit("list").runs(),
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()), Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
Node::lit("village").runs().then(
Node::arg("режим", Value::choice(["easy", "normal", "hard", "start", "status", "prices", "stop"])).runs(),
),
]), ]),
Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()), Node::lit("breaches").runs().then(Node::arg("страница", Value::int_from(1)).runs()),
Node::lit("why").runs().then(
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
),
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
Node::lit("raid").runs(), Node::lit("raid").runs(),
Node::lit("sites").runs(), Node::lit("sites").runs(),
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())), Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
@@ -107,6 +114,15 @@ pub fn tree() -> Tree {
Node::lit("reset").runs(), Node::lit("reset").runs(),
])), ])),
Node::lit("recon").runs(), Node::lit("recon").runs(),
Node::lit("post").runs().then(Node::arg("поиск", Value::word()).runs()),
Node::lit("panel").with([
Node::lit("snapshot").then(Node::arg("запрос", Value::word()).then(
Node::arg("ракурс", Value::choice(["public", "debug"])).then(Node::arg("позиция", Value::word()).runs())
)),
Node::lit("launch").then(Node::arg("запрос", Value::word()).then(
Node::arg("сессия", Value::word()).then(Node::arg("сценарий", Value::word()).runs())
)),
]),
Node::lit("stats").runs(), Node::lit("stats").runs(),
]) ])
} }
@@ -163,12 +179,13 @@ mod tests {
#[test] #[test]
fn every_branch_of_the_handler_parses() { fn every_branch_of_the_handler_parses() {
for line in [ for line in [
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles", "", "menu", "capabilities", "monitor", "grid", "post", "post Панцирь", "post 82", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles",
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all", "replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3", "replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop", "replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list", "scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
"scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear", "scenario delete a", "scenario village", "scenario village hard", "scenario village start",
"breaches", "breaches 2", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000", "sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off", "wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic", "roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
@@ -242,14 +259,15 @@ mod tests {
fn completion_offers_the_next_word_only() { fn completion_offers_the_next_word_only() {
let top = complete("", &[]); let top = complete("", &[]);
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move", for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] { "target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}"); assert!(top.contains(&w.to_string()), "{w} in {top:?}");
} }
assert_eq!(top.len(), 36); assert!(top.contains(&"post".to_string()));
assert_eq!(top.len(), 40);
assert_eq!(complete("rep", &[]), ["repair", "replay"]); assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]); assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]); assert_eq!(complete("replay film ", &[]), ["all", "best"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save"]); assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save", "village"]);
assert_eq!(complete("wave ", &[]).len(), 14); assert_eq!(complete("wave ", &[]).len(), 14);
assert!(complete("wave s", &[]).contains(&"shahed".to_string())); assert!(complete("wave s", &[]).contains(&"shahed".to_string()));
assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]); assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]);
+229
View File
@@ -0,0 +1,229 @@
//! Picking nearby AirDef models against the same block ray the client uses for its crosshair.
use crate::sim::Model;
use glam::{DVec3, Vec3};
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
pub const REACH: f32 = 24.0;
const FACE_BYTES: usize = 4 * 3 * size_of::<f32>();
const FACES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/inspect-faces.bin"));
const MESHES: &[(&str, Mesh)] = include!(concat!(env!("OUT_DIR"), "/inspect-meshes.rs"));
struct Mesh {
min: [f32; 3],
max: [f32; 3],
radius: f32,
start: usize,
end: usize,
}
pub struct Ray {
origin: DVec3,
direction: DVec3,
limit: f64,
}
impl Ray {
pub fn from_view(eye: DVec3, direction: DVec3, terrain: Option<DVec3>) -> Self {
let mut origin = eye;
let mut limit = f64::from(REACH);
if let Some(point) = terrain {
let horizontal = DVec3::new(direction.x, 0.0, direction.z);
let distance = if horizontal.length_squared() > 1e-8 {
// Feet and eye share X/Z. Recover the actual eye height from the host
// ray when it hit a block (the eye lowers while crouching or swimming).
let t = (point - eye).dot(horizontal) / horizontal.length_squared();
origin.y = point.y - direction.y * t;
t
} else {
(point - eye).dot(direction)
};
limit = distance.clamp(0.0, limit);
}
Self {
origin,
direction,
limit,
}
}
fn hits_bounds(&self, min: DVec3, max: DVec3) -> bool {
let (mut near, mut far) = (0.0f64, self.limit);
for i in 0..3 {
if self.direction[i].abs() < 1e-10 {
if self.origin[i] < min[i] || self.origin[i] > max[i] {
return false;
}
} else {
let a = (min[i] - self.origin[i]) / self.direction[i];
let b = (max[i] - self.origin[i]) / self.direction[i];
near = near.max(a.min(b));
far = far.min(a.max(b));
if near > far {
return false;
}
}
}
near < self.limit
}
fn triangle(&self, a: DVec3, b: DVec3, c: DVec3) -> Option<f64> {
let ab = b - a;
let ac = c - a;
let p = self.direction.cross(ac);
let determinant = ab.dot(p);
if determinant.abs() < 1e-10 {
return None;
}
let t = self.origin - a;
let u = t.dot(p) / determinant;
let q = t.cross(ab);
let v = self.direction.dot(q) / determinant;
let distance = ac.dot(q) / determinant;
(u >= 0.0 && v >= 0.0 && u + v <= 1.0 && distance >= 0.0 && distance < self.limit)
.then_some(distance)
}
}
/// Return the object that owns the closest visible face, including its rotated moving parts.
pub fn pick(
mut ray: Ray,
models: &[Model],
mut is_unit_model: impl FnMut(&Model) -> bool,
) -> Option<u32> {
let mut picked = None;
for model in models {
if model.glow || model.scale <= 0.0 {
continue;
}
let Ok(i) = MESHES.binary_search_by_key(&model.name, |(name, _)| *name) else {
continue;
};
let mesh = &MESHES[i].1;
let scale = f64::from(model.scale);
let reach = ray.limit + scale * f64::from(mesh.radius);
if model.at.distance_squared(ray.origin) > reach * reach || !is_unit_model(model) {
continue;
}
let unrotate = model.rotation.conjugate();
let mut local = Ray {
origin: unrotate * (ray.origin - model.at) / scale,
direction: unrotate * ray.direction / scale,
limit: ray.limit,
};
if !local.hits_bounds(
Vec3::from_array(mesh.min).as_dvec3(),
Vec3::from_array(mesh.max).as_dvec3(),
) {
continue;
}
for face in FACES[mesh.start..mesh.end].chunks_exact(FACE_BYTES) {
let [a, b, c, d] = std::array::from_fn(|vertex| {
DVec3::from_array(std::array::from_fn(|axis| {
let start = (vertex * 3 + axis) * size_of::<f32>();
let value = f32::from_le_bytes(
face[start..start + size_of::<f32>()].try_into().unwrap(),
);
f64::from(value)
}))
});
if let Some(hit) = local.triangle(a, b, c).or_else(|| local.triangle(a, c, d)) {
local.limit = hit;
picked = Some(model.object_id());
}
}
ray.limit = local.limit;
}
picked
}
pub fn hint(size: (f32, f32), text_width: f32, label: String) -> [Shape; 2] {
let (x, y) = (size.0 / 2.0, size.1 / 2.0 + 14.0);
[
Shape::Fill(FillShape {
rect: Rect {
x: x - text_width / 2.0 - 4.0,
y: y - 2.0,
w: text_width + 8.0,
h: 12.0,
},
color: 0xA0101518,
}),
Shape::Text(TextShape {
text: label,
at: Point { x, y },
color: 0xFFF0F4FA,
centered: true,
shadow: true,
}),
]
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DQuat;
fn radar(id: u32, at: DVec3) -> Model {
Model {
id,
name: "airdef:radar_truck",
at,
rotation: DQuat::from_rotation_y(0.4),
scale: 1.0,
glow: false,
}
}
#[test]
fn takes_the_closest_model_face_only_in_front_of_the_terrain() {
let eye = DVec3::new(0.0, 0.25, 0.0);
let models = [radar(16, 10.0 * DVec3::Z), radar(33, 6.0 * DVec3::Z)];
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |_| true),
Some(32)
);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, wall), &models, |_| true),
None
);
let wall_between_units = Some(DVec3::new(0.0, 0.25, 8.0));
assert_eq!(
pick(
Ray::from_view(eye, DVec3::Z, wall_between_units),
&models,
|_| true
),
Some(32)
);
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |m| m.id == 16),
Some(16)
);
}
#[test]
fn a_higher_visible_part_is_pickable_above_a_wall() {
let body = radar(16, 8.0 * DVec3::Z);
let antenna = Model {
name: "airdef:radar_panel",
..radar(18, DVec3::new(0.0, 1.8, 8.0))
};
let low_eye = DVec3::new(0.0, 0.25, 0.0);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
let high_eye = DVec3::new(0.0, 1.8, 0.0);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &[body], |_| true),
None
);
let models = [radar(16, 8.0 * DVec3::Z), antenna];
assert_eq!(
pick(Ray::from_view(low_eye, DVec3::Z, wall), &models, |_| true),
None
);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &models, |_| true),
Some(16)
);
}
}
+23 -8
View File
@@ -48,6 +48,9 @@ pub struct Layout {
pub wave: Option<Vec<String>>, pub wave: Option<Vec<String>>,
pub far: Option<bool>, pub far: Option<bool>,
pub acoustics: Option<bool>, pub acoustics: Option<bool>,
/// The player's DLSS request; absent in older saves (the engine's own
/// default applies: on where supported).
pub dlss: Option<bool>,
pub effects: Option<(bool, bool)>, pub effects: Option<(bool, bool)>,
pub roles: Vec<(SamKind, u8)>, pub roles: Vec<(SamKind, u8)>,
/// Fire doctrines by the system's place in the file (#47). /// Fire doctrines by the system's place in the file (#47).
@@ -130,7 +133,9 @@ impl Layout {
None => break, None => break,
} }
} }
let ground_rounds = l.num(22, "заряжено RM48U", 0.0, 4.0)?.unwrap_or(0.0) as u32; let supports_ground = kind.supports_rm48u();
let shared_cells = if supports_ground { kind.missile_magazine().unwrap_or(0) } else { 0 };
let ground_rounds = l.num(22, "заряжено RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32;
let ground_stock = l.num(23, "запас RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32; let ground_stock = l.num(23, "запас RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32;
let air_48n6_stock = l.num(24, "снятый боезапас ПВО", 0.0, COUNT)?.unwrap_or(0.0) as u32; let air_48n6_stock = l.num(24, "снятый боезапас ПВО", 0.0, COUNT)?.unwrap_or(0.0) as u32;
let mode = match l.w.get(25) { let mode = match l.w.get(25) {
@@ -146,7 +151,7 @@ impl Layout {
Some(v) => v.parse::<u8>().map_err(|_| l.bad("пустые контейнеры", "нужно целое число 0..255"))?, Some(v) => v.parse::<u8>().map_err(|_| l.bad("пустые контейнеры", "нужно целое число 0..255"))?,
}; };
let ground_request = l.num(28, "заявка RM48U", 0.0, 1.0)?.unwrap_or(0.0) == 1.0; let ground_request = l.num(28, "заявка RM48U", 0.0, 1.0)?.unwrap_or(0.0) == 1.0;
if ground_request && kind != SamKind::S400 { return Err(l.bad("заявка RM48U", "нужен С-400")); } if ground_request && !supports_ground { return Err(l.bad("заявка RM48U", "нужен совместимый профиль")); }
let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true); let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true);
let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false); let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false);
let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false); let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false);
@@ -154,7 +159,7 @@ impl Layout {
None => None, None => None,
Some(v) => Some(sim::battery::RadarProfile::from_id(v).ok_or_else(|| l.bad("профиль РЛС", "radar_multi, radar_search, radar_track или radar_height"))?), Some(v) => Some(sim::battery::RadarProfile::from_id(v).ok_or_else(|| l.bad("профиль РЛС", "radar_multi, radar_search, radar_track или radar_height"))?),
}; };
if (ground_return && (kind != SamKind::S400 || ground_request || ground_rounds == 0)) || (return_cargo && (kind != SamKind::Tzm || ground_stock == 0)) { return Err(l.bad("возврат RM48U", "несовместимое состояние")); } if (ground_return && (!supports_ground || ground_request || ground_rounds == 0)) || (return_cargo && (kind != SamKind::Tzm || ground_stock == 0)) { return Err(l.bad("возврат RM48U", "несовместимое состояние")); }
if radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar { if radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС")); return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
} }
@@ -164,14 +169,14 @@ impl Layout {
} }
// An old line has only the role: it migrates to the matching profile. // An old line has only the role: it migrates to the matching profile.
let radar_profile = radar_profile.or((kind == SamKind::Radar).then(|| sim::battery::RadarProfile::of(radar_role))); let radar_profile = radar_profile.or((kind == SamKind::Radar).then(|| sim::battery::RadarProfile::of(radar_role)));
if mode == sim::battery::SamMode::LauncherOnly && !matches!(kind, SamKind::S400 | SamKind::S500) { if mode == sim::battery::SamMode::LauncherOnly && !sim::catalog::has_separate_launcher(kind) {
return Err(l.bad("режим", "пусковая поддерживается только С-400 и С-500")); return Err(l.bad("режим", "отдельная пусковая для этого типа недоступна"));
} }
if (kind != SamKind::S400 && ground_rounds != 0) || (!matches!(kind, SamKind::Depot | SamKind::Tzm) && (ground_stock != 0 || air_48n6_stock != 0)) { if (!supports_ground && ground_rounds != 0) || (!matches!(kind, SamKind::Depot | SamKind::Tzm) && (ground_stock != 0 || air_48n6_stock != 0)) {
return Err(l.bad("боезапас", "несовместимый тип техники")); return Err(l.bad("боезапас", "несовместимый тип техники"));
} }
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 { if supports_ground && ammo.map_or(0, |(missiles, ..)| missiles) + ground_rounds > shared_cells {
return Err(l.bad("боезапас", "больше четырёх ячеек")); return Err(l.bad("боезапас", &format!("больше {shared_cells} ячеек")));
} }
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo }); out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo });
} }
@@ -188,6 +193,7 @@ impl Layout {
"strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))), "strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))),
"far" => out.far = l.flag(1, "значение")?, "far" => out.far = l.flag(1, "значение")?,
"acoustics" => out.acoustics = l.flag(1, "значение")?, "acoustics" => out.acoustics = l.flag(1, "значение")?,
"dlss" => out.dlss = l.flag(1, "значение")?,
"effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))), "effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))),
"seed" => { "seed" => {
let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?; let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?;
@@ -279,6 +285,15 @@ mod tests {
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects"); assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
} }
#[test]
fn the_dlss_request_round_trips_and_old_saves_keep_the_engine_default() {
assert_eq!(Layout::parse("dlss false\n").unwrap().dlss, Some(false));
assert_eq!(Layout::parse("dlss true\n").unwrap().dlss, Some(true));
assert!(Layout::parse("dlss maybe\n").is_err());
// Older saves have no line: the engine's own default (on) applies.
assert_eq!(Layout::parse("damage true\n").unwrap().dlss, None);
}
#[test] #[test]
fn radar_profile_ids_round_trip_and_old_roles_map_to_them() { fn radar_profile_ids_round_trip_and_old_roles_map_to_them() {
let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search"; let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search";
+865 -137
View File
File diff suppressed because it is too large Load Diff
+58 -3
View File
@@ -116,6 +116,7 @@ enum Act {
ResetDoc, ResetDoc,
Strike(u32), Strike(u32),
Centre, Centre,
Inspect,
Follow, Follow,
Rotate, Rotate,
Delete, Delete,
@@ -916,6 +917,28 @@ impl AirDef {
self.map.drag = None; self.map.drag = None;
} }
pub(crate) fn open_unit_map(&mut self, unit: u32, centre: bool) {
self.close_menu();
self.post.transition = Some((crate::post::Transition::Map { unit, centre }, false));
}
pub(crate) fn show_unit_on_map(&mut self, id: u32, centre: bool) {
let Some(sam) = self.sim.sams.iter().find(|sam| sam.id == id) else {
say("Комплекс уже убран");
return;
};
let pos = sam.pos;
if !self.map.open {
self.map_toggle();
}
self.map.sel = Some(Sel::Sam(id));
if centre {
self.map.centre = (pos.x, pos.z);
}
self.map.follow = false;
self.map.dirty = true;
}
/// Once a frame while the map is open. /// Once a frame while the map is open.
pub(crate) fn map_frame(&mut self) { pub(crate) fn map_frame(&mut self) {
if !self.map.open { if !self.map.open {
@@ -1321,6 +1344,14 @@ impl AirDef {
ui.centre = (p.x, p.z); ui.centre = (p.x, p.z);
} }
} }
Act::Inspect => {
if matches!(ui.mode, Mode::View)
&& let Some(Sel::Sam(id)) = ui.sel
{
self.post.transition = Some((crate::post::Transition::Card(id), false));
ui.close = true;
}
}
Act::Follow => { Act::Follow => {
if matches!(ui.sel, Some(Sel::Track(_))) { if matches!(ui.sel, Some(Sel::Track(_))) {
ui.follow = !ui.follow; ui.follow = !ui.follow;
@@ -1603,6 +1634,27 @@ impl AirDef {
ui.note(tick, "Бой идёт: расстановка закрыта"); ui.note(tick, "Бой идёт: расстановка закрыта");
return; return;
} }
if self.village_active() {
let objects_changed = ui.draft.objs.len() != self.sim.targets.len()
|| ui.draft.objs.iter().any(|o| o.gone
|| o.idx.and_then(|i| self.sim.targets.get(i)) != Some(&o.pos));
if objects_changed {
ui.note(tick, "Цели в «Обороне деревни» закреплены");
return;
}
let cost = |s: &DSam| crate::village::cost(s.kind);
let added = ui.draft.sams.iter().filter(|s| s.id.is_none() && !s.gone).map(cost).sum();
let removed: u32 = ui.draft.sams.iter()
.filter(|s| s.gone && s.id.is_some_and(|id| self.sim.sams.iter().any(|current| current.id == id)))
.map(cost).sum();
let kept = self.village_layout_cost().saturating_sub(removed);
if let Some(village) = &mut self.village
&& let Err(e) = village.charge(kept, added)
{
ui.note(tick, &e);
return;
}
}
let d = std::mem::take(&mut ui.draft); let d = std::mem::take(&mut ui.draft);
// Objects: removals from the end so the indices hold. // Objects: removals from the end so the indices hold.
let mut gone: Vec<usize> = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect(); let mut gone: Vec<usize> = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect();
@@ -2727,12 +2779,15 @@ impl AirDef {
let Some((n, sam)) = self.sim.sams.iter().enumerate().find(|(_, s)| s.id == id) else { return }; let Some((n, sam)) = self.sim.sams.iter().enumerate().find(|(_, s)| s.id == id) else { return };
let k = sam.kind; let k = sam.kind;
lines.push((format!("{} №{}", k.name(), n + 1), CYAN)); lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
if matches!(ui.mode, Mode::View) {
btns.push(("Карточка…".into(), Act::Inspect, false));
}
if k == SamKind::Radar { if k == SamKind::Radar {
let profile = sam.radar_profile(); let profile = sam.radar_profile();
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE)); lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
lines.push((crate::battery_view::radar_profile_line(profile), GREY)); lines.push((crate::battery_view::radar_profile_line(profile), GREY));
lines.push((format!("Ограничение: {}", profile.limit), GREY)); lines.push((format!("Ограничение: {}", profile.limit), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY)); lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(now), profile.channels), GREY));
} else if sam.mode == sim::battery::SamMode::LauncherOnly { } else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE)); lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
} }
@@ -2740,7 +2795,7 @@ impl AirDef {
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE)); lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on)); btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
} }
lines.push((crate::battery_view::sam_status(sam), WHITE)); lines.push((crate::battery_view::sam_status(sam, now), WHITE));
if k == SamKind::Optical if k == SamKind::Optical
&& let Some(r) = self.sim.optical_report(sam.id) && let Some(r) = self.sim.optical_report(sam.id)
{ {
@@ -2762,7 +2817,7 @@ impl AirDef {
lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE)); lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE));
} }
if k.armed() { if k.armed() {
if sam.kind == SamKind::S400 { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); } if sam.kind.supports_rm48u() { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); }
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE)); lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE)); lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE));
} }
+5 -5
View File
@@ -1,7 +1,7 @@
//! The air-defence monitor: a system's state, its radar's picture round it //! The air-defence monitor: a system's state, its radar's picture round it
//! and its camera (a real view of the world from the system, the game //! and its camera (a real view of the world from the system, the game
//! renders it) locked on its target. K shows one system at a time, J all of //! renders it) locked on its target. K shows one system at a time. The
//! them in a grid. //! command post can also open a grid of up to eight cameras.
use crate::panel::distance; use crate::panel::distance;
use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text}; use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text};
use glam::DVec3; use glam::DVec3;
@@ -21,7 +21,7 @@ fn quad(a: (f32, f32), b: (f32, f32), c: (f32, f32), d: (f32, f32), color: u32)
} }
/// `t` cut to `w` GUI pixels, with an ellipsis. /// `t` cut to `w` GUI pixels, with an ellipsis.
fn fit(t: String, w: f32) -> String { pub(crate) fn fit(t: String, w: f32) -> String {
if render::text_width(&t) <= w { if render::text_width(&t) <= w {
return t; return t;
} }
@@ -189,7 +189,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
format!("сеть · {seen}") format!("сеть · {seen}")
} else if radar_up { } else if radar_up {
let profile = sam.radar_profile(); let profile = sam.radar_profile();
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) }; let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(tick), profile.channels) };
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen) format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
} else { } else {
"РЛС ОТКАЗ".to_string() "РЛС ОТКАЗ".to_string()
@@ -312,7 +312,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
} else { } else {
if !matches!(sam.kind, SamKind::Gepard) { if !matches!(sam.kind, SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles); line += &format!("Р{} ", sam.missiles);
if sam.kind == SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); } if sam.kind.supports_rm48u() { line += &format!("У{} ", sam.ground_rounds); }
} }
if crate::sim::catalog::unit(sam.kind).has_gun() { if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts); line += &format!("Оч{} ", sam.bursts);
+175 -38
View File
@@ -5,14 +5,22 @@
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them. //! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
//! Letting the key go hides everything. The markers are projected through the camera the last //! Letting the key go hides everything. The markers are projected through the camera the last
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn. //! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
//! Visibility comes before the draw budget (#141): each layer projects at most a bounded number
//! of its nearest candidates, keeps the markers of the nearest visible ones, and counts a target
//! that leaves the frame without spending a slot.
use crate::panel::distance; use crate::panel::distance;
use crate::sim::{ClassEst, Sim, Track}; use crate::sim::{ClassEst, Sim, Track};
use glam::DVec3; use glam::DVec3;
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape}; use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
/// The most markers of one picture (the network's and the truth's each): a full raid still fits /// The most markers of one picture (the network's, the truth's and the interceptors' each): a full
/// the HUD's 1024 shapes — a marker is four sides and a label. /// raid still fits the HUD's 1024 shapes — a marker is four sides and a label.
const MAX_MARKERS: usize = 64; const MAX_MARKERS: usize = 64;
/// The most candidates of one layer the frame looks at: the nearest ones by distance. The draw
/// budget is spent on what is in frame, but the projection work stays bounded — a crowd the frame
/// does not hold cannot buy an unbounded scan, and what the scan never reaches counts as past the
/// budget rather than out of the frame.
const MAX_SCAN: usize = 4 * MAX_MARKERS;
/// A marker's side thickness, pixels. /// A marker's side thickness, pixels.
const LINE: f32 = 1.0; const LINE: f32 = 1.0;
/// A label line's height (the HUD font with its shadow). /// A label line's height (the HUD font with its shadow).
@@ -86,6 +94,50 @@ fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
} }
} }
/// What one layer shows this frame: the markers to draw (the nearest visible candidates), how
/// many of the scanned candidates left the frame, and how many the budgets left out.
struct Pick<T> {
marks: Vec<(T, Point, f32)>,
offscreen: usize,
capped: usize,
}
/// The markers one layer gets this frame. The candidates are ordered nearest the player first and
/// at most [`MAX_SCAN`] of them are projected; a candidate the frame does not hold (behind the
/// camera or past an edge) is counted and its slot stays free for the next, so the nearest
/// [`MAX_MARKERS`] visible candidates are drawn. Work stays bounded by the scan, not the picture.
fn pick<T: Copy>(
items: impl Iterator<Item = T>,
at: impl Fn(T) -> DVec3,
half_at: impl Fn(T) -> f32,
player: DVec3,
gui: (f32, f32),
project: &impl Fn(DVec3) -> Option<Point>,
) -> Pick<T> {
let near = |a: &T, b: &T| at(*a).distance(player).total_cmp(&at(*b).distance(player));
let mut items: Vec<T> = items.collect();
let total = items.len();
// Only the nearest candidates are ever projected: no sort of the whole picture is needed.
if items.len() > MAX_SCAN {
items.select_nth_unstable_by(MAX_SCAN, near);
items.truncate(MAX_SCAN);
}
items.sort_by(near);
let mut marks = Vec::new();
let mut offscreen = 0usize;
for it in items {
if marks.len() >= MAX_MARKERS {
break;
}
let h = half_at(it);
match project(at(it)) {
Some(p) if p.x >= h && p.x <= gui.0 - h && p.y >= h && p.y <= gui.1 - h => marks.push((it, p, h)),
_ => offscreen += 1,
}
}
Pick { capped: total - marks.len() - offscreen, marks, offscreen }
}
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn /// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
/// frame's camera); a point behind the camera projects to None, a point off the screen still /// frame's camera); a point behind the camera projects to None, a point off the screen still
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held. /// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
@@ -97,20 +149,17 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
let pic = sim.air_picture(); let pic = sim.air_picture();
let now = pic.now; let now = pic.now;
let truth = sim.truth && !pic.unaided; let truth = sim.truth && !pic.unaided;
// The network's tracks, nearest first: a full raid keeps the closest markers. // The frame's counts: what got a marker and what did not — out of the frame (behind the camera
let mut tracks: Vec<&Track> = pic.tracks.iter().collect(); // or past an edge) or past the budget. The header keeps the two apart (#141).
tracks.sort_by(|a, b| a.est(now).distance(player).total_cmp(&b.est(now).distance(player)));
let mut shown = 0usize; let mut shown = 0usize;
let mut hidden = tracks.len().saturating_sub(MAX_MARKERS); let mut offscreen = 0usize;
for t in tracks.into_iter().take(MAX_MARKERS) { let mut capped = 0usize;
let e = t.est(now); // The network's tracks: the nearest visible keep the markers; a target behind the camera no
let dist = e.distance(player); // longer spends one, so a crowd behind cannot crowd out the target in frame.
let Some(p) = project(e) else { hidden += 1; continue }; let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project);
let h = half(dist); offscreen += net.offscreen;
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h { capped += net.capped;
hidden += 1; for (t, p, h) in net.marks {
continue;
}
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours). // Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
let (color, a) = if pic.unaided { let (color, a) = if pic.unaided {
(RED, 1.0) (RED, 1.0)
@@ -128,16 +177,17 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
// with the actual type the network never shows. A tracked drone wears both: the network's // with the actual type the network never shows. A tracked drone wears both: the network's
// estimate under the square, the truth over it — the offset between them is the point. // estimate under the square, the truth over it — the offset between them is the point.
if truth { if truth {
let mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect(); let real = pick(
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player))); sim.drones.iter().filter(|d| d.alive()),
hidden += drones.len().saturating_sub(MAX_MARKERS); |d| d.pos,
for d in drones.into_iter().take(MAX_MARKERS) { |d| half(d.pos.distance(player)) + 2.0,
let Some(p) = project(d.pos) else { hidden += 1; continue }; player,
let h = half(d.pos.distance(player)) + 2.0; gui,
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h { &project,
hidden += 1; );
continue; offscreen += real.offscreen;
} capped += real.capped;
for (d, p, h) in real.marks {
s.extend(square_outline(p.x, p.y, h, WHITE)); s.extend(square_outline(p.x, p.y, h, WHITE));
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player))); let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true)); s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
@@ -145,24 +195,18 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
} }
} }
// The player's own interceptors: small yellow squares, no label — they are not targets, and // The player's own interceptors: small yellow squares, no label — they are not targets, and
// the network never hid them (the radar has always shown them). // the network never hid them (the radar has always shown them). They keep their own budget.
let mut missiles: Vec<_> = sim.missiles.iter().collect(); let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project);
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player))); for (_, p, h) in own.marks {
for m in missiles.into_iter().take(MAX_MARKERS) {
let Some(p) = project(m.pos) else { continue };
let h = MISSILE_HALF;
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
continue;
}
s.extend(square_outline(p.x, p.y, h, MISSILE)); s.extend(square_outline(p.x, p.y, h, MISSILE));
} }
// The mode, named as the map names it: the network's data by default, the sandbox's truth // The mode, named as the map names it: the network's data by default, the sandbox's truth
// explicitly marked. The counts say what the frame holds and what stayed behind the camera // explicitly marked. The counts say what the frame holds, what left it, and what the budget cut.
// or past the edges. let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}");
let head = if truth { let head = if truth {
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}") format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}")
} else { } else {
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}") format!("ОБЗОР · данные сети РЛС · {counts}")
}; };
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true)); s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
s s
@@ -201,6 +245,17 @@ mod tests {
}).collect() }).collect()
} }
fn head(shapes: &[Shape]) -> String {
texts(shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).expect("no header").text.clone()
}
/// `n` targets in a row right behind the camera, each nearer than anything the tests put ahead.
fn crowd_behind(sim: &mut Sim, n: u32) {
for i in 0..n {
sim.launch(DroneKind::Shahed, DVec3::new(i as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
}
#[test] #[test]
fn a_visible_target_gets_a_square_and_a_short_line() { fn a_visible_target_gets_a_square_and_a_short_line() {
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0)); let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
@@ -282,6 +337,88 @@ mod tests {
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS); assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
} }
/// #141: 64 targets behind the camera and one in frame. The budget used to be spent on the
/// crowd before the visibility check, so the picture came out empty; the target in frame must
/// keep its marker, and the crowd is out of frame, not past the budget.
#[test]
fn a_crowd_behind_the_camera_leaves_the_network_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, RED), 4, "the target in frame got no marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The truth layer keeps its own budget the same way: the real drone in frame is drawn, the
/// crowd behind the camera costs no white marker.
#[test]
fn a_crowd_behind_the_camera_leaves_the_truth_budget_to_the_target_in_frame() {
let mut sim = Sim::new(1);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.truth = true;
crowd_behind(&mut sim, 64);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 4, "the drone in frame got no truth marker");
assert_eq!(fills(&shapes, RED), 0, "the network drew a track it does not hold");
assert_eq!(head(&shapes), "ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре 1, за кадром 64, сверх бюджета 0");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The interceptors keep their own budget too: a salvo behind the camera leaves the marker
/// to the one in frame.
#[test]
fn a_crowd_behind_the_camera_leaves_the_interceptor_budget_to_the_one_in_frame() {
let mut sim = Sim::new(1);
for i in 0..64 {
sim.missiles.push(crate::sim::Missile::test_at(i + 1, DVec3::new(i as f64, 64.0, -50.0), 0));
}
sim.missiles.push(crate::sim::Missile::test_at(100, DVec3::new(0.0, 64.0, 100.0), 0));
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, MISSILE), 4, "the interceptor in frame got no marker");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The header tells what really left the frame from what the draw budget cut, and the markers
/// go to the nearest of the visible: 64 behind the camera, 65 in frame.
#[test]
fn the_header_separates_the_frames_edge_from_the_draw_budget() {
let mut sim = Sim::new(1);
crowd_behind(&mut sim, 64);
for i in 0..65 {
let z = 100.0 + i as f64 * 10.0;
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, z), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
}
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
// The 64 nearest in frame are drawn; the farthest one is past the draw budget, not out of frame.
assert_eq!(fills(&shapes, RED), 4 * MAX_MARKERS);
assert!(texts(&shapes).iter().any(|t| t.text.contains("100 м")), "the nearest visible lost its marker");
assert!(!texts(&shapes).iter().any(|t| t.text.contains("740 м")), "the farthest visible took a nearer one's marker");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 64, за кадром 64, сверх бюджета 1");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
/// The projection work itself is bounded: with more candidates than the scan budget, only the
/// nearest `MAX_SCAN` are looked at, and the rest are counted as past the budget.
#[test]
fn the_projection_work_is_bounded_by_the_scan_budget() {
let mut sim = Sim::new(1);
for i in 0..1000 {
sim.launch(DroneKind::Shahed, DVec3::new((i % 100) as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
}
let calls = std::cell::Cell::new(0usize);
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, |p| {
calls.set(calls.get() + 1);
ahead(p)
});
assert_eq!(calls.get(), MAX_SCAN, "one layer projected more than its scan budget");
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 0, за кадром 256, сверх бюджета 744");
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
}
#[test] #[test]
fn interceptors_wear_small_yellow_squares_without_labels() { fn interceptors_wear_small_yellow_squares_without_labels() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0)); let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
+2 -2
View File
@@ -127,9 +127,9 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
} }
for sam in sim.sams.iter().take(shown) { for sam in sim.sams.iter().take(shown) {
let mut text = if sam.kind.armed() { let mut text = if sam.kind.armed() {
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles)) format!("{} [{}]", crate::battery_view::sam_status(sam, now), crate::sim::roles_text(sam.roles))
} else { } else {
crate::battery_view::sam_status(sam) crate::battery_view::sam_status(sam, now)
}; };
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) { if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos))); text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
+302
View File
@@ -0,0 +1,302 @@
//! The command post lists every deployed unit without requesting camera views.
use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole, decision, record::Recording};
/// Keep enough room under the engine's 512-row limit for large layouts.
pub const PAGE_SIZE: usize = 200;
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub enum Filter {
#[default]
All,
Weapons,
Sensors,
Support,
InCombat,
NoAmmo,
NoLink,
Damaged,
}
impl Filter {
const ALL: [Self; 8] = [
Self::All, Self::Weapons, Self::Sensors, Self::Support, Self::InCombat,
Self::NoAmmo, Self::NoLink, Self::Damaged,
];
pub fn next(self) -> Self {
Self::ALL[(self as usize + 1) % Self::ALL.len()]
}
pub fn label(self) -> &'static str {
match self {
Self::All => "Все",
Self::Weapons => "Огневые",
Self::Sensors => "Наблюдение",
Self::Support => "Поддержка",
Self::InCombat => "В работе",
Self::NoAmmo => "Без боезапаса",
Self::NoLink => "Отказ связи",
Self::Damaged => "Повреждённые",
}
}
fn matches(self, sam: &Sam) -> bool {
let sensor = matches!(sam.kind, SamKind::Radar | SamKind::Optical);
match self {
Self::All => true,
Self::Weapons => sam.kind.armed(),
Self::Sensors => sensor,
Self::Support => !sam.kind.armed() && !sensor,
Self::InCombat => sam.alive() && (
matches!(sam.state, SamState::Track | SamState::Slew | SamState::Lock | SamState::Launch | SamState::Fire)
|| sam.ew_on
|| (sensor && !sam.own.is_empty())
|| (sam.kind == SamKind::Optical && sam.optical.state() == crate::sim::OpticalState::Observing)
),
Self::NoAmmo => sam.alive() && sam.kind.armed() && sam.missiles == 0 && sam.bursts == 0,
Self::NoLink => sam.alive() && Part::Comms.on(sam.kind) && sam.part_state(Part::Comms) == PartState::Failed,
Self::Damaged => sam.health < 1.0 || !sam.comps.whole(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum From {
World,
Post,
Map(u32),
Monitor,
Source,
}
#[derive(Clone, Copy)]
pub enum Action {
Checks,
Map,
Camera,
Source(u32),
Pin,
History,
LatestDecision,
}
pub enum Transition {
Map { unit: u32, centre: bool },
Card(u32),
}
#[derive(Default)]
pub struct Post {
pub filter: Filter,
pub query: String,
pub page: usize,
pub pinned: Option<u32>,
/// IDs and actions exactly as shown in the screen, even if the sim advances before a click.
pub shown: Vec<u32>,
pub actions: Vec<Action>,
pub decisions: Vec<RecordedChoice>,
pub source_origin: Option<(u32, From)>,
/// Let the client finish closing one screen before opening a different kind.
pub transition: Option<(Transition, bool)>,
}
#[derive(Clone, Copy)]
pub struct RecordedChoice {
pub raid: u32,
pub entry: decision::Entry,
}
pub fn recorded_choices<'a>(recordings: impl Iterator<Item = &'a Recording> + 'a, unit: u32) -> impl Iterator<Item = RecordedChoice> + 'a {
recordings.flat_map(move |rec| rec.decisions.entries().rev()
.filter(move |entry| entry.unit == unit)
.map(move |&entry| RecordedChoice { raid: rec.number, entry }))
}
pub fn decision_label(outcome: decision::Outcome) -> &'static str {
use decision::{Block as B, Outcome as O};
match outcome {
O::Held(B::Hold) => "Огонь запрещён",
O::Held(B::Moving) => "Комплекс на марше",
O::Held(B::Reload) => "Перезарядка",
O::Held(B::Empty) => "Ожидает пополнения",
O::Held(B::NoSelection) => "Цель не назначена",
O::Held(B::WaitingForTerrain) => "Ожидает данных о рельефе",
O::Held(B::Terrain) => "Траектория перекрыта",
O::Held(B::Aim) => "Доворачивается",
O::Held(B::Opening) => "Открывает ТПК",
O::Held(B::BusyWithGroundShot) => "Готовит наземный пуск",
O::Held(B::Cooldown) => "Пауза между выстрелами",
O::Held(B::GunFault) => "Орудие недоступно",
O::Held(B::LauncherFault) => "Пусковая недоступна",
O::Held(B::NoLock) => "Нет свежего захвата",
O::Held(B::Range) => "Вне дальности орудия",
O::Burst => "Очередь выпущена",
O::BurstMissed => "Промах очереди",
O::BurstHit | O::Intercepted(_) => "Цель сбита",
O::Launched(_) => "Ракета выпущена",
O::InterceptorMissed(_) => "Промах перехватчика",
O::InterceptorEnded(_) => "Полёт перехватчика завершён",
}
}
pub fn decision_lines(choice: RecordedChoice, rec: Option<&Recording>) -> Vec<String> {
use decision::{Channel, Outcome};
let entry = choice.entry;
let channel = match entry.channel {
Channel::Launcher => "Пусковая",
Channel::Gun => "Орудие",
Channel::Unit => "Комплекс",
};
let mut lines = vec![
format!("Налёт №{} · {} · {channel}", choice.raid, crate::replay::clock(f64::from(entry.at))),
format!("На тот момент · {}", decision_label(entry.outcome)),
];
if matches!(entry.outcome, Outcome::Held(_)) {
lines.push("На этой проверке выстрела не было".to_owned());
}
if let Some(target) = entry.target {
lines.push(format!("Трек №{target}"));
}
if let Some(mark) = entry.mark {
let source = if mark.own { "своя отметка".to_owned() } else {
rec.and_then(|rec| rec.sams.iter().position(|s| s.0 == mark.source))
.map_or_else(|| format!("источник ID {}", mark.source), |i| format!("источник №{}", i + 1))
};
lines.push(format!("{source} · {:.1} с назад", f64::from(mark.age) / 20.0));
lines.push(format!("{} · {} · качество {}", mark.product.name(), mark.class.name(), mark.quality));
}
if let Outcome::Launched(id) | Outcome::Intercepted(id) | Outcome::InterceptorMissed(id) | Outcome::InterceptorEnded(id) = entry.outcome {
lines.push(format!("Перехватчик ID {id}"));
}
lines
}
impl Post {
pub fn matching(&self, sams: &[Sam]) -> Vec<usize> {
let number = self.query.trim_start_matches('№').parse::<usize>().ok();
let mut rows: Vec<_> = sams.iter().enumerate()
.filter(|(i, sam)| self.filter.matches(sam) && (self.query.is_empty()
|| number == Some(i + 1)
|| sam.kind.key().contains(&self.query)
|| sam.kind.name().to_lowercase().contains(&self.query)))
.map(|(i, _)| i)
.collect();
if let Some(i) = rows.iter().position(|&i| self.pinned == Some(sams[i].id)) {
let pinned = rows.remove(i);
rows.insert(0, pinned);
}
rows
}
}
pub fn state(sam: &Sam) -> &'static str {
if !sam.alive() {
return "Уничтожен";
}
if sam.moving() {
return sam.state.name();
}
match sam.kind {
SamKind::Optical => sam.optical.state().name(),
SamKind::Radar if !sam.radar_on => "Излучение выкл.",
SamKind::Radar if !sam.radar_up() => "РЛС недоступна",
SamKind::Radar if !sam.own.is_empty() => "Есть отметки",
SamKind::Ew if sam.ew_on => "Активна",
SamKind::Ew | SamKind::Depot | SamKind::Tzm | SamKind::Light => "На позиции",
_ => sam.state.name(),
}
}
pub fn row(sam: &Sam, index: usize, pinned: bool) -> String {
let name = match sam.kind {
SamKind::Radar => match sam.radar_role {
RadarRole::Search => "РЛС обзора",
RadarRole::Engagement => "РЛС сопровождения",
RadarRole::Height => "РЛС высоты",
RadarRole::Multifunction => "РЛС",
},
SamKind::Depot => "Склад",
_ => sam.kind.name(),
};
let status = if Filter::NoLink.matches(sam) {
"Нет связи"
} else if Filter::NoAmmo.matches(sam) && sam.reloading == 0 {
"Нет БК"
} else {
state(sam)
};
let pin = if pinned { "★ " } else { "" };
let health = if sam.alive() && Filter::Damaged.matches(sam) {
format!(" · {:.0}%", sam.health * 100.0)
} else {
String::new()
};
format!("{pin}№{} {name} · {status}{health}", index + 1)
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DVec3;
#[test]
fn the_post_includes_support_and_searches_names_keys_and_shown_numbers() {
let sams = [
Sam::new(77, SamKind::Pantsir, DVec3::ZERO, 0.0),
Sam::new(90, SamKind::Depot, DVec3::ZERO, 0.0),
Sam::new(23, SamKind::Radar, DVec3::ZERO, 0.0),
];
let mut post = Post { pinned: Some(23), ..Post::default() };
assert_eq!(post.matching(&sams), [2, 0, 1]);
for (query, expected) in [("панц", 0), ("depot", 1), ("№3", 2)] {
post.query = query.to_string();
assert_eq!(post.matching(&sams), [expected]);
}
post.query.clear();
post.filter = Filter::Support;
assert_eq!(post.matching(&sams), [1]);
assert_eq!(post.pinned, Some(23));
}
#[test]
fn availability_filters_distinguish_empty_worn_and_destroyed_units() {
let mut ready = Sam::new(15, SamKind::Pantsir, DVec3::ZERO, 0.0);
ready.missiles = 0;
ready.bursts = 0;
ready.comps.0[Part::Comms as usize] = 0.0;
assert!(Filter::NoAmmo.matches(&ready));
assert!(Filter::NoLink.matches(&ready));
assert!(Filter::Damaged.matches(&ready));
assert!(row(&ready, 0, true).starts_with("★ №1"));
ready.health = 0.0;
assert!(!Filter::NoAmmo.matches(&ready));
assert!(!Filter::NoLink.matches(&ready));
assert_eq!(state(&ready), "Уничтожен");
assert!(Filter::Damaged.matches(&ready));
}
#[test]
fn historical_details_use_the_recorded_station_and_separate_a_miss_from_a_refusal() {
let mut rec = Recording::blank(100);
rec.sams = vec![(96, SamKind::S400, DVec3::ZERO), (48, SamKind::Radar, DVec3::X)];
let entry = decision::Entry {
unit: 96,
at: 40,
target: Some(112),
channel: decision::Channel::Launcher,
outcome: decision::Outcome::Held(decision::Block::Terrain),
mark: Some(decision::Mark {
source: 48, age: 12, own: false, quality: 62,
product: crate::sim::battery::Measure::Search,
class: crate::sim::ClassEst::Unknown,
}),
};
let lines = decision_lines(RecordedChoice { raid: 2, entry }, Some(&rec));
assert!(lines.iter().any(|line| line == "источник №2 · 0.6 с назад"));
assert!(lines.iter().any(|line| line.contains("выстрела не было")));
let missed = decision::Entry { outcome: decision::Outcome::InterceptorMissed(144), mark: None, ..entry };
let lines = decision_lines(RecordedChoice { raid: 2, entry: missed }, None);
assert!(lines.iter().any(|line| line.contains("Промах перехватчика")));
assert!(!lines.iter().any(|line| line.contains("выстрела не было")));
}
}
+21 -5
View File
@@ -80,7 +80,7 @@ pub fn intent_name(intent: &str) -> &'static str {
/// and the priority the planner prices it at. /// and the priority the planner prices it at.
pub fn mark_line(m: &ReconReport) -> String { pub fn mark_line(m: &ReconReport) -> String {
let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default(); let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default();
format!( let mut line = format!(
"Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}", "Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}",
m.id, m.id,
category_name(m.category), category_name(m.category),
@@ -90,7 +90,11 @@ pub fn mark_line(m: &ReconReport) -> String {
confidence_name(m.confidence), confidence_name(m.confidence),
m.age / 20, m.age / 20,
m.priority m.priority
) );
if m.launches != 0 {
line.push_str(&format!(" · замечено пусков {}", m.launches));
}
line
} }
/// Why the mark has the priority it does: the observed role, the freshness and the quality, each /// Why the mark has the priority it does: the observed role, the freshness and the quality, each
@@ -182,7 +186,7 @@ pub fn picture_lines(pic: &EnemyPictureReport) -> Vec<String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport}; use crate::sim::{AimReport, BearingReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport};
use glam::DVec3; use glam::DVec3;
fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport { fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport {
@@ -190,7 +194,7 @@ mod tests {
let qual = Quality::from_key(quality).unwrap(); let qual = Quality::from_key(quality).unwrap();
let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key); let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key);
let (f, q, r) = priority_parts(confidence, qual, cat, role_enum); let (f, q, r) = priority_parts(confidence, qual, cat, role_enum);
ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r } ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", launches: 0, age, quality, confidence, live: true, priority: f * 4 + q * 3 + r }
} }
fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport { fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport {
@@ -198,7 +202,19 @@ mod tests {
} }
fn picture(recon: Vec<ReconReport>, recon_sorties: Vec<ReconSortieReport>, aims: Vec<AimReport>) -> EnemyPictureReport { fn picture(recon: Vec<ReconReport>, recon_sorties: Vec<ReconSortieReport>, aims: Vec<AimReport>) -> EnemyPictureReport {
EnemyPictureReport { now: 1000, contacts: Vec::new(), aims, pending: Vec::new(), work_per_tick: 4, recon, recon_sorties } EnemyPictureReport {
now: 1000,
contacts: Vec::new(),
aims,
pending: Vec::new(),
work_per_tick: 4,
recon,
recon_sorties,
observations: Vec::new(),
bearing: BearingReport::default(),
refresh_waiting: false,
refresh_applied: 0,
}
} }
// The reason names all three factors with the planner's own weights, and they sum to the priority. // The reason names all three factors with the planner's own weights, and they sum to the priority.
+327 -31
View File
@@ -9,7 +9,7 @@ use crate::sim::catalog::sound;
use crate::film::{self, Film}; use crate::film::{self, Film};
use crate::panel::distance; use crate::panel::distance;
use crate::sim::Ground; use crate::sim::Ground;
use crate::sim::record::{EventKind, Recording, STEP, StrikeResult, What}; use crate::sim::record::{Chain, ChainOutcome, ChainStepKind, EventKind, Recording, STEP, StrikeResult, What};
use std::cell::Cell; use std::cell::Cell;
use crate::sim::{Class, DroneKind, Out, Sim}; use crate::sim::{Class, DroneKind, Out, Sim};
use glam::DVec3; use glam::DVec3;
@@ -124,7 +124,7 @@ fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape {
let p = |x: f32, y: f32| Point { x, y }; let p = |x: f32, y: f32| Point { x, y };
Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color }) Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color })
} }
fn clock(ticks: f64) -> String { pub(crate) fn clock(ticks: f64) -> String {
let s = (ticks / 20.0).max(0.0); let s = (ticks / 20.0).max(0.0);
format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0) format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0)
} }
@@ -187,6 +187,121 @@ pub fn row(rec: &Recording, i: usize) -> String {
format!("{} {what}", clock(e.at as f64)) format!("{} {what}", clock(e.at as f64))
} }
/// A row of the after-action chain list and where a click on it opens a replay.
#[derive(Clone, Debug, PartialEq)]
pub struct ChainRow {
pub text: String,
/// The recorded event to clip (the outcome), when there is one.
pub event: Option<usize>,
/// Otherwise the recording's tick to open the map at (the launch, else the mark).
pub at: f64,
}
/// The short chains of a raid: отметка → передача → захват → пуск → исход, filtered by a
/// battery's id when asked. The list is the recording's measured transitions, not a guess.
pub fn chain_rows(rec: &Recording, battery: Option<u32>) -> Vec<ChainRow> {
chain_page(rec, battery, ChainFilter::All, 0, usize::MAX).rows
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum ChainFilter {
#[default]
All,
NoLaunch,
Breach,
}
impl ChainFilter {
pub fn next(self) -> Self {
match self {
Self::All => Self::NoLaunch,
Self::NoLaunch => Self::Breach,
Self::Breach => Self::All,
}
}
pub fn label(self) -> &'static str {
match self {
Self::All => "Все цепочки",
Self::NoLaunch => "Без записи пуска",
Self::Breach => "Прорывы",
}
}
fn matches(self, chain: &Chain) -> bool {
match self {
Self::All => true,
Self::NoLaunch => chain.missed(),
Self::Breach => chain.outcome == ChainOutcome::Hit,
}
}
}
#[derive(Default)]
pub(crate) struct ChainPage {
pub rows: Vec<ChainRow>,
pub total: usize,
pub index: usize,
}
pub(crate) fn chain_page(rec: &Recording, battery: Option<u32>, filter: ChainFilter, page: usize, size: usize) -> ChainPage {
let mut chains = rec.chains(battery);
chains.retain(|chain| filter.matches(chain));
let total = chains.len();
let index = page.min(total.div_ceil(size).saturating_sub(1));
let rows = chains.iter().skip(index * size).take(size).map(|chain| ChainRow {
text: chain_row(rec, chain),
event: chain.outcome_event(),
at: chain_jump_at(chain),
}).collect();
ChainPage { rows, total, index }
}
/// Where a chain opens in a replay when its outcome has no recorded event.
fn chain_jump_at(chain: &Chain) -> f64 {
chain
.step(ChainStepKind::Launch)
.or_else(|| chain.step(ChainStepKind::Mark))
.map_or(0.0, |s| s.at as f64)
}
fn chain_step_name(chain: &Chain, kind: ChainStepKind, own: bool) -> &'static str {
match kind {
ChainStepKind::Mark => "отметка",
ChainStepKind::Handoff if own => "передача (своя РЛС)",
ChainStepKind::Handoff => "передача (сеть)",
ChainStepKind::Lock => "захват",
ChainStepKind::Launch => "пуск",
ChainStepKind::Outcome => match chain.outcome {
ChainOutcome::Destroyed => "сбит",
ChainOutcome::Hit => "прорыв",
ChainOutcome::Lost => "потерян",
ChainOutcome::Unfinished => "без исхода",
},
}
}
/// One chain as a line: the battery, its contact, and the four or five measured steps.
pub fn chain_row(rec: &Recording, chain: &Chain) -> String {
let index = rec.sams.iter().position(|s| s.0 == chain.sam).map(|i| i + 1);
let kind = rec.sam(chain.sam).map_or("ПВО", |(kind, _)| kind.name());
let target = rec
.track(chain.target)
.and_then(|t| match t.what {
What::Drone(kind) => Some(kind.spec().name),
_ => None,
})
.unwrap_or("цель");
let steps: Vec<String> = chain.steps.iter().map(|s| format!("{} {}", chain_step_name(chain, s.kind, s.own), clock(s.at as f64))).collect();
let battery = index.map_or_else(|| format!("№? {kind}"), |i| format!("№{i} {kind}"));
format!(
"{} {battery} → «{target}»: {}{}",
clock(chain.marked_at() as f64),
steps.join(" → "),
if chain.missed() { " · пуск не записан" } else { "" },
)
}
/// How worth watching an event is: the reel takes the best. /// How worth watching an event is: the reel takes the best.
pub fn interest(rec: &Recording, i: usize) -> f64 { pub fn interest(rec: &Recording, i: usize) -> f64 {
let e = &rec.events[i]; let e = &rec.events[i];
@@ -299,6 +414,16 @@ impl Player {
} }
} }
/// Opens the replay at a recording tick (a chain's launch or mark), holding that frame.
pub fn seek(&mut self, rec: &Recording, at: f64) {
self.t = at.clamp(0.0, rec.len as f64);
self.heard = self.t;
self.shot = (usize::MAX, 0);
self.fade = 0;
self.card = 0;
self.paused = true;
}
/// The wheel: scrubs the map and the full replay, skips clips. /// The wheel: scrubs the map and the full replay, skips clips.
pub fn wheel(&mut self, steps: f32, rec: &Recording) { pub fn wheel(&mut self, steps: f32, rec: &Recording) {
let c = if steps > 0.0 { Control::Back } else { Control::Forward }; let c = if steps > 0.0 { Control::Back } else { Control::Forward };
@@ -525,7 +650,7 @@ impl Player {
/// Sounds as the camera hears them: moved so the player stands where the camera is. /// Sounds as the camera hears them: moved so the player stands where the camera is.
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) { fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
let heard = |p: DVec3| listener + (p - self.eye); let heard = |p: DVec3| listener + (p - self.eye);
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) { for (_, e) in rec.events_between(self.heard, self.t) {
let event = match e.kind { let event = match e.kind {
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3, EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)], EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
@@ -546,7 +671,7 @@ impl Player {
} }
// New recordings carry the exact launch and ignition sounds and their actual positions. // New recordings carry the exact launch and ignition sounds and their actual positions.
if let Some(scene) = &rec.scene { if let Some(scene) = &rec.scene {
for e in scene.events().iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) { for e in scene.events_between(self.heard, self.t) {
match e.kind { match e.kind {
crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch), crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch),
crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0), crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0),
@@ -773,9 +898,9 @@ impl Player {
// The full replay follows what comes next: the next event within 6 s, else the drone // The full replay follows what comes next: the next event within 6 s, else the drone
// nearest its target. // nearest its target.
Mode::Full => rec Mode::Full => rec
.events .events_between(self.t - 30.0, self.t + 120.0)
.iter() .next()
.position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64))) .map(|(i, _)| i)
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }), .or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
Mode::Map | Mode::Film(_) => None, Mode::Map | Mode::Film(_) => None,
}; };
@@ -973,11 +1098,11 @@ impl Player {
What::Missile(..) => (0x90FFD040, 0xFFFFE070), What::Missile(..) => (0x90FFD040, 0xFFFFE070),
What::Strike | What::StrikeCarrier(_) => (0x90FFA040, 0xFFFFC060), What::Strike | What::StrikeCarrier(_) => (0x90FFA040, 0xFFFFC060),
}; };
let upto = ((self.t - tr.first as f64) / STEP as f64).floor(); let upto = ((self.t - tr.first as f64) / tr.step() as f64).floor();
if upto < 0.0 { if upto < 0.0 {
continue; continue;
} }
let last = ((tr.last() - tr.first) / STEP) as f64; let last = ((tr.last() - tr.first) / tr.step()) as f64;
let count = upto.min(last) as usize + 1; let count = upto.min(last) as usize + 1;
if count < 2 { if count < 2 {
continue; continue;
@@ -999,29 +1124,13 @@ impl Player {
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head)); s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
} }
} }
// Events so far. // Events so far, in their order. The header's counts come from the recording's prefix
for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) { // index, not from walking the journal again; past the shape cap nothing drawn here
let (x, y) = at(e.pos); // survives `truncate`.
if !inside((x, y)) { s.extend(event_marks(rec, self.t, &at, &inside, 1024usize.saturating_sub(s.len())));
continue;
}
match e.kind {
EventKind::Kill { .. } => {
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
}
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
let r = 2.0 + power as f32;
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
}
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
}
}
// Header, legend, time line. // Header, legend, time line.
let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count(); let kills = rec.kills_until(self.t);
let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count(); let hits = rec.hits_until(self.t);
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) }; let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false)); s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт"; let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
@@ -1040,6 +1149,10 @@ impl Player {
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF)); s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
let len = rec.len.max(1) as f32; let len = rec.len.max(1) as f32;
for e in &rec.events { for e in &rec.events {
// The line is cut at 1024 shapes: past that, a mark would not be kept.
if s.len() >= 1024 {
break;
}
let x = tx + tw * e.at as f32 / len; let x = tx + tw * e.at as f32 / len;
let c = match e.kind { let c = match e.kind {
EventKind::Kill { .. } => 0xFFFFE040, EventKind::Kill { .. } => 0xFFFFE040,
@@ -1057,6 +1170,42 @@ impl Player {
} }
} }
/// The marks of the events up to `t` on the raid map, in the order they happened: a kill as a
/// cross, a hit as a square, a lost system as a dark square, a split and a strike as dots. Reads
/// the journal by time (`events_until`) and stops at `room` shapes, the rest of the map's cap.
fn event_marks(
rec: &Recording,
t: f64,
at: &impl Fn(DVec3) -> (f32, f32),
inside: &impl Fn((f32, f32)) -> bool,
room: usize,
) -> Vec<Shape> {
let mut s = Vec::new();
for (_, e) in rec.events_until(t) {
if s.len() >= room {
break;
}
let (x, y) = at(e.pos);
if !inside((x, y)) {
continue;
}
match e.kind {
EventKind::Kill { .. } => {
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
}
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
let r = 2.0 + power as f32;
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
}
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
}
}
s
}
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that /// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
/// flew (not the ballistic falls), with the systems and objects, or round the /// flew (not the ballistic falls), with the systems and objects, or round the
/// origin when nothing did. /// origin when nothing did.
@@ -1102,6 +1251,69 @@ impl Player {
mod surface_tests { mod surface_tests {
use super::*; use super::*;
#[test]
fn a_chain_row_lists_the_measured_steps_and_opens_its_frame() {
use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind};
use crate::sim::outcome::Outcome;
use crate::sim::MissileKind;
let mut rec = Recording::blank(300);
rec.sams = vec![(10, crate::sim::SamKind::Pantsir, DVec3::ZERO)];
rec.straight(7, What::Drone(DroneKind::Shahed), 0, 200, DVec3::new(0.0, 80.0, 0.0), DVec3::new(200.0, 80.0, 0.0));
let mut scene = SceneJournal::default();
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
scene.fixture_push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
scene.fixture_push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
scene.fixture_push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
scene.fixture_push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
rec.scene = Some(scene);
rec.events.push(Event {
at: 90,
pos: DVec3::ZERO,
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: crate::sim::SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
});
let rows = chain_rows(&rec, None);
assert_eq!(rows.len(), 1);
for step in ["отметка", "передача", "захват", "пуск", "сбит"] {
assert!(rows[0].text.contains(step), "the chain row misses {step}: {}", rows[0].text);
}
assert_eq!(rows[0].event, Some(0));
assert!(chain_rows(&rec, Some(10)).len() == 1);
assert!(chain_rows(&rec, Some(11)).is_empty());
// A chain with no recorded outcome opens its launch frame on the map, held still.
let mut player = Player::new(1, Mode::Map, &Sim::new(1));
player.seek(&rec, rows[0].at);
assert!(player.paused);
assert!((player.time() - rows[0].at).abs() < 1e-9);
}
#[test]
fn pages_and_filters_keep_the_original_replay_jump() {
use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind};
let mut rec = Recording::blank(300);
let mut scene = SceneJournal::default();
for target in 1..=4 {
scene.fixture_push(SceneEvent {
at: target * 20,
pos: DVec3::ZERO,
kind: SceneKind::TrackAcquired { sam: 10, target, ever_own: true },
});
}
rec.scene = Some(scene);
rec.events.push(Event {
at: 100,
pos: DVec3::ZERO,
kind: EventKind::Hit { drone: 3, kind: DroneKind::Shahed, power: 1, object: Some(0), sam: None },
});
let page = chain_page(&rec, Some(10), ChainFilter::NoLaunch, 1, 2);
assert_eq!((page.index, page.total, page.rows.len()), (1, 4, 2));
assert_eq!((page.rows[0].event, page.rows[0].at), (Some(0), 60.0));
assert_eq!((page.rows[1].event, page.rows[1].at), (None, 80.0));
let page = chain_page(&rec, Some(10), ChainFilter::Breach, 9, 2);
assert_eq!((page.index, page.total, page.rows.len()), (0, 1, 1));
assert_eq!(page.rows[0].event, Some(0));
assert!(chain_page(&rec, Some(11), ChainFilter::All, 1, 2).rows.is_empty());
}
/// A gun standing on the sea floor films from above the water, not from under it. /// A gun standing on the sea floor films from above the water, not from under it.
#[test] #[test]
fn the_gun_camera_is_lifted_above_the_water() { fn the_gun_camera_is_lifted_above_the_water() {
@@ -1326,6 +1538,90 @@ mod engine_tests {
assert!(host.0.is_empty()); assert!(host.0.is_empty());
} }
// #150: the sounds of a window are exactly the events it holds: the same set, order and
// names after any seek, forward or back, empty or spanning ties.
#[test]
fn event_sounds_are_exactly_the_events_of_the_window_after_any_seek() {
use crate::sim::catalog::sound;
use crate::sim::record::{Event, EventKind};
let mut rec = Recording::blank(1000);
rec.events = [10u32, 10, 25, 40, 40, 40, 75, 130]
.into_iter()
.enumerate()
.map(|(i, at)| Event {
at,
pos: DVec3::new(i as f64, 80.0, 0.0),
kind: EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: (i % 5) as u32 },
})
.collect();
let names = |lo: f64, hi: f64| -> Vec<&'static str> {
rec.events
.iter()
.filter(|e| (lo..hi).contains(&(e.at as f64)))
.map(|e| match e.kind {
EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
_ => unreachable!(),
})
.collect()
};
let mut p = player(&rec);
let mut out = Out::default();
for &(heard, t) in &[(0.0, 11.0), (10.0, 10.0), (11.0, 25.0), (10.0, 40.0), (25.0, 40.5), (40.0, 41.0), (40.0, 75.0), (75.0, 130.5), (130.0, 0.0), (41.0, 25.0), (10.5, 40.0)] {
out.sounds.clear();
p.heard = heard;
p.t = t;
p.sounds(&rec, DVec3::ZERO, &mut out);
let got: Vec<&'static str> = out.sounds.iter().map(|s| s.0).collect();
assert_eq!(got, names(heard, t), "{heard}..{t}");
}
}
// #150: the map draws every event up to now, in its order, and reads only that far.
#[test]
fn the_map_marks_the_events_up_to_now_in_their_order() {
use crate::sim::record::{Event, EventKind, StrikeResult};
let ev = |at, kind| Event { at, pos: DVec3::new(at as f64, 0.0, 0.0), kind };
let mut rec = Recording::blank(1000);
rec.events = vec![
ev(100, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
ev(200, EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: None, sam: None }),
ev(300, EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 1 }),
ev(400, EventKind::SamLost { sam: 1, kind: crate::sim::SamKind::S400, index: 0 }),
ev(500, EventKind::Split { drone: 1 }),
ev(600, EventKind::Strike { site: 1, result: StrikeResult::Stunned }),
ev(900, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
];
rec.close();
let at = |p: DVec3| (p.x as f32, 0.0);
let all = |_: (f32, f32)| true;
let colors = |shapes: Vec<Shape>| shapes
.iter()
.map(|s| match s {
Shape::Fill(f) => f.color,
Shape::Quad(q) => q.color,
_ => 0,
})
.collect::<Vec<_>>();
// The kill's cross, then the hit, the crash, the lost system and the split: the earlier
// events only, in their order.
assert_eq!(
colors(event_marks(&rec, 500.0, &at, &all, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020]
);
assert_eq!(
colors(event_marks(&rec, 600.0, &at, &all, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020, 0xFFFFA040]
);
// The map's shape cap stops the reading; nothing past it would be kept anyway.
assert_eq!(event_marks(&rec, 600.0, &at, &all, 3).len(), 3);
// What lies outside the map is skipped, the rest keeps its order.
let left = |(x, _): (f32, f32)| x < 250.0;
assert_eq!(
colors(event_marks(&rec, 600.0, &at, &left, usize::MAX)),
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020]
);
}
#[test] #[test]
fn a_fast_replay_is_silent() { fn a_fast_replay_is_silent() {
let rec = recording(); let rec = recording();
+6
View File
@@ -67,7 +67,9 @@ impl AirDef {
} }
// Everything of the last layout goes: its systems with their jobs and targets, the sky, // Everything of the last layout goes: its systems with their jobs and targets, the sky,
// the cook-offs to come; ids are made anew with the new systems. // the cook-offs to come; ids are made anew with the new systems.
self.village = None;
self.sim.clear(); self.sim.clear();
self.sim.clear_breakthroughs();
self.sim.sams.clear(); self.sim.sams.clear();
self.sim.targets.clear(); self.sim.targets.clear();
self.sim.target_health.clear(); self.sim.target_health.clear();
@@ -77,6 +79,7 @@ impl AirDef {
self.sim.hits = 0; self.sim.hits = 0;
self.sim.launched = 0; self.sim.launched = 0;
self.monitor = None; self.monitor = None;
self.post = crate::post::Post::default();
self.grid_ids.clear(); self.grid_ids.clear();
self.moving = None; self.moving = None;
self.pending.clear(); self.pending.clear();
@@ -108,6 +111,9 @@ impl AirDef {
)) ))
} }
["load", name, flags @ ..] => { ["load", name, flags @ ..] => {
if self.village_active() {
return Err("Чтобы загрузить другой сценарий, остановите «Оборону деревни»".into());
}
let name = valid(name)?; let name = valid(name)?;
let bytes = storage::get(&key(&name)).ok_or(format!("Нет сценария «{name}» (/airdef scenario list)"))?; let bytes = storage::get(&key(&name)).ok_or(format!("Нет сценария «{name}» (/airdef scenario list)"))?;
self.apply_scenario(&String::from_utf8_lossy(&bytes), flags.contains(&"force"))?; self.apply_scenario(&String::from_utf8_lossy(&bytes), flags.contains(&"force"))?;
+18 -14
View File
@@ -234,6 +234,7 @@ impl Sam {
if self.radar_role != role { if self.radar_role != role {
self.radar_role = role; self.radar_role = role;
self.tracks.clear(); self.tracks.clear();
self.class_plots.clear();
self.seen.clear(); self.seen.clear();
self.own.clear(); self.own.clear();
} }
@@ -241,10 +242,11 @@ impl Sam {
} }
/// Change the physical configuration. Invalid combinations leave the unit untouched. /// Change the physical configuration. Invalid combinations leave the unit untouched.
pub fn set_mode(&mut self, mode: SamMode) -> bool { pub fn set_mode(&mut self, mode: SamMode) -> bool {
if mode == SamMode::LauncherOnly && !matches!(self.kind, SamKind::S400 | SamKind::S500) { return false; } if mode == SamMode::LauncherOnly && !catalog::has_separate_launcher(self.kind) { return false; }
if self.mode != mode { if self.mode != mode {
self.mode = mode; self.mode = mode;
self.tracks.clear(); self.tracks.clear();
self.class_plots.clear();
self.seen.clear(); self.seen.clear();
self.own.clear(); self.own.clear();
self.target = None; self.target = None;
@@ -269,7 +271,7 @@ impl Sim {
self.sams.iter().enumerate().filter_map(|(index, sam)| { self.sams.iter().enumerate().filter_map(|(index, sam)| {
if sam.kind == SamKind::Radar { if sam.kind == SamKind::Radar {
Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 }) Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 })
} else if matches!(sam.kind, SamKind::S400 | SamKind::S500) { } else if catalog::has_separate_launcher(sam.kind) {
let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())); let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()));
Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked }) Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked })
} else { None } } else { None }
@@ -540,30 +542,32 @@ mod emission_tests {
assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0); assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
assert!(!sim.sams[1].radar_up()); assert!(!sim.sams[1].radar_up());
// The emitting source is fixed by the drone; the silent receiver is not. // The emitting source gives the drone a coarse area. The silent receiver stays hidden.
let picture = sim.picture_of_defences(); let picture = sim.knowledge_now().observations();
assert_eq!(picture.len(), 1); assert_eq!(picture.len(), 1);
assert_eq!((picture[0].id, picture[0].at), (1, DVec3::ZERO)); let signal = picture[0];
assert_eq!(picture[0].seen, ew::Seen::Emission); assert!(recon::is_mark(signal.id) && !signal.exact());
assert_eq!((signal.channel, signal.kind), (recon::Source::Emission, None));
sim.sams[0].radar_on = false; sim.sams[0].radar_on = false;
// The truth moving is not an observation: the contact keeps the observed place. // The truth moving is not an observation: the contact keeps the observed place.
sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0); sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0);
sim.tick = 40; sim.tick = 40;
sim.update_sight(&mut ground); sim.update_sight(&mut ground);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
let picture = sim.picture_of_defences(); assert_eq!(sim.knowledge_now().observations(), picture, "a hidden move changed the picture");
assert_eq!(picture.len(), 1); // A fresh witnessed emission moves the estimated area.
assert_eq!(picture[0].at, DVec3::ZERO, "a hidden move changed the picture");
// A fresh emission fix re-places it where seen then.
sim.sams[0].radar_on = true; sim.sams[0].radar_on = true;
sim.tick = 60; sim.tick = 60;
sim.update_sight(&mut ground); sim.update_sight(&mut ground);
assert_eq!(sim.picture_of_defences()[0].at, DVec3::new(400.0, 0.0, 0.0)); let moved = sim.knowledge_now().observations()[0];
assert_eq!(moved.id, signal.id);
assert!(moved.at != signal.at && moved.at != sim.sams[0].pos);
assert!(moved.at.distance(sim.sams[0].pos) < moved.radius);
sim.sams[0].radar_on = false; sim.sams[0].radar_on = false;
// Other disclosure channels still reveal a silent unit. // Other disclosure channels still reveal a silent unit.
sim.intel.observe(&sim.sams[1], 60, ew::Seen::Launch); sim.recon.signal(&sim.sams[1], 60, recon::Source::Launch);
assert!(sim.known_live(2)); assert!(sim.knowledge_now().observations().iter().any(|o| o.channel == recon::Source::Launch && !o.exact()));
sim.tick = 6060; sim.tick = 6060;
assert!(sim.picture_of_defences().is_empty(), "an unrefreshed contact never ages out"); assert!(sim.knowledge_now().observations().is_empty(), "an unrefreshed contact never ages out");
} }
} }
+269
View File
@@ -0,0 +1,269 @@
//! Bounded, observed facts about impacts. This is session history, not save data.
use super::*;
const MAX_ACTIVE: usize = 4096;
const MAX_HITS: usize = 128;
const PAGE_SIZE: usize = 3;
#[derive(Clone, Copy, Default)]
pub(super) struct FlightFacts {
/// False when observation began after the flight began, or after a load.
complete: bool,
pub(super) first: Option<(u64, u32)>,
launches: u32,
}
impl FlightFacts {
pub(super) fn new(complete: bool) -> Self {
Self {
complete,
..Default::default()
}
}
}
struct Hit {
tick: u64,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
facts: Option<FlightFacts>,
nearby: Vec<BatterySnapshot>,
}
struct BatterySnapshot {
kind: SamKind,
reason: why::BattleReason,
terrain_blocked: bool,
}
#[derive(Default)]
pub(super) struct Breakthroughs {
pub(super) active: HashMap<u32, FlightFacts>,
hits: VecDeque<Hit>,
}
impl Breakthroughs {
pub(super) fn begin(&mut self, id: u32, complete: bool) {
if self.active.len() < MAX_ACTIVE {
self.active.insert(id, FlightFacts::new(complete));
}
}
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes, vecdeque_bytes};
map_bytes(
self.active.capacity(),
std::mem::size_of::<(u32, FlightFacts)>(),
) + vecdeque_bytes(&self.hits)
+ self
.hits
.iter()
.map(|h| vec_bytes(&h.nearby))
.sum::<usize>()
}
}
impl Sim {
/// Clears the displayed history; observation of flights already in progress continues.
pub fn clear_breakthroughs(&mut self) {
self.breakthroughs.hits.clear();
}
pub(super) fn breakthrough_launch(&mut self, id: u32) {
if let Some(facts) = self.breakthroughs.active.get_mut(&id) {
facts.launches = facts.launches.saturating_add(1);
}
}
pub(super) fn breakthrough_hit(
&mut self,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
) {
// Only the nearest three armed systems; this runs once per impact, not per tick.
let mut nearest: Vec<_> = self
.sams
.iter()
.enumerate()
.filter(|(_, s)| s.kind.armed())
.map(|(i, s)| (i, s.pos.distance_squared(pos)))
.collect();
nearest.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let nearby = nearest
.into_iter()
.take(3)
.filter_map(|(i, _)| {
let sam = &self.sams[i];
Some(BatterySnapshot {
kind: sam.kind,
reason: self.battle_reason_at(i, Some(id))?,
terrain_blocked: sam.terrain_verdict(id, self.tick).is_some_and(|v| v != 0),
})
})
.collect();
let hit = Hit {
tick: self.tick,
id,
kind,
pos,
object,
facts: self.breakthroughs.active.get(&id).copied(),
nearby,
};
if self.breakthroughs.hits.len() == MAX_HITS {
self.breakthroughs.hits.pop_front();
}
self.breakthroughs.hits.push_back(hit);
}
pub fn breakthrough_pages(&self) -> usize {
self.breakthroughs.hits.len().div_ceil(PAGE_SIZE)
}
/// Most recent recorded impacts, three per page. Page is zero-based.
pub fn breakthrough_page(&self, page: usize) -> String {
let total = self.breakthroughs.hits.len();
if total == 0 {
return "Прорывов в истории нет".into();
}
let pages = self.breakthrough_pages();
if page >= pages {
return format!("Нет страницы {}. Страниц: {pages}", page.saturating_add(1));
}
let mut lines = vec![format!(
"Прорывы: страница {}/{} (последние {total})",
page + 1,
pages
)];
for hit in self
.breakthroughs
.hits
.iter()
.rev()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let detection = match hit.facts {
Some(f) if f.complete => match f.first {
Some((t, radar)) => format!(
"первое измерение РЛС id {radar}: тик {t}, за {:.1} с до удара",
hit.tick.saturating_sub(t) as f64 / 20.0
),
None => "своих измерений РЛС не было".into(),
},
Some(f) => match f.first {
Some((t, radar)) => format!(
"первое известное измерение РЛС id {radar}: тик {t} (предыдущее неизвестно)"
),
None => "обнаружение до загрузки или начала наблюдения неизвестно".into(),
},
None => "данные обнаружения недоступны".into(),
};
let launches = hit.facts.map_or("пуски неизвестны".to_string(), |f| {
if f.complete {
format!("пусков: {}", f.launches)
} else {
format!("известных пусков: {} (предыдущие неизвестны)", f.launches)
}
});
let object = hit
.object
.map_or_else(String::new, |i| format!(" · объект №{}", i + 1));
lines.push(format!(
"{} №{} · ({:.0}, {:.0}, {:.0}){object}",
hit.kind.spec().name,
hit.id,
hit.pos.x,
hit.pos.y,
hit.pos.z
));
lines.push(format!("{detection} · {launches}"));
if !hit.nearby.is_empty() {
lines.push("Снимок перед ударом · ближайшие комплексы".into());
for battery in &hit.nearby {
let terrain = if battery.terrain_blocked {
" · рельеф перекрывал траекторию"
} else {
""
};
lines.push(format!(
"{} №{} · {}{terrain}",
battery.kind.name(),
battery.reason.sam + 1,
reason_text(&battery.reason),
));
}
}
}
lines.join("\n")
}
}
fn reason_text(reason: &why::BattleReason) -> &'static str {
use why::{BattleBlock as B, BattleKind as K};
match reason.kind {
K::Ready => "готов к пуску",
K::ObserveOnly => "только обзор",
K::AwaitingTrack => "ждёт сопровождения",
K::ChannelsBusy => "каналы заняты",
K::NoAmmo => "нет боезапаса или перезарядка",
K::Blocked => match reason.block {
Some(B::Destroyed) => "уничтожен",
Some(B::Moving) => "на марше",
Some(B::Hold) => "огонь запрещён",
Some(B::NoWeapon) => "нет оружия",
Some(B::NoTarget) => "нет цели",
Some(B::NoTrack) => "нет трассы",
Some(B::ClassPending) => "ждёт подтверждения класса цели",
Some(B::OutOfRoles) => "вне ролей",
Some(B::OutOfReach) => "вне дальности",
Some(B::Claimed) => "занята перехватчиками",
Some(B::Doctrine) => "доктрина",
Some(B::Aiming) => "наводится",
Some(B::Preparing) => "подготовка пуска",
Some(B::LauncherDown) => "пусковая отказала",
Some(B::Other) | None => "другая причина",
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impact_history_is_bounded_and_pages_are_safe() {
let mut sim = Sim::new(1);
for id in 0..130 {
sim.tick = id as u64;
sim.breakthrough_hit(id, DroneKind::Geran3, DVec3::ZERO, None);
}
assert_eq!(sim.breakthroughs.hits.len(), MAX_HITS);
assert!(sim.breakthrough_page(0).contains("№129"));
assert!(sim.breakthrough_page(usize::MAX).contains("Нет страницы"));
sim.clear_breakthroughs();
assert!(sim.breakthrough_page(0).contains("истории нет"));
}
#[test]
fn detection_and_launches_distinguish_complete_and_partial_history() {
let mut sim = Sim::new(1);
sim.tick = 20;
sim.breakthroughs.active.insert(1, FlightFacts::new(true));
sim.breakthrough_launch(1);
sim.breakthrough_hit(1, DroneKind::Geran3, DVec3::ZERO, None);
let page = sim.breakthrough_page(0);
assert!(page.contains("измерений РЛС не было"));
assert!(page.contains("пусков: 1"));
sim.breakthroughs.active.insert(2, FlightFacts::new(false));
sim.breakthrough_hit(2, DroneKind::Geran3, DVec3::ZERO, None);
assert!(
sim.breakthrough_page(0)
.contains("до загрузки или начала наблюдения неизвестно")
);
}
}
+48 -2
View File
@@ -25,6 +25,8 @@ impl Aircraft {
pub struct UnitVariant { pub struct UnitVariant {
/// Existing command/menu key; changing it requires an explicit migration. /// Existing command/menu key; changing it requires an explicit migration.
pub id: &'static str, pub id: &'static str,
/// Its own placeable remote, so every configuration is a separate item.
pub deploy_item: &'static str,
pub kind: SamKind, pub kind: SamKind,
pub mode: SamMode, pub mode: SamMode,
pub role: RadarRole, pub role: RadarRole,
@@ -69,7 +71,9 @@ impl Unit {
/// Whether the unit has a gun; callers need no access to the private weapon profile. /// Whether the unit has a gun; callers need no access to the private weapon profile.
pub fn has_gun(self) -> bool { self.kind.spec().gun.is_some() } pub fn has_gun(self) -> bool { self.kind.spec().gun.is_some() }
pub fn ground_strike(self) -> GroundStrike { pub fn ground_strike(self) -> GroundStrike {
if self.kind == SamKind::S400 { GroundStrike::Rm48uGame } else { GroundStrike::Unavailable { reason: "Для этой техники не задан профиль удара по координатам" } } self.kind.spec().ground_strike.unwrap_or(GroundStrike::Unavailable {
reason: "Для этой техники не задан профиль удара по координатам",
})
} }
} }
@@ -121,7 +125,7 @@ pub fn unit(kind: SamKind) -> &'static Unit {
/// Inventory ordering is stable for existing remotes, while availability comes from the same entries as raids. /// Inventory ordering is stable for existing remotes, while availability comes from the same entries as raids.
const fn inventory_count() -> usize { const fn inventory_count() -> usize {
let mut n = UNIT_COUNT + 4; let mut n = UNIT_COUNT + VARIANTS.len() + 4;
let mut i = 0; let mut i = 0;
while i < AIRCRAFT.len() { while i < AIRCRAFT.len() {
if AIRCRAFT[i].launch_item.is_some() { n += 1; } if AIRCRAFT[i].launch_item.is_some() { n += 1; }
@@ -144,6 +148,10 @@ const fn inventory_items() -> [&'static str; INVENTORY_COUNT] {
out[n] = "airdef:mover"; out[n] = "airdef:mover";
out[n + 1] = "airdef:flare_gun"; out[n + 1] = "airdef:flare_gun";
out[n + 2] = "airdef:remover"; out[n + 2] = "airdef:remover";
// Variant remotes come last: every existing remote keeps its slot.
n += 3;
i = 0;
while i < VARIANTS.len() { out[n] = VARIANTS[i].deploy_item; n += 1; i += 1; }
out out
} }
pub const INVENTORY: [&str; INVENTORY_COUNT] = inventory_items(); pub const INVENTORY: [&str; INVENTORY_COUNT] = inventory_items();
@@ -154,11 +162,23 @@ pub fn launch_item(id: &str) -> Option<DroneKind> {
pub fn deploy_item(id: &str) -> Option<SamKind> { pub fn deploy_item(id: &str) -> Option<SamKind> {
UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind) UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind)
} }
/// The configuration a remote item deploys: a unit's ordinary integrated
/// system or a variant's own mode and radar role.
pub fn deploy_item_configuration(id: &str) -> Option<(SamKind, SamMode, RadarRole)> {
if let Some(kind) = deploy_item(id) {
return Some((kind, SamMode::Integrated, RadarRole::Multifunction));
}
VARIANTS.iter().find(|entry| entry.deploy_item == id).map(|entry| (entry.kind, entry.mode, entry.role))
}
pub fn variant(id: &str) -> Option<&'static UnitVariant> { pub fn variant(id: &str) -> Option<&'static UnitVariant> {
VARIANTS.iter().find(|variant| variant.id == id) VARIANTS.iter().find(|variant| variant.id == id)
} }
pub fn has_separate_launcher(kind: SamKind) -> bool {
VARIANTS.iter().any(|variant| variant.kind == kind && variant.mode == SamMode::LauncherOnly)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -197,9 +217,32 @@ mod tests {
} }
assert_eq!(kinds, SamKind::ALL.into_iter().collect()); assert_eq!(kinds, SamKind::ALL.into_iter().collect());
for e in VARIANTS {
assert!(items.insert(e.deploy_item), "duplicate item {}", e.deploy_item);
assert_eq!(e.deploy_item, format!("airdef:deploy_{}", e.id));
}
assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]); assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]);
} }
/// `give` hands out every remote once; the ordinary units keep their historical
/// slots and the variant remotes are appended after them.
#[test]
fn inventory_holds_every_remote_once_and_keeps_existing_slots() {
let unique: HashSet<&str> = INVENTORY.iter().copied().collect();
assert_eq!(unique.len(), INVENTORY.len(), "duplicate inventory item");
let launches = AIRCRAFT.iter().filter(|a| a.launch_item.is_some()).count();
let first_unit = 1 + launches;
for (i, unit) in UNITS.iter().enumerate() {
assert_eq!(INVENTORY[first_unit + i], unit.deploy_item);
assert_eq!(deploy_item_configuration(unit.deploy_item), Some((unit.kind, SamMode::Integrated, RadarRole::Multifunction)));
}
let tail = first_unit + UNITS.len();
assert_eq!(&INVENTORY[tail..tail + 3], &["airdef:mover", "airdef:flare_gun", "airdef:remover"]);
assert_eq!(&INVENTORY[tail + 3..], &VARIANTS.iter().map(|v| v.deploy_item).collect::<Vec<_>>()[..]);
assert_eq!(deploy_item_configuration("airdef:designator"), None);
assert_eq!(deploy_item_configuration("airdef:deploy_radar_track"), Some((SamKind::Radar, SamMode::Integrated, RadarRole::Engagement)));
}
/// A variant is a configuration of an existing kind, one row in the catalog, /// A variant is a configuration of an existing kind, one row in the catalog,
/// under an id that stays out of the other identities' keys; the battery-menu /// under an id that stays out of the other identities' keys; the battery-menu
/// order is part of the UI's tested behaviour. /// order is part of the UI's tested behaviour.
@@ -211,6 +254,9 @@ mod tests {
assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id); assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id);
assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id); assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id);
assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id); assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
assert_eq!(v.deploy_item, format!("airdef:deploy_{}", v.id));
assert!(INVENTORY.contains(&v.deploy_item), "{} has no remote in the inventory", v.id);
assert_eq!(deploy_item_configuration(v.deploy_item), Some((v.kind, v.mode, v.role)));
assert!(!v.label.is_empty() && !v.description.is_empty()); assert!(!v.label.is_empty() && !v.description.is_empty());
assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role))); assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role)));
if v.kind == SamKind::Radar { if v.kind == SamKind::Radar {
+1 -1
View File
@@ -1,4 +1,4 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit. // Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
pub const AIRCRAFT: &[Aircraft] = &[ pub const AIRCRAFT: &[Aircraft] = &[
Aircraft { kind: Gerbera, launch_item: None, raid: true }, Aircraft { kind: Gerbera, launch_item: None, raid: true },
Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true }, Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true },
+3 -25
View File
@@ -135,17 +135,7 @@ fn blast_exposure(ground: &Ground, from: DVec3, centre: DVec3, size: f64, now: u
impl MissileKind { impl MissileKind {
/// The explosive a missile left in a burning launcher adds (TNT). /// The explosive a missile left in a burning launcher adds (TNT).
fn charge(self) -> f64 { fn charge(self) -> f64 {
match self { self.spec().launcher_blast
MissileKind::Pac3 => 0.8,
MissileKind::M57e6 => 0.45,
MissileKind::M48n6 => 1.8,
MissileKind::M77n6 => 2.2,
MissileKind::IrisT => 0.6,
MissileKind::Amraam => 0.5,
MissileKind::M9m317 => 1.2,
MissileKind::M9m338 => 0.4,
MissileKind::P1sun => 0.1,
}
} }
} }
@@ -159,20 +149,7 @@ impl DroneKind {
/// Strike accuracy: the CEP (blocks; half the strikes land within it, the scatter is Rayleigh) /// Strike accuracy: the CEP (blocks; half the strikes land within it, the scatter is Rayleigh)
/// and the share of strikes with a rare gross navigation fault, which lands beyond `MISS_RADIUS`. /// and the share of strikes with a rare gross navigation fault, which lands beyond `MISS_RADIUS`.
pub(super) fn accuracy(self) -> (f64, f64) { pub(super) fn accuracy(self) -> (f64, f64) {
match self { self.spec().accuracy
DroneKind::Shahed => (1.2, 0.03),
DroneKind::Geran3 => (1.0, 0.03),
DroneKind::Lancet => (0.8, 0.02),
DroneKind::Gerbera => (1.5, 0.04),
DroneKind::Kh101 => (1.3, 0.05),
DroneKind::Kalibr => (1.3, 0.05),
DroneKind::Kh22 => (1.6, 0.06),
DroneKind::Zircon => (1.5, 0.06),
DroneKind::Iskander => (1.4, 0.06),
DroneKind::Kinzhal => (1.5, 0.06),
// The bus and its blocks: the blocks are aimed by the split, so only the bus's own error applies.
DroneKind::Oreshnik | DroneKind::OreshnikBlock | DroneKind::OreshnikSub => (1.6, 0.08),
}
} }
} }
@@ -313,6 +290,7 @@ impl Sim {
sam.gun_target = None; sam.gun_target = None;
sam.reloading = 0; sam.reloading = 0;
sam.tracks.clear(); sam.tracks.clear();
sam.class_plots.clear();
sam.seen.clear(); sam.seen.clear();
sam.own.clear(); sam.own.clear();
let spec = sam.kind.spec(); let spec = sam.kind.spec();
+260
View File
@@ -0,0 +1,260 @@
//! Recorded choices at the firing checks, on the same clock as the replay.
use super::{ClassEst, Sam, battery::Measure, memory, why};
use std::collections::{HashMap, VecDeque};
const MAX_ENTRIES: usize = 4096;
const MAX_STREAMS: usize = 1024;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Channel {
Unit,
Gun,
Launcher,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Block {
Hold,
Moving,
Reload,
Empty,
NoSelection,
WaitingForTerrain,
Terrain,
Aim,
Opening,
BusyWithGroundShot,
Cooldown,
GunFault,
LauncherFault,
NoLock,
Range,
}
impl Block {
pub(super) fn gun(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::JAMMED != 0 {
Self::GunFault
} else if bits & why::NO_LOCK != 0 {
Self::NoLock
} else if bits & (why::NOT_AIMED | why::AIM_ERROR) != 0 {
Self::Aim
} else if bits & why::OUT_OF_RANGE != 0 {
Self::Range
} else {
Self::Cooldown
}
}
pub(super) fn launcher(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::LAUNCHER_DOWN != 0 {
Self::LauncherFault
} else {
Self::Cooldown
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
Held(Block),
Burst,
BurstMissed,
BurstHit,
Launched(u32),
Intercepted(u32),
InterceptorMissed(u32),
InterceptorEnded(u32),
}
/// What the unit itself measured or received, with IDs fixed at recording time.
#[derive(Clone, Copy, Debug)]
pub struct Mark {
pub source: u32,
pub age: u16,
pub own: bool,
pub quality: u8,
pub product: Measure,
pub class: ClassEst,
}
#[derive(Clone, Copy, Debug)]
pub struct Entry {
pub at: u32,
pub unit: u32,
pub target: Option<u32>,
pub channel: Channel,
pub outcome: Outcome,
pub mark: Option<Mark>,
}
#[derive(Default)]
pub struct History {
entries: VecDeque<Entry>,
first: u64,
last: HashMap<(u32, Channel), (Option<u32>, Outcome)>,
truncated: bool,
}
impl History {
pub fn first_index(&self) -> u64 { self.first }
pub fn entries(&self) -> impl DoubleEndedIterator<Item = &Entry> {
self.entries.iter()
}
pub fn truncated(&self) -> bool {
self.truncated
}
pub(super) fn resume(&mut self, unit: u32, channel: Channel) {
self.last.remove(&(unit, channel));
}
pub(super) fn note(
&mut self,
at: u32,
now: u64,
sam: &Sam,
channel: Channel,
target: Option<u32>,
outcome: Outcome,
) {
let key = (sam.id, channel);
if matches!(outcome, Outcome::Held(_)) {
if self.last.get(&key) == Some(&(target, outcome)) {
return;
}
if self.last.len() == MAX_STREAMS && !self.last.contains_key(&key) {
self.truncated = true;
return;
}
self.last.insert(key, (target, outcome));
} else {
self.last.remove(&key);
}
let mark = target.and_then(|id| sam.track(id)).map(|track| Mark {
source: track.source,
age: track.age(now).min(u64::from(u16::MAX)) as u16,
own: track.source == sam.id,
quality: track.quality,
product: track.product,
class: track.class,
});
// A refusal is for a public track, or the absence of a selected track.
// An actual shot still identifies the track it was fired at.
let target = if matches!(outcome, Outcome::Held(_)) && mark.is_none() {
None
} else {
target
};
self.push(Entry {
at,
unit: sam.id,
target,
channel,
outcome,
mark,
});
}
pub(super) fn outcome(
&mut self,
at: u32,
unit: u32,
target: u32,
channel: Channel,
outcome: Outcome,
) {
self.push(Entry {
at,
unit,
target: Some(target),
channel,
outcome,
mark: None,
});
}
fn push(&mut self, entry: Entry) {
if self.entries.len() == MAX_ENTRIES {
self.entries.pop_front();
self.first += 1;
self.truncated = true;
}
self.entries.push_back(entry);
}
pub(super) fn close(&mut self) {
self.last = HashMap::new();
}
pub(super) fn bytes(&self) -> usize {
memory::vecdeque_bytes(&self.entries)
+ memory::map_bytes(
self.last.capacity(),
size_of::<((u32, Channel), (Option<u32>, Outcome))>(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::SamKind;
use glam::DVec3;
#[test]
fn deduplicates_continuous_refusals_and_preserves_a_known_miss() {
let sam = Sam::new(16, SamKind::S400, DVec3::ZERO, 0.0);
let mut history = History::default();
for at in 0..100 {
history.note(
at,
u64::from(at),
&sam,
Channel::Unit,
None,
Outcome::Held(Block::Hold),
);
}
history.note(
100,
100,
&sam,
Channel::Launcher,
Some(93),
Outcome::Launched(94),
);
history.outcome(
130,
sam.id,
93,
Channel::Launcher,
Outcome::InterceptorMissed(94),
);
let entries: Vec<_> = history.entries().collect();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].at, 0);
assert_eq!(entries[1].outcome, Outcome::Launched(94));
assert_eq!(entries[2].outcome, Outcome::InterceptorMissed(94));
}
#[test]
fn a_full_journal_keeps_recent_entries_and_marks_the_gap() {
let mut history = History::default();
for at in 0..MAX_ENTRIES as u32 + 3 {
history.outcome(at, 16, 93, Channel::Gun, Outcome::BurstHit);
}
assert!(history.truncated());
assert_eq!(history.entries().count(), MAX_ENTRIES);
assert_eq!(history.entries().next().unwrap().at, 3);
}
}
+119 -44
View File
@@ -21,6 +21,7 @@
//! contacts, route points and relief cells — so a saved air state can never grow the file without limit. //! contacts, route points and relief cells — so a saved air state can never grow the file without limit.
use super::*; use super::*;
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::fmt::Write;
/// The section's format version. A different one is refused rather than half-read. /// The section's format version. A different one is refused rather than half-read.
const VERSION: u32 = 1; const VERSION: u32 = 1;
@@ -49,8 +50,11 @@ const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2;
pub struct AirSave { pub struct AirSave {
tick: u64, tick: u64,
job_next: u32, job_next: u32,
diversions_left: u32,
kills: [u32; ew::SECTORS], kills: [u32; ew::SECTORS],
hits: [u32; ew::SECTORS], hits: [u32; ew::SECTORS],
/// The bearing memory's small window of recent outcomes (#149).
outcomes: Vec<ew::Learned>,
contacts: Vec<ew::Contact>, contacts: Vec<ew::Contact>,
drones: Vec<Drone>, drones: Vec<Drone>,
queue: Vec<(u64, Drone)>, queue: Vec<(u64, Drone)>,
@@ -162,7 +166,8 @@ impl Drone {
if !self.route.is_empty() { if !self.route.is_empty() {
route = self.route.len().to_string(); route = self.route.len().to_string();
for p in &self.route { for p in &self.route {
route += &format!(" {} {} {}", coord(p.x), coord(p.y), coord(p.z)); // 🤖 Agent: format straight into the buffer, not through a temporary `String`.
write!(route, " {} {} {}", coord(p.x), coord(p.y), coord(p.z)).unwrap();
} }
} }
format!( format!(
@@ -213,6 +218,7 @@ impl Sim {
^ (self.intel.contacts().len() as u64) << 36 ^ (self.intel.contacts().len() as u64) << 36
^ (self.job_next as u64) << 48 ^ (self.job_next as u64) << 48
^ self.recon.mark().rotate_left(12) ^ self.recon.mark().rotate_left(12)
^ u64::from(self.diversions_left).rotate_left(18)
} }
/// The air section of the state text: `None` when there is nothing to keep (an empty sky and no /// The air section of the state text: `None` when there is nothing to keep (an empty sky and no
@@ -241,13 +247,27 @@ impl Sim {
let job_relief: Vec<Option<usize>> = self.retargets.iter().map(|j| j.relief.as_ref().and_then(|r| token_of(r, &mut reliefs))).collect(); let job_relief: Vec<Option<usize>> = self.retargets.iter().map(|j| j.relief.as_ref().and_then(|r| token_of(r, &mut reliefs))).collect();
let (kills, hits) = self.intel.sectors(); let (kills, hits) = self.intel.sectors();
// The head, with the counts filled in later; its length is what the body is measured against. // The head, with the counts filled in later; its length is what the body is measured against.
// 🤖 Agent: `write!`/`push_str` format into the buffer in place. `head += &format!(...)` made a
// temporary `String` per item and re-copied the whole growing head, so a full relief grid cost
// O(n²) bytes and a heavy autosave ran out of fuel.
let mut head = format!("air {VERSION} {} {} 0 0 0 {} {}\n", self.tick, self.job_next, contacts.len(), reliefs.len()); let mut head = format!("air {VERSION} {} {} 0 0 0 {} {}\n", self.tick, self.job_next, contacts.len(), reliefs.len());
head += "airintel"; writeln!(head, "airdiversions {}", self.diversions_left).unwrap();
head.push_str("airintel");
for v in kills.iter().chain(hits.iter()) { for v in kills.iter().chain(hits.iter()) {
head += &format!(" {v}"); write!(head, " {v}").unwrap();
} }
head += "\n"; head.push('\n');
head += &format!("airglobal {}\n", global.map_or_else(|| "-".into(), |t| t.to_string())); // The bearing window (#149): bounded, and optional — an older save without it loads with
// an empty window and the lifetime tally it does carry.
let outcomes: Vec<&ew::Learned> = self.intel.outcomes().iter().take(ew::MAX_OUTCOMES).collect();
if !outcomes.is_empty() {
write!(head, "airlearn {}", outcomes.len()).unwrap();
for o in &outcomes {
write!(head, " {} {} {}", o.sector, o.tick, u8::from(o.killed)).unwrap();
}
head.push('\n');
}
write!(head, "airglobal {}\n", global.map_or_else(|| "-".into(), |t| t.to_string())).unwrap();
for (i, r) in reliefs.iter().enumerate() { for (i, r) in reliefs.iter().enumerate() {
let g = r.grid(); let g = r.grid();
let mut line = format!("airrelief {i} {} {} {} {} ", coord(g.min.x), coord(g.min.z), coord(g.cell), g.size); let mut line = format!("airrelief {i} {} {} {} {} ", coord(g.min.x), coord(g.min.z), coord(g.cell), g.size);
@@ -257,20 +277,21 @@ impl Sim {
match run { match run {
Some((k, n)) if k == key => run = Some((k, n + 1)), Some((k, n)) if k == key => run = Some((k, n + 1)),
Some((k, n)) => { Some((k, n)) => {
line += &format!("{} ", run_token(k, n)); write!(line, "{} ", run_token(k, n)).unwrap();
run = Some((key, 1)); run = Some((key, 1));
} }
None => run = Some((key, 1)), None => run = Some((key, 1)),
} }
} }
if let Some((k, n)) = run { if let Some((k, n)) = run {
line += &run_token(k, n); line.push_str(&run_token(k, n));
} }
head += &line; head.push_str(&line);
head += "\n"; head.push('\n');
} }
for c in &contacts { for c in &contacts {
head += &format!( write!(
head,
"aircontact {} {} {} {} {} {} {} {} {} {}\n", "aircontact {} {} {} {} {} {} {} {} {} {}\n",
c.id, c.id,
c.kind.spec().key, c.kind.spec().key,
@@ -282,7 +303,8 @@ impl Sim {
tick(c.emission), tick(c.emission),
tick(c.destroyed), tick(c.destroyed),
c.launches c.launches
); )
.unwrap();
} }
// The bodies go in while the section stays inside its byte bound; a drone left out takes its // The bodies go in while the section stays inside its byte bound; a drone left out takes its
// job with it (a job whose drone is not saved could never be restored). // job with it (a job whose drone is not saved could never be restored).
@@ -295,8 +317,8 @@ impl Sim {
if !fits(&head, &body, &line) { if !fits(&head, &body, &line) {
break; break;
} }
body += &line; body.push_str(&line);
body += "\n"; body.push('\n');
saved.insert(d.id); saved.insert(d.id);
drone_count += 1; drone_count += 1;
} }
@@ -306,8 +328,8 @@ impl Sim {
if !fits(&head, &body, &line) { if !fits(&head, &body, &line) {
break; break;
} }
body += &line; body.push_str(&line);
body += "\n"; body.push('\n');
saved.insert(d.id); saved.insert(d.id);
queued_count += 1; queued_count += 1;
} }
@@ -319,7 +341,7 @@ impl Sim {
.zip(job_relief) .zip(job_relief)
.filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit))) .filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit)))
.collect(); .collect();
if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() { if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() && outcomes.is_empty() {
return None; return None;
} }
let head = head.replacen( let head = head.replacen(
@@ -328,9 +350,10 @@ impl Sim {
1, 1,
); );
let mut text = head; let mut text = head;
text += &body; text.push_str(&body);
for (job, relief) in jobs { for (job, relief) in jobs {
text += &format!( write!(
text,
"airjob {} {} {} {} {} {} {} {} {} {}\n", "airjob {} {} {} {} {} {} {} {} {} {}\n",
job.id, job.id,
job.drone, job.drone,
@@ -342,7 +365,8 @@ impl Sim {
job.priority(), job.priority(),
job.intent.key(), job.intent.key(),
relief.map_or_else(|| "-".into(), |t| t.to_string()) relief.map_or_else(|| "-".into(), |t| t.to_string())
); )
.unwrap();
} }
// Recon: the marks are memory (survive a new raid), the sorties are the aircraft still // Recon: the marks are memory (survive a new raid), the sorties are the aircraft still
// out, and the zones already reported empty. Everything is bounded, and each line is // out, and the zones already reported empty. Everything is bounded, and each line is
@@ -361,7 +385,7 @@ impl Sim {
for m in self.recon.marks.values().take(MAX_RECON_MARKS) { for m in self.recon.marks.values().take(MAX_RECON_MARKS) {
let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0); let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0);
let line = format!( let line = format!(
"airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n", "airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
m.id, m.id,
truth, truth,
coord(m.area.x), coord(m.area.x),
@@ -375,6 +399,8 @@ impl Sim {
m.observed, m.observed,
m.reported, m.reported,
m.looks, m.looks,
m.launches,
m.last_launch.map_or_else(|| "-".into(), |t| t.to_string()),
); );
if !add(&line) { if !add(&line) {
break; break;
@@ -402,8 +428,9 @@ impl Sim {
s.zones.len(), s.zones.len(),
); );
for l in &s.pending { for l in &s.pending {
body += &format!( write!(
"airrecobs {} {} {} {} {} {} {} {} {} {}\n", body,
"airrecobs {} {} {} {} {} {} {} {} {} {} {}\n",
l.truth, l.truth,
coord(l.area.x), coord(l.area.x),
coord(l.area.y), coord(l.area.y),
@@ -414,18 +441,20 @@ impl Sim {
l.quality.name(), l.quality.name(),
l.source.name(), l.source.name(),
l.observed, l.observed,
); l.wreck,
)
.unwrap();
} }
for z in &s.zones { for z in &s.zones {
body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius)); write!(body, "airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius)).unwrap();
} }
if !add(&body) { if !add(&body) {
break; break;
} }
sorties += 1; sorties += 1;
} }
text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked); write!(text, "airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked).unwrap();
text += &recon_body; text.push_str(&recon_body);
} }
Some(text) Some(text)
} }
@@ -466,6 +495,8 @@ impl Sim {
let n_reliefs = l.count(8, "версии рельефа", MAX_RELIEFS)?; let n_reliefs = l.count(8, "версии рельефа", MAX_RELIEFS)?;
// Every line of the section, and nothing else: a truncated or foreign line is refused. // Every line of the section, and nothing else: a truncated or foreign line is refused.
let mut intel: Option<[u32; ew::SECTORS * 2]> = None; let mut intel: Option<[u32; ew::SECTORS * 2]> = None;
let mut diversions_left = None;
let mut outcomes: Vec<ew::Learned> = Vec::new();
let mut global: Option<usize> = None; let mut global: Option<usize> = None;
let mut reliefs: Vec<Option<std::sync::Arc<ew::KnownRelief>>> = vec![None; n_reliefs]; let mut reliefs: Vec<Option<std::sync::Arc<ew::KnownRelief>>> = vec![None; n_reliefs];
let mut contacts: BTreeMap<u32, ew::Contact> = BTreeMap::new(); let mut contacts: BTreeMap<u32, ew::Contact> = BTreeMap::new();
@@ -488,6 +519,12 @@ impl Sim {
} }
let l = Line { n: *n, word, w: w.clone() }; let l = Line { n: *n, word, w: w.clone() };
match word { match word {
"airdiversions" => {
if w.len() != 2 || diversions_left.is_some() {
return Err(l.bad("перенацеливание", "нужен один счётчик на сохранение"));
}
diversions_left = Some(l.int(1, "остаток перенацеливаний", 0, i64::from(u32::MAX))? as u32);
}
"airintel" => { "airintel" => {
if w.len() != 1 + ew::SECTORS * 2 { if w.len() != 1 + ew::SECTORS * 2 {
return Err(l.bad("счётчики секторов", &format!("нужны {} чисел", ew::SECTORS * 2))); return Err(l.bad("счётчики секторов", &format!("нужны {} чисел", ew::SECTORS * 2)));
@@ -498,6 +535,21 @@ impl Sim {
} }
intel = Some(v); intel = Some(v);
} }
"airlearn" => {
let n = l.count(1, "исходы", ew::MAX_OUTCOMES)?;
if w.len() != 2 + n * 3 {
return Err(l.bad("исходы", "нужны сектор, такт и исход каждого"));
}
if !outcomes.is_empty() {
return Err(l.bad("исходы", "окно записано дважды"));
}
for i in 0..n {
let sector = l.int(2 + i * 3, "сектор исхода", 0, ew::SECTORS as i64 - 1)? as u8;
let t = l.int(3 + i * 3, "такт исхода", 0, tick as i64)? as u64;
let killed = l.int(4 + i * 3, "исход", 0, 1)? == 1;
outcomes.push(ew::Learned { sector, tick: t, killed });
}
}
"airglobal" => { "airglobal" => {
if w.len() != 2 { if w.len() != 2 {
return Err(l.bad("рельеф", "нужна одна ссылка на версию рельефа")); return Err(l.bad("рельеф", "нужна одна ссылка на версию рельефа"));
@@ -601,7 +653,7 @@ impl Sim {
let unit = l.int(6, "юнит", 0, 1 << 30)? as u32; let unit = l.int(6, "юнит", 0, 1 << 30)? as u32;
let version = l.int(7, "версия знаний", 0, tick as i64)? as u64; let version = l.int(7, "версия знаний", 0, tick as i64)? as u64;
let priority = l.int(8, "приоритет", 0, 9)? as u8; let priority = l.int(8, "приоритет", 0, 9)? as u8;
let intent = intent_of(l.word(9, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; let intent = intent_of(l.word(9, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react, replace или refresh"))?;
if priority != intent.priority() { if priority != intent.priority() {
return Err(l.bad("приоритет", "не совпадает с намерением")); return Err(l.bad("приоритет", "не совпадает с намерением"));
} }
@@ -634,7 +686,7 @@ impl Sim {
recon.drone_next = drone_next; recon.drone_next = drone_next;
} }
"airreconmark" => { "airreconmark" => {
if w.len() != 14 { if !matches!(w.len(), 14 | 16) {
return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена")); return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена"));
} }
let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32; let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32;
@@ -657,6 +709,10 @@ impl Sim {
let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64; let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64;
let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64; let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64;
let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16; let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16;
let launches = if w.len() == 16 { l.int(14, "видимые пуски", 0, u16::MAX as i64)? as u16 } else { 0 };
let last_launch = if w.len() == 16 && w[15] != "-" {
Some(l.int(15, "такт последнего пуска", 0, tick as i64)? as u64)
} else { None };
if recon.marks.contains_key(&id) { if recon.marks.contains_key(&id) {
return Err(l.bad("id отметки", "отметка записана дважды")); return Err(l.bad("id отметки", "отметка записана дважды"));
} }
@@ -672,6 +728,8 @@ impl Sim {
reported, reported,
quality, quality,
looks, looks,
launches,
last_launch,
}); });
let slot = id.saturating_sub(recon::ID_BASE); let slot = id.saturating_sub(recon::ID_BASE);
recon.next = recon.next.max(slot); recon.next = recon.next.max(slot);
@@ -715,8 +773,8 @@ impl Sim {
recon_expect.push((pending, zones)); recon_expect.push((pending, zones));
} }
"airrecobs" => { "airrecobs" => {
if w.len() != 11 { if w.len() != 11 && w.len() != 12 {
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт")); return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник, такт и признак остова"));
} }
let Some(at) = recon_sortie_at else { let Some(at) = recon_sortie_at else {
return Err(l.bad("наблюдение разведки", "строка без разведчика")); return Err(l.bad("наблюдение разведки", "строка без разведчика"));
@@ -739,7 +797,10 @@ impl Sim {
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?; let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?; let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?;
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64; let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed }); // An older save has no wreck flag: every pending look it holds is of a unit
// that was alive when it was seen.
let wreck = if w.len() > 11 { l.flag(11, "остов")? } else { false };
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed, wreck });
} }
"airreczone" => { "airreczone" => {
if w.len() != 5 { if w.len() != 5 {
@@ -821,8 +882,10 @@ impl Sim {
Ok(Some(AirSave { Ok(Some(AirSave {
tick, tick,
job_next, job_next,
diversions_left: diversions_left.unwrap_or(0),
kills, kills,
hits, hits,
outcomes,
contacts: contacts.into_values().collect(), contacts: contacts.into_values().collect(),
drones: drones.into_values().collect(), drones: drones.into_values().collect(),
queue, queue,
@@ -837,35 +900,45 @@ impl Sim {
/// job whose drone, aim or unit no longer stands is dropped — a restored job is never a ghost. /// job whose drone, aim or unit no longer stands is dropped — a restored job is never a ghost.
/// The live air state is replaced, never merged: what the sky held before the load goes. /// The live air state is replaced, never merged: what the sky held before the load goes.
pub fn restore_air(&mut self, save: AirSave) -> u32 { pub fn restore_air(&mut self, save: AirSave) -> u32 {
self.breakthroughs.active.clear();
self.diversions_left = save.diversions_left;
self.tick = save.tick; self.tick = save.tick;
// New jobs must not reuse an id a restored job already holds. // New jobs must not reuse an id a restored job already holds.
let highest = save.jobs.iter().map(|j| j.id).max().unwrap_or(0); let highest = save.jobs.iter().map(|j| j.id).max().unwrap_or(0);
self.job_next = save.job_next.max(1).max(highest.saturating_add(1)); self.job_next = save.job_next.max(1).max(highest.saturating_add(1));
self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits); self.intel = ew::Intel::restore(save.contacts.clone(), save.kills, save.hits, save.outcomes.clone());
self.known_relief = save.known_relief; self.known_relief = save.known_relief;
self.drones = save.drones; self.drones = save.drones;
for d in &self.drones {
self.breakthroughs.begin(d.id, false);
}
self.queue = save.queue; self.queue = save.queue;
self.recon = save.recon;
let alive: std::collections::HashSet<u32> = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect(); let alive: std::collections::HashSet<u32> = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect();
self.recon.retain_drones(&alive);
self.recon.expire(self.tick);
self.retargets.clear(); self.retargets.clear();
// A job's picture is its version's: the contacts observed no later than it, plus its own // A job's picture is its version's: the contacts observed no later than it, plus its own
// target (whose last saved observation stands in for one made after the version). // target (whose last saved observation stands in for one made after the version), and the
let mut by_version: HashMap<u64, std::sync::Arc<Vec<ew::Contact>>> = HashMap::new(); // recon marks reported by then. The snapshot keeps the version's tick: the job ages its
// contacts at that tick, not at the tick the restored queue reaches it (#146).
let mut by_version: HashMap<u64, std::sync::Arc<ew::KnowledgeSnapshot>> = HashMap::new();
for rec in save.jobs { for rec in save.jobs {
let known = by_version.entry(rec.version).or_insert_with(|| { let known = by_version.entry(rec.version).or_insert_with(|| {
let picture: Vec<ew::Contact> = save let contacts: Vec<ew::Contact> = save
.contacts .contacts
.iter() .iter()
.filter(|c| c.tick <= rec.version || c.id == rec.unit) .filter(|c| c.tick <= rec.version || c.id == rec.unit)
.copied() .copied()
.collect(); .collect();
std::sync::Arc::new(picture) let marks = save.recon.leads(rec.version).into_iter().filter(|m| m.observed <= rec.version).collect();
std::sync::Arc::new(ew::KnowledgeSnapshot { tick: rec.version, contacts, marks })
}); });
let job = ew::RouteJob::restored(rec.id, rec.drone, rec.aim, rec.unit, rec.version, rec.intent, std::sync::Arc::clone(known), rec.relief); let job = ew::RouteJob::restored(rec.id, rec.drone, rec.aim, rec.unit, rec.version, rec.intent, std::sync::Arc::clone(known), rec.relief);
self.retargets.push_back(job); self.retargets.push_back(job);
} }
// The recon memory goes back after the jobs' snapshots were read from the save's own: a
// job's version keeps the marks reported by then, not what survives today's expiry.
self.recon = save.recon;
self.recon.retain_drones(&alive);
self.recon.expire(self.tick);
// Jobs the saved picture no longer stands behind, and anything past the bound, go now. // Jobs the saved picture no longer stands behind, and anything past the bound, go now.
self.prune_air() self.prune_air()
} }
@@ -880,7 +953,7 @@ fn parse_drone(l: &Line, first: usize) -> Result<(Drone, usize), String> {
let vel = DVec3::new(l.num(first + 5, "скорость X")?, l.num(first + 6, "скорость Y")?, l.num(first + 7, "скорость Z")?); let vel = DVec3::new(l.num(first + 5, "скорость X")?, l.num(first + 6, "скорость Y")?, l.num(first + 7, "скорость Z")?);
let target = DVec3::new(l.num(first + 8, "цель X")?, l.num(first + 9, "цель Y")?, l.num(first + 10, "цель Z")?); let target = DVec3::new(l.num(first + 8, "цель X")?, l.num(first + 9, "цель Y")?, l.num(first + 10, "цель Z")?);
let flight = flight_of(l.word(first + 11, "полёт")?).ok_or_else(|| l.bad("полёт", "cruise, dive, ballistic или falling"))?; let flight = flight_of(l.word(first + 11, "полёт")?).ok_or_else(|| l.bad("полёт", "cruise, dive, ballistic или falling"))?;
let intent = intent_of(l.word(first + 12, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react или replace"))?; let intent = intent_of(l.word(first + 12, "намерение")?).ok_or_else(|| l.bad("намерение", "plan, sead, react, replace или refresh"))?;
let unit = l.int(first + 13, "юнит намерения", 0, 1 << 30)? as u32; let unit = l.int(first + 13, "юнит намерения", 0, 1 << 30)? as u32;
let since = l.int(first + 14, "такт выбора цели", 0, 1 << 40)? as u64; let since = l.int(first + 14, "такт выбора цели", 0, 1 << 40)? as u64;
let switches = l.int(first + 15, "переключения", 0, u16::MAX as i64)? as u16; let switches = l.int(first + 15, "переключения", 0, u16::MAX as i64)? as u16;
@@ -973,13 +1046,14 @@ mod durable_tests {
let id = sim.id(); let id = sim.id();
let at = DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0); let at = DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0);
let c = contact(id, kind, at, 10, if kind == SamKind::Ew { ew::Seen::Jamming } else { ew::Seen::Emission }, k as u16); let c = contact(id, kind, at, 10, if kind == SamKind::Ew { ew::Seen::Jamming } else { ew::Seen::Emission }, k as u16);
sim.intel = ew::Intel::restore([c].to_vec(), [0; ew::SECTORS], [0; ew::SECTORS]); sim.intel = ew::Intel::restore([c].to_vec(), [0; ew::SECTORS], [0; ew::SECTORS], Vec::new());
ids.push(id); ids.push(id);
} }
sim.intel = ew::Intel::restore( sim.intel = ew::Intel::restore(
ids.iter().enumerate().map(|(k, id)| contact(*id, [SamKind::S400, SamKind::Radar, SamKind::Ew][k], DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0), 10, ew::Seen::Emission, k as u16)).collect(), ids.iter().enumerate().map(|(k, id)| contact(*id, [SamKind::S400, SamKind::Radar, SamKind::Ew][k], DVec3::new(-400.0 + k as f64 * 400.0, 70.0, 0.0), 10, ew::Seen::Emission, k as u16)).collect(),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
Vec::new(),
); );
sim.tick = 120; sim.tick = 120;
sim.job_next = 7; sim.job_next = 7;
@@ -1004,7 +1078,8 @@ mod durable_tests {
sim.queue.push((300, queued)); sim.queue.push((300, queued));
// Two pending jobs: one of the plan, one a replacement, both with their own version. // Two pending jobs: one of the plan, one a replacement, both with their own version.
let job = |id, drone, aim, unit, version, intent| { let job = |id, drone, aim, unit, version, intent| {
ew::RouteJob::restored(id, drone, aim, unit, version, intent, std::sync::Arc::new(sim.intel.contacts().values().copied().collect()), sim.known_relief.clone()) let known = ew::KnowledgeSnapshot { tick: version, contacts: sim.intel.contacts().values().copied().collect(), marks: Vec::new() };
ew::RouteJob::restored(id, drone, aim, unit, version, intent, std::sync::Arc::new(known), sim.known_relief.clone())
}; };
sim.retargets.push_back(job(5, sim.drones[0].id, sim.drones[0].target, ids[0], 100, ew::Intent::React)); sim.retargets.push_back(job(5, sim.drones[0].id, sim.drones[0].target, ids[0], 100, ew::Intent::React));
let queued_target = sim.queue[0].1.target; let queued_target = sim.queue[0].1.target;
@@ -1064,7 +1139,7 @@ mod durable_tests {
let id = sim.id(); let id = sim.id();
contacts.push(contact(id, SamKind::S400, DVec3::new(-560.0 + k as f64 * 160.0, 70.0, -320.0), 0, ew::Seen::Emission, 0)); contacts.push(contact(id, SamKind::S400, DVec3::new(-560.0 + k as f64 * 160.0, 70.0, -320.0), 0, ew::Seen::Emission, 0));
} }
sim.intel = ew::Intel::restore(contacts, [0; ew::SECTORS], [0; ew::SECTORS]); sim.intel = ew::Intel::restore(contacts, [0; ew::SECTORS], [0; ew::SECTORS], Vec::new());
for i in 0..40 { for i in 0..40 {
let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0); let from = DVec3::new(-1800.0, 100.0, -800.0 + i as f64 * 40.0);
let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0)); let mut d = sim.make_drone(DroneKind::Kh22, from, DVec3::X, DVec3::new(1800.0, 70.0, 1800.0));
@@ -1128,7 +1203,7 @@ mod durable_tests {
let kept = sim.retargets.len(); let kept = sim.retargets.len();
let some = sim.retargets[0].clone(); let some = sim.retargets[0].clone();
// A job for a drone that is not here. // A job for a drone that is not here.
sim.retargets.push_back(ew::RouteJob::restored(900, 999_999, DVec3::ZERO, 0, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); sim.retargets.push_back(ew::RouteJob::restored(900, 999_999, DVec3::ZERO, 0, sim.tick, ew::Intent::Plan, std::sync::Arc::new(ew::KnowledgeSnapshot::empty(sim.tick)), None));
// A job whose aim is no longer its drone's. // A job whose aim is no longer its drone's.
let mut stale = some.clone(); let mut stale = some.clone();
stale.id = 901; stale.id = 901;
+464 -76
View File
@@ -45,6 +45,9 @@ pub enum Intent {
/// A replacement: the picture watched the previous aim die or forgot it, and this contact /// A replacement: the picture watched the previous aim die or forgot it, and this contact
/// is the nearest live one. /// is the nearest live one.
Replace, Replace,
/// A bounded refresh (#149): a recon report arrived while the raid's drones were still
/// waiting to launch, and the plan's own picks were re-aimed once on the fresh snapshot.
Refresh,
} }
impl Intent { impl Intent {
@@ -54,6 +57,7 @@ impl Intent {
Self::Sead => "sead", Self::Sead => "sead",
Self::React => "react", Self::React => "react",
Self::Replace => "replace", Self::Replace => "replace",
Self::Refresh => "refresh",
} }
} }
/// The key a save writes and reads. /// The key a save writes and reads.
@@ -61,14 +65,15 @@ impl Intent {
self.name() self.name()
} }
pub(super) fn from_key(key: &str) -> Option<Self> { pub(super) fn from_key(key: &str) -> Option<Self> {
[Self::Plan, Self::Sead, Self::React, Self::Replace].into_iter().find(|i| i.key() == key) [Self::Plan, Self::Sead, Self::React, Self::Replace, Self::Refresh].into_iter().find(|i| i.key() == key)
} }
/// The planner's share of a tick this aim is worth: a planned SEAD job and a reaction to a /// The planner's share of a tick this aim is worth: a planned SEAD job and a reaction to a
/// disclosure are finished before a replacement, and the plan's own objective before both (#127). /// disclosure are finished before a replacement, and the plan's own objective before both (#127).
/// A refresh of the unreleased portion is worth a SEAD job's share (#149).
pub(super) fn priority(self) -> u8 { pub(super) fn priority(self) -> u8 {
match self { match self {
Self::Plan => 3, Self::Plan => 3,
Self::Sead => 2, Self::Sead | Self::Refresh => 2,
Self::React => 1, Self::React => 1,
Self::Replace => 0, Self::Replace => 0,
} }
@@ -114,8 +119,9 @@ pub(super) struct RouteJob {
pub(super) unit: u32, pub(super) unit: u32,
/// The adaptive tick whose picture chose the aim: the knowledge version. /// The adaptive tick whose picture chose the aim: the knowledge version.
pub(super) version: u64, pub(super) version: u64,
/// The enemy picture that tick knew, shared by every job of the tick. /// The enemy knowledge that tick chose the aim from, shared by every job of the tick: its
pub(super) known: Arc<Vec<Contact>>, /// contacts are aged at its own tick, not at the tick the job gets its budget (#146).
pub(super) known: Arc<KnowledgeSnapshot>,
/// The land that tick's plan knew, shared by every job of the version. A later plan replacing the /// The land that tick's plan knew, shared by every job of the version. A later plan replacing the
/// global snapshot must not change a pending job's relief (#127). /// global snapshot must not change a pending job's relief (#127).
pub(super) relief: Option<Arc<KnownRelief>>, pub(super) relief: Option<Arc<KnownRelief>>,
@@ -125,14 +131,14 @@ pub(super) struct RouteJob {
impl RouteJob { impl RouteJob {
/// A job of this tick's picture; the id and the priority follow from the intent. /// A job of this tick's picture; the id and the priority follow from the intent.
fn new(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<Vec<Contact>>, relief: Option<Arc<KnownRelief>>) -> Self { fn new(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<KnowledgeSnapshot>, relief: Option<Arc<KnownRelief>>) -> Self {
Self { id, drone, aim, unit, version, known, relief, intent } Self { id, drone, aim, unit, version, known, relief, intent }
} }
pub(super) fn priority(&self) -> u8 { pub(super) fn priority(&self) -> u8 {
self.intent.priority() self.intent.priority()
} }
/// A job read back from a save: its id, aim, unit, version, picture and relief are the file's. /// A job read back from a save: its id, aim, unit, version, picture and relief are the file's.
pub(super) fn restored(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<Vec<Contact>>, relief: Option<Arc<KnownRelief>>) -> Self { pub(super) fn restored(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc<KnowledgeSnapshot>, relief: Option<Arc<KnownRelief>>) -> Self {
Self { id, drone, aim, unit, version, known, relief, intent } Self { id, drone, aim, unit, version, known, relief, intent }
} }
} }
@@ -145,6 +151,11 @@ pub(super) struct KnownRelief {
} }
impl KnownRelief { impl KnownRelief {
/// What the relief holds, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.heights)
}
pub(super) fn new(grid: raid::Grid, heights: Vec<f32>) -> Self { pub(super) fn new(grid: raid::Grid, heights: Vec<f32>) -> Self {
Self { grid, heights } Self { grid, heights }
} }
@@ -190,7 +201,7 @@ impl RouteJob {
aim: DVec3, aim: DVec3,
unit: u32, unit: u32,
version: u64, version: u64,
known: Arc<Vec<Contact>>, known: Arc<KnowledgeSnapshot>,
relief: Option<Arc<KnownRelief>>, relief: Option<Arc<KnownRelief>>,
) -> Self { ) -> Self {
Self { id: drone, drone, aim, unit, version, known, relief, intent: Intent::Plan } Self { id: drone, drone, aim, unit, version, known, relief, intent: Intent::Plan }
@@ -245,6 +256,16 @@ pub(super) const JOB_TTL: u64 = 1200;
/// What a cell of land a job's knowledge version does not know costs on top of the open ground /// What a cell of land a job's knowledge version does not know costs on top of the open ground
/// (the base cell is 1): unknown land is not free, so a replanned route keeps to what was mapped (#127). /// (the base cell is 1): unknown land is not free, so a replanned route keeps to what was mapped (#127).
pub(super) const UNKNOWN_LAND: f32 = 6.0; pub(super) const UNKNOWN_LAND: f32 = 6.0;
/// How long a smart raid's unreleased portion may wait for a recon report to refresh its aims
/// (#149). A report due later than this is left to the adaptive ticks; nothing pauses for ever.
pub(super) const REFRESH_WINDOW: u64 = 600;
/// The pending refresh of a raid's unreleased portion (#149): the absolute deadline and the
/// report count it waits to pass. Transient — a save drops it, the launches keep their times.
pub(super) struct Refresh {
pub(super) deadline: u64,
pub(super) reports: u32,
}
/// How a contact's trust decays with age alone (#127). The bands are the only source of /// How a contact's trust decays with age alone (#127). The bands are the only source of
/// confidence: nothing is invented about a unit between observations. /// confidence: nothing is invented about a unit between observations.
@@ -371,6 +392,40 @@ impl Contact {
} }
} }
/// One version of the enemy's knowledge (#146): the tick it was observed at, the disclosure
/// contacts and the recon marks live then. A smart order chooses its targets and prices every
/// kind's routes on this one snapshot; a retarget version ages its contacts at its own tick,
/// never at the tick the planner's budget happens to reach the job. The current time may cancel
/// a stale job, but it never re-ages the snapshot the job was chosen from.
#[derive(Clone)]
pub(super) struct KnowledgeSnapshot {
/// The tick the contacts and marks were observed at.
pub(super) tick: u64,
pub(super) contacts: Vec<Contact>,
pub(super) marks: Vec<recon::Mark>,
}
impl KnowledgeSnapshot {
/// What the snapshot holds, about (see `sim::memory`); shared `Arc`s are counted per holder.
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.contacts) + vec_bytes(&self.marks)
}
pub(super) fn new(tick: u64, contacts: Vec<Contact>, marks: Vec<recon::Mark>) -> Self {
Self { tick, contacts, marks }
}
/// A version that knows nothing: for a job whose picture is empty.
#[cfg(test)]
pub(super) fn empty(tick: u64) -> Self {
Self { tick, contacts: Vec::new(), marks: Vec::new() }
}
/// The one public hint list of this version (#149): contacts and marks merged by public
/// features, ranked on the single scale. The snapshot's own tick ages every hint.
pub(super) fn observations(&self) -> Vec<Observation> {
observe::merge(&self.contacts, &self.marks, self.tick)
}
}
/// The radar reach the enemy's planners price by: the type's published figure, undamaged /// The radar reach the enemy's planners price by: the type's published figure, undamaged
/// and role-default. What a unit suffers or is configured to while unobserved is not in it. /// and role-default. What a unit suffers or is configured to while unobserved is not in it.
pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f64 { pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f64 {
@@ -383,17 +438,90 @@ pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f
radar.min(horizon).max(sight::NEAR) radar.min(horizon).max(sight::NEAR)
} }
/// One raid outcome the bearing memory keeps (#149): the sector it came from, when, and its fate.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Learned {
pub(super) sector: u8,
pub(super) tick: u64,
pub(super) killed: bool,
}
/// The bearing memory is a small window of the latest outcomes, not a lifetime tally (#149):
/// this many entries, and nothing older than `OUTCOME_WINDOW` is scored.
pub(super) const MAX_OUTCOMES: usize = 48;
pub(super) const OUTCOME_WINDOW: u64 = 12_000;
/// A window whose newest outcome is older than this is stale: the fight may have moved on.
pub(super) const OUTCOME_STALE: u64 = 6_000;
/// Why the bearing picker chose as it did (#149), in typed terms the diagnostic reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BearingReason {
/// The legacy fixed-share picker (the comparison runner's "current" mode).
FixedShare,
/// Too few outcomes in the window to trust a best sector: explore more.
FewObservations,
/// The window's newest outcome is old: explore more.
StaleResults,
/// The public picture's shape changed since the outcomes were learned: explore more.
ConditionsChanged,
/// Enough fresh outcomes under unchanged conditions: exploit the best sector.
Exploiting,
}
impl BearingReason {
pub fn name(self) -> &'static str {
match self {
Self::FixedShare => "fixed-share",
Self::FewObservations => "few-observations",
Self::StaleResults => "stale-results",
Self::ConditionsChanged => "conditions-changed",
Self::Exploiting => "exploiting",
}
}
}
/// The bearing picker's last decision, for the diagnostic (#149).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BearingReport {
pub sector: usize,
pub reason: BearingReason,
/// Outcomes scored (the window, not the lifetime tally).
pub observations: usize,
/// The best sector's window score.
pub score: f64,
/// The exploration share this decision used.
pub explore: f64,
}
impl Default for BearingReport {
fn default() -> Self {
Self { sector: 0, reason: BearingReason::FewObservations, observations: 0, score: 0.5, explore: 0.6 }
}
}
#[derive(Default)] #[derive(Default)]
pub(super) struct Intel { pub(super) struct Intel {
/// Shot down and got through, by approach sector, over every raid. /// Shot down and got through, by approach sector, over every raid (the lifetime tally the
/// legacy picker scores; the window below is what the candidate forgets and reasons about).
pub kills: [u32; SECTORS], pub kills: [u32; SECTORS],
pub hits: [u32; SECTORS], pub hits: [u32; SECTORS],
/// The last observation of each unit the enemy knows of, by id. One entry per unit: /// The last observation of each unit the enemy knows of, by id. One entry per unit:
/// a newer observation replaces the older, so no log ever needs rescanning (#122). /// a newer observation replaces the older, so no log ever needs rescanning (#122).
contacts: BTreeMap<u32, Contact>, contacts: BTreeMap<u32, Contact>,
/// The small window of recent raid outcomes the bearing picker scores (#149).
outcomes: VecDeque<Learned>,
/// The public picture's shape when the last outcome was learned: a change is a reason to
/// explore, never a read of the hidden force (#149).
conditions: u64,
} }
impl Intel { impl Intel {
/// What the enemy's memory holds, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{btree_bytes, vecdeque_bytes};
btree_bytes(self.contacts.len(), std::mem::size_of::<u32>() + std::mem::size_of::<Contact>())
+ vecdeque_bytes(&self.outcomes)
}
/// The picture as a save writes it, and back: the contacts (one per unit) and the sector scores. /// The picture as a save writes it, and back: the contacts (one per unit) and the sector scores.
pub(super) fn contacts(&self) -> &BTreeMap<u32, Contact> { pub(super) fn contacts(&self) -> &BTreeMap<u32, Contact> {
&self.contacts &self.contacts
@@ -401,15 +529,35 @@ impl Intel {
pub(super) fn sectors(&self) -> ([u32; SECTORS], [u32; SECTORS]) { pub(super) fn sectors(&self) -> ([u32; SECTORS], [u32; SECTORS]) {
(self.kills, self.hits) (self.kills, self.hits)
} }
pub(super) fn restore(contacts: Vec<Contact>, kills: [u32; SECTORS], hits: [u32; SECTORS]) -> Self { pub(super) fn outcomes(&self) -> &VecDeque<Learned> {
Self { kills, hits, contacts: contacts.into_iter().map(|c| (c.id, c)).collect() } &self.outcomes
}
pub(super) fn restore(contacts: Vec<Contact>, kills: [u32; SECTORS], hits: [u32; SECTORS], outcomes: Vec<Learned>) -> Self {
Self {
kills,
hits,
contacts: contacts.into_iter().map(|c| (c.id, c)).collect(),
outcomes: outcomes.into_iter().take(MAX_OUTCOMES).collect(),
conditions: 0,
}
} }
/// The one writer of contacts: what was seen of `s`, at its place, this moment. /// One outcome into the window, bounded: the oldest goes first (#149).
pub(super) fn learn(&mut self, sector: usize, killed: bool, now: u64, conditions: u64) {
self.outcomes.push_back(Learned { sector: (sector % SECTORS) as u8, tick: now, killed });
while self.outcomes.len() > MAX_OUTCOMES {
self.outcomes.pop_front();
}
self.conditions = conditions;
}
/// Fixture for the old exact disclosure format. New observations go through recon marks.
#[cfg(test)]
pub(super) fn observe(&mut self, s: &Sam, now: u64, seen: Seen) { pub(super) fn observe(&mut self, s: &Sam, now: u64, seen: Seen) {
self.note(s.id, s.kind, s.pos, s.alive(), now, seen); self.note(s.id, s.kind, s.pos, s.alive(), now, seen);
} }
#[cfg(test)]
pub(super) fn note(&mut self, id: u32, kind: SamKind, at: DVec3, alive: bool, now: u64, seen: Seen) { pub(super) fn note(&mut self, id: u32, kind: SamKind, at: DVec3, alive: bool, now: u64, seen: Seen) {
let c = self.contacts.entry(id).or_insert(Contact { id, kind, at, tick: now, seen, emission: None, destroyed: None, launches: 0 }); let c = self.contacts.entry(id).or_insert(Contact { id, kind, at, tick: now, seen, emission: None, destroyed: None, launches: 0 });
// The newest observation wins; a fresh look at a live unit clears an old wreck call. // The newest observation wins; a fresh look at a live unit clears an old wreck call.
@@ -511,9 +659,12 @@ impl Sim {
if now % 40 == 0 { if now % 40 == 0 {
out.sound("minecraft:block.beacon.ambient", top, 2.0, 1.4); out.sound("minecraft:block.beacon.ambient", top, 2.0, 1.4);
} }
// A transmitter on the air: the enemy finds it. // A hostile aircraft experiencing interference can report an area.
if now % 20 == 0 { if now % 20 == 0 && s.ew_up() && self.drones.iter().any(|d| d.alive()
self.intel.observe(s, now, Seen::Jamming); && !recon::is_drone_id(d.id) && d.kind.jammable()
&& horizontal(d.pos - s.pos).length_squared() < EW_RADIUS * EW_RADIUS)
{
self.recon.signal(s, now, recon::Source::Jamming);
} }
} }
} }
@@ -532,24 +683,77 @@ impl Sim {
} }
} }
/// What the enemy's raids learned: their drones' fates by sector. /// What the enemy's raids learned: their drones' fates by sector, into the lifetime tally
/// and the small recent window the bearing picker scores (#149).
pub(super) fn learn(&mut self, sector: usize, killed: bool) { pub(super) fn learn(&mut self, sector: usize, killed: bool) {
if killed { if killed {
self.intel.kills[sector % SECTORS] += 1; self.intel.kills[sector % SECTORS] += 1;
} else { } else {
self.intel.hits[sector % SECTORS] += 1; self.intel.hits[sector % SECTORS] += 1;
} }
let conditions = self.picture_fingerprint();
self.intel.learn(sector, killed, self.tick, conditions);
} }
/// The bearing a smart raid comes from: the sector its raids got through best, a little random. /// The public picture's shape (#149): how many live hints of each category the enemy holds.
/// A fingerprint of beliefs only — no health, magazine, switch or true place is read.
pub(super) fn picture_fingerprint(&self) -> u64 {
let now = self.tick;
let mut h: u64 = 0xCBF2_9CE4_8422_2325;
let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0000_0100_0000_01B3);
let mut cats = [0u32; 6];
for c in self.intel.contacts.values().filter(|c| c.live(now)) {
cats[recon::Category::of(c.kind) as usize] += 1;
}
for m in self.recon.marks.values().filter(|m| m.live(now)) {
cats[m.category as usize] += 1;
}
for n in cats {
mix(u64::from(n));
}
h
}
/// The bearing a smart raid comes from (#149). The candidate scores a small window of the
/// latest outcomes, forgets the old ones, and adapts its exploration share to what the
/// window can support — few observations, a stale result or changed public conditions each
/// named as a typed reason. The legacy mode keeps the lifetime tally and the fixed share.
pub(super) fn best_bearing(&mut self) -> f64 { pub(super) fn best_bearing(&mut self) -> f64 {
let score = |i: usize| { let now = self.tick;
let (k, h) = (self.intel.kills[i] as f64, self.intel.hits[i] as f64); let (pick, report) = if self.smart_legacy {
(h + 1.0) / (k + h + 2.0) let score = |i: usize| {
let (k, h) = (self.intel.kills[i] as f64, self.intel.hits[i] as f64);
(h + 1.0) / (k + h + 2.0)
};
let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0);
// Unknown sectors are worth a look too.
let pick = if self.rng.chance(0.3) { (self.rng.f() * SECTORS as f64) as usize } else { best };
let observations = self.intel.kills.iter().chain(self.intel.hits.iter()).map(|n| *n as usize).sum();
(pick, BearingReport { sector: pick, reason: BearingReason::FixedShare, observations, score: score(best), explore: 0.3 })
} else {
let window: Vec<&Learned> = self.intel.outcomes.iter().filter(|o| now.saturating_sub(o.tick) <= OUTCOME_WINDOW).collect();
let total = window.len();
let newest = window.iter().map(|o| o.tick).max().unwrap_or(0);
let conditions = self.picture_fingerprint();
let (reason, explore) = if total < 6 {
(BearingReason::FewObservations, 0.6)
} else if now.saturating_sub(newest) > OUTCOME_STALE {
(BearingReason::StaleResults, 0.5)
} else if conditions != self.intel.conditions {
(BearingReason::ConditionsChanged, 0.45)
} else {
(BearingReason::Exploiting, 0.15)
};
let score = |i: usize| {
let k = window.iter().filter(|o| o.sector as usize == i && o.killed).count() as f64;
let h = window.iter().filter(|o| o.sector as usize == i && !o.killed).count() as f64;
(h + 1.0) / (k + h + 2.0)
};
let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0);
let pick = if self.rng.chance(explore) { (self.rng.f() * SECTORS as f64) as usize } else { best };
(pick, BearingReport { sector: pick, reason, observations: total, score: score(best), explore })
}; };
let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0); self.bearing = report;
// Unknown sectors are worth a look too.
let pick = if self.rng.chance(0.3) { (self.rng.f() * SECTORS as f64) as usize } else { best };
(pick as f64 + 0.5 + self.rng.s() * 0.4) / SECTORS as f64 * TAU (pick as f64 + 0.5 + self.rng.s() * 0.4) / SECTORS as f64 * TAU
} }
@@ -564,9 +768,79 @@ impl Sim {
out out
} }
/// The knowledge this moment holds, as one snapshot for a whole decision (#146): the tick,
/// the contacts and the recon marks, read once and never re-read per kind or per job.
pub(super) fn knowledge_now(&self) -> KnowledgeSnapshot {
KnowledgeSnapshot { tick: self.tick, contacts: self.picture_of_defences(), marks: self.recon.leads(self.tick) }
}
/// The bounded refresh of a raid's unreleased portion (#149): a recon flight is out, and the
/// plan's own picks may be re-aimed once when a report arrives. The deadline is absolute — no
/// report, no delay: the launches keep their times either way.
pub(super) fn step_refresh(&mut self, out: &mut Out) {
let Some(r) = self.refresh.take() else { return };
if self.tick > r.deadline {
return;
}
if self.recon.reports <= r.reports {
self.refresh = Some(r);
return;
}
// A report arrived: one fresh snapshot, one bounded pass over the drones still waiting
// to launch. Only the plan's own picks are re-aimed, once, within the switch cap.
let knowledge = self.knowledge_now();
let obs = knowledge.observations();
let known = Arc::new(knowledge);
let relief = self.known_relief.clone();
let now = self.tick;
let mut per: HashMap<u32, usize> = HashMap::new();
let mut assigned = 0usize;
let mut changed = 0u32;
let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
let mut jobs: Vec<RouteJob> = Vec::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic && matches!(d.intent, Intent::Plan | Intent::Sead)) {
if assigned >= ASSIGN_PER_TICK || d.aim.switches >= SWITCH_CAP
|| d.kind.spec().decoy || (d.aim.unit == 0 && diversions_left == 0)
{
continue;
}
let Some(o) = obs.iter().find(|o| {
o.confidence(now) >= Confidence::Probable
&& (o.kind.is_some() || observe::fits(d.kind, o.category))
&& o.id != d.aim.unit
&& per.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT
}) else {
continue;
};
*per.entry(o.id).or_insert(0) += 1;
assigned += 1;
changed += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = o.at + d.err;
d.intent = Intent::Refresh;
d.aim = d.aim.replaced(o.id, now, o.confidence(now));
if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Refresh, Arc::clone(&known), relief.clone()));
job_next += 1;
} else {
d.route.clear();
}
}
self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs {
self.queue_route(job);
}
if changed > 0 {
self.refresh_applied = self.refresh_applied.saturating_add(changed);
out.messages.push(format!("Разведка противника: донесение изменило план налёта ({changed} целей)"));
}
}
/// Whether the picture holds a live contact for this unit: what the old revelation log /// Whether the picture holds a live contact for this unit: what the old revelation log
/// answered at a scan, now one map lookup. /// answered at a scan, now one map lookup. A public belief, never the unit's truth.
pub(super) fn known_live(&self, id: u32) -> bool { pub fn known_live(&self, id: u32) -> bool {
if recon::is_mark(id) { if recon::is_mark(id) {
return self.recon.live(id, self.tick); return self.recon.live(id, self.tick);
} }
@@ -593,8 +867,13 @@ impl Sim {
fn adapt_targets(&mut self) { fn adapt_targets(&mut self) {
self.intel.expire(self.tick); self.intel.expire(self.tick);
self.recon.expire(self.tick); self.recon.expire(self.tick);
let picture = Arc::new(self.picture_of_defences()); // One knowledge version for every aim and job this adaptive tick chooses (#146).
let leads = self.recon.leads(self.tick); let knowledge = Arc::new(self.knowledge_now());
let picture = &knowledge.contacts;
let leads = &knowledge.marks;
// The candidate picks from the one merged hint list (#149); the legacy mode keeps the
// two separate lists and their old scales.
let obs = if self.smart_legacy { Vec::new() } else { knowledge.observations() };
if picture.is_empty() && leads.is_empty() { if picture.is_empty() && leads.is_empty() {
return; return;
} }
@@ -605,16 +884,17 @@ impl Sim {
// Job ids are taken from the simulation's counter: a job keeps its id when it is replaced in // Job ids are taken from the simulation's counter: a job keeps its id when it is replaced in
// place, and the save writes it back (#127). // place, and the save writes it back (#127).
let mut job_next = self.job_next; let mut job_next = self.job_next;
let mut diversions_left = self.diversions_left;
// The drones sent at a new target: a route job each, to be worked out as the planner's budget allows. // The drones sent at a new target: a route job each, to be worked out as the planner's budget allows.
let mut jobs: Vec<RouteJob> = Vec::new(); let mut jobs: Vec<RouteJob> = Vec::new();
let mut n = 0usize; let mut n = 0usize;
let mut assigned = 0usize; let mut assigned = 0usize;
let mut per_contact: HashMap<u32, usize> = HashMap::new(); let mut per_contact: HashMap<u32, usize> = HashMap::new();
for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart) { for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart && d.kind.spec().class != Class::Ballistic) {
let hunter = matches!(d.kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon); let hunter = matches!(d.kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
let eligible = hunter || (d.kind == DroneKind::Shahed && n % 4 == 0); let eligible = hunter || (d.kind == DroneKind::Shahed && n % 4 == 0);
n += 1; n += 1;
if !eligible { if !eligible || (d.aim.unit == 0 && diversions_left == 0) {
continue; continue;
} }
// A recon mark is an area, not a unit: it is kept while the mark lives. A // A recon mark is an area, not a unit: it is kept while the mark lives. A
@@ -635,11 +915,12 @@ impl Sim {
} }
*per_contact.entry(c.id).or_insert(0) += 1; *per_contact.entry(c.id).or_insert(0) += 1;
assigned += 1; assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = c.at + d.err; d.target = c.at + d.err;
d.intent = Intent::React; d.intent = Intent::React;
d.aim = d.aim.replaced(c.id, now, c.confidence(now)); d.aim = d.aim.replaced(c.id, now, c.confidence(now));
if Self::route_plannable(d) { if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&knowledge), relief.clone()));
job_next += 1; job_next += 1;
} else { } else {
d.route.clear(); d.route.clear();
@@ -651,32 +932,40 @@ impl Sim {
if assigned >= ASSIGN_PER_TICK { if assigned >= ASSIGN_PER_TICK {
continue; continue;
} }
let exact = Self::fresh_target(&picture, &per_contact, d.kind, n); // The candidate picks from the one merged hint list (#149): a matched mark is not a
// No disclosure contact to take: a recon mark whose observed role fits this drone, // second target, and both channels rank on the same public scale. The legacy mode
// best role and freshest first, bounded per mark as any assignment is. Where both // keeps the two separate lists and their old scales.
// exist, the better observed role and fresher mark wins; a hidden unit is in neither. let (at, unit, confidence) = if self.smart_legacy {
let mark = Self::fresh_recon_target(&leads, &per_contact); let exact = Self::fresh_target(&picture, &per_contact, d.kind, n);
let (at, unit, confidence) = match (exact, mark) { let mark = Self::fresh_recon_target(&leads, &per_contact);
(Some(c), Some(m)) => { match (exact, mark) {
let exact_rank = Self::exact_rank(&c, now); (Some(c), Some(m)) => {
if m.priority(now) > exact_rank { let exact_rank = Self::exact_rank(&c, now);
(m.area, m.id, m.confidence(now)) if m.priority(now) > exact_rank {
} else { (m.area, m.id, m.confidence(now))
(c.at, c.id, c.confidence(now)) } else {
(c.at, c.id, c.confidence(now))
}
} }
(Some(c), None) => (c.at, c.id, c.confidence(now)),
(None, Some(m)) => (m.area, m.id, m.confidence(now)),
(None, None) => continue,
}
} else {
match Self::fresh_observation(&obs, &per_contact, d.kind, n) {
Some(o) => (o.at, o.id, o.confidence(now)),
None => continue,
} }
(Some(c), None) => (c.at, c.id, c.confidence(now)),
(None, Some(m)) => (m.area, m.id, m.confidence(now)),
(None, None) => continue,
}; };
*per_contact.entry(unit).or_insert(0) += 1; *per_contact.entry(unit).or_insert(0) += 1;
assigned += 1; assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = at + d.err; d.target = at + d.err;
d.intent = Intent::React; d.intent = Intent::React;
// A first assignment is not a switch: the aim's clock starts here, the count is kept. // A first assignment is not a switch: the aim's clock starts here, the count is kept.
d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) }; d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) };
if Self::route_plannable(d) { if Self::route_plannable(d) {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&knowledge), relief.clone()));
job_next += 1; job_next += 1;
} else { } else {
// Nothing will be replanned for it: its old route leads to the old aim, so it goes straight. // Nothing will be replanned for it: its old route leads to the old aim, so it goes straight.
@@ -687,7 +976,10 @@ impl Sim {
// or forgotten after its contact aged out mid-flight, is replaced by the nearest live contact // or forgotten after its contact aged out mid-flight, is replaced by the nearest live contact
// it can still turn onto — or, past the switch cap, the drone keeps its course. A unit merely // it can still turn onto — or, past the switch cap, the drone keeps its course. A unit merely
// moved is still aimed where seen. // moved is still aimed where seen.
for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) { for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart && d.kind.spec().class != Class::Ballistic) {
if d.aim.unit == 0 && diversions_left == 0 {
continue;
}
let aim = d.target - d.err; let aim = d.target - d.err;
let aim_gone = if recon::is_mark(d.aim.unit) { let aim_gone = if recon::is_mark(d.aim.unit) {
!self.recon.live(d.aim.unit, self.tick) !self.recon.live(d.aim.unit, self.tick)
@@ -707,39 +999,51 @@ impl Sim {
if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK { if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK {
continue; continue;
} }
let exact = picture // The candidate replaces from the one merged hint list, best public rank first and
.iter() // nearest among equals (#149); the legacy mode keeps the two lists and their scales.
.filter(|c| !plannable || Self::can_turn_to(d, c.at)) let next = if self.smart_legacy {
.filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) let exact = picture
.map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now))) .iter()
.min_by(|a, b| a.0.total_cmp(&b.0)); .filter(|c| !plannable || Self::can_turn_to(d, c.at))
let mark = leads .filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.iter() .map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now)))
.filter(|m| !plannable || Self::can_turn_to(d, m.area)) .min_by(|a, b| a.0.total_cmp(&b.0));
.filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) let mark = leads
.map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now))) .iter()
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0))); .filter(|m| !plannable || Self::can_turn_to(d, m.area))
// A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal .filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
// freshness is preferred, because it is a fix rather than an area. .map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now)))
let exact_rank = exact.map(|(_, _, _, c)| match c { .min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)));
Confidence::Confirmed => 30, // A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal
Confidence::Probable => 15, // freshness is preferred, because it is a fix rather than an area.
Confidence::Doubtful => 0, let exact_rank = exact.map(|(_, _, _, c)| match c {
}); Confidence::Confirmed => 30,
let next = match (exact, mark) { Confidence::Probable => 15,
(Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)), Confidence::Doubtful => 0,
(Some(e), _) => Some(e), });
(None, Some(m)) => Some((m.0, m.1, m.2, m.3)), match (exact, mark) {
(None, None) => None, (Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)),
(Some(e), _) => Some(e),
(None, Some(m)) => Some((m.0, m.1, m.2, m.3)),
(None, None) => None,
}
} else {
obs.iter()
.filter(|o| !plannable || Self::can_turn_to(d, o.at))
.filter(|o| per_contact.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
.map(|o| (o.at.distance(d.pos), o.id, o.at, o.confidence(now), o.rank(now)))
.min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0)))
.map(|(d, id, at, c, _)| (d, id, at, c))
}; };
if let Some((_, unit, at, confidence)) = next { if let Some((_, unit, at, confidence)) = next {
*per_contact.entry(unit).or_insert(0) += 1; *per_contact.entry(unit).or_insert(0) += 1;
assigned += 1; assigned += 1;
diversions_left -= u32::from(d.aim.unit == 0);
d.target = at + d.err; d.target = at + d.err;
d.intent = Intent::Replace; d.intent = Intent::Replace;
d.aim = d.aim.replaced(unit, now, confidence); d.aim = d.aim.replaced(unit, now, confidence);
if plannable { if plannable {
jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone())); jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&knowledge), relief.clone()));
job_next += 1; job_next += 1;
} else { } else {
d.route.clear(); d.route.clear();
@@ -747,6 +1051,7 @@ impl Sim {
} }
} }
self.job_next = job_next; self.job_next = job_next;
self.diversions_left = diversions_left;
for job in jobs { for job in jobs {
self.queue_route(job); self.queue_route(job);
} }
@@ -802,6 +1107,27 @@ impl Sim {
.find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) .find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT)
} }
/// The hint a drone not yet sent at a unit should be given (#149): one merged list, one
/// public scale. A transmitting jammer is the loudest disclosure, then (for the hunters)
/// anything that showed itself, then a round-robin over what fits — a disclosure contact
/// always fits, a recon mark only when the small policy says its category suits the kind.
fn fresh_observation(obs: &[Observation], per_contact: &HashMap<u32, usize>, kind: DroneKind, n: usize) -> Option<Observation> {
let free = |o: &&Observation| per_contact.get(&o.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT;
let jammers: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Ew && o.channel == recon::Source::Jamming).filter(free).collect();
if let Some(o) = jammers.get(n % jammers.len().max(1)) {
return Some(**o);
}
let hunters = matches!(kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon);
if hunters {
let shown: Vec<&Observation> = obs.iter().filter(|o| o.channel != recon::Source::Flyby).filter(free).collect();
if let Some(o) = shown.get(n % shown.len().max(1)) {
return Some(**o);
}
}
let fit: Vec<&Observation> = obs.iter().filter(|o| o.kind.is_some() || observe::fits(kind, o.category)).filter(free).collect();
fit.get(n % fit.len().max(1)).map(|o| **o)
}
/// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the /// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the
/// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the /// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the
/// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new /// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new
@@ -1007,7 +1333,7 @@ impl Sim {
Some(r) => r.clone(), Some(r) => r.clone(),
None => { None => {
if !prices.contains_key(&(kind, version)) { if !prices.contains_key(&(kind, version)) {
let (p, cost) = self.price_grid_known(&grid, kind, land, job.known.as_slice()); let (p, cost) = self.price_grid_known(&grid, kind, land, &job.known);
work += cost; work += cost;
prices.insert((kind, version), p); prices.insert((kind, version), p);
} }
@@ -1124,6 +1450,7 @@ pub struct ReconReport {
pub role: Option<&'static str>, pub role: Option<&'static str>,
/// "flyby", "emission", "jamming" or "launch". /// "flyby", "emission", "jamming" or "launch".
pub source: &'static str, pub source: &'static str,
pub launches: u16,
pub age: u64, pub age: u64,
/// "coarse" or "refined". /// "coarse" or "refined".
pub quality: &'static str, pub quality: &'static str,
@@ -1163,6 +1490,27 @@ pub struct PendingReport {
pub reason: &'static str, pub reason: &'static str,
} }
/// One merged public hint as the diagnostic reports it (#149): the one scale the planner ranks
/// and prices by, and whether a second channel agreed by public features (a belief, not a fact).
#[derive(Clone, Debug, PartialEq)]
pub struct ObservationReport {
pub id: u32,
pub at: DVec3,
pub radius: f64,
/// "flyby", "emission", "jamming" or "launch".
pub channel: &'static str,
pub age: u64,
pub confidence: Confidence,
pub category: &'static str,
pub role: Option<&'static str>,
/// The identified type of a disclosure contact; `None` for a recon mark's area.
pub kind: Option<&'static str>,
pub quality: &'static str,
/// A second public hint matched by area and category. Never a hidden truth.
pub matched: bool,
pub rank: u8,
}
/// The enemy's whole picture at one tick: what it knows and what it assumes, structured for /// The enemy's whole picture at one tick: what it knows and what it assumes, structured for
/// diagnostics (#127). No truth anywhere in it — a unit the picture got wrong is reported wrong. /// diagnostics (#127). No truth anywhere in it — a unit the picture got wrong is reported wrong.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -1179,6 +1527,14 @@ pub struct EnemyPictureReport {
pub recon: Vec<ReconReport>, pub recon: Vec<ReconReport>,
/// The recon flights still out. /// The recon flights still out.
pub recon_sorties: Vec<ReconSortieReport>, pub recon_sorties: Vec<ReconSortieReport>,
/// The one merged hint list the candidate planner ranks and prices by (#149).
pub observations: Vec<ObservationReport>,
/// The bearing picker's last decision and its typed reason (#149).
pub bearing: BearingReport,
/// Whether a bounded refresh of the unreleased portion is still waiting for a report (#149).
pub refresh_waiting: bool,
/// Aims the refresh has re-chosen so far (#149).
pub refresh_applied: u32,
} }
impl Sim { impl Sim {
@@ -1272,6 +1628,7 @@ impl Sim {
category: m.category.name(), category: m.category.name(),
role: m.role.map(|r| r.key()), role: m.role.map(|r| r.key()),
source: m.source.name(), source: m.source.name(),
launches: m.launches,
age: m.age(now), age: m.age(now),
quality: m.quality.name(), quality: m.quality.name(),
confidence: m.confidence(now), confidence: m.confidence(now),
@@ -1296,7 +1653,38 @@ impl Sim {
report_in: s.report_at.map(|t| t.saturating_sub(now)), report_in: s.report_at.map(|t| t.saturating_sub(now)),
}) })
.collect(); .collect();
EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties } let observations = self
.knowledge_now()
.observations()
.into_iter()
.map(|o| ObservationReport {
id: o.id,
at: o.at,
radius: o.radius,
channel: o.channel.name(),
age: o.age(now),
confidence: o.confidence(now),
category: o.category.name(),
role: o.role.map(|r| r.key()),
kind: o.kind.map(|k| k.spec().key),
quality: o.quality.name(),
matched: o.matched,
rank: o.rank(now),
})
.collect();
EnemyPictureReport {
now,
contacts,
aims,
pending,
work_per_tick: raid::WORK_PER_TICK,
recon,
recon_sorties,
observations,
bearing: self.bearing,
refresh_waiting: self.refresh.is_some(),
refresh_applied: self.refresh_applied,
}
} }
/// What the planner makes of a contact, in words for the diagnostic (#127). /// What the planner makes of a contact, in words for the diagnostic (#127).
@@ -1854,7 +2242,7 @@ mod intent_tests {
d.smart = true; d.smart = true;
let id = d.id; let id = d.id;
sim.drones.push(d); sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 0.0), 0, 1, Arc::new(Vec::new()), None)); sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 0.0), 0, 1, Arc::new(KnowledgeSnapshot::empty(1)), None));
} }
assert_eq!(sim.retargets.len(), JOBS_MAX); assert_eq!(sim.retargets.len(), JOBS_MAX);
// A replacement is worth less than a plan's objective: the queue refuses it. // A replacement is worth less than a plan's objective: the queue refuses it.
@@ -1862,7 +2250,7 @@ mod intent_tests {
d.smart = true; d.smart = true;
let id = d.id; let id = d.id;
sim.drones.push(d); sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 50.0), 0, 2, Arc::new(Vec::new()), None).with_intent(Intent::Replace)); sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 50.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Replace));
assert_eq!(sim.retargets.len(), JOBS_MAX, "a worthless job grew the queue"); assert_eq!(sim.retargets.len(), JOBS_MAX, "a worthless job grew the queue");
// Nothing queued is a replacement: a replacement is the lowest priority and does displace one. // Nothing queued is a replacement: a replacement is the lowest priority and does displace one.
sim.retargets.iter_mut().for_each(|j| j.intent = Intent::Replace); sim.retargets.iter_mut().for_each(|j| j.intent = Intent::Replace);
@@ -1870,7 +2258,7 @@ mod intent_tests {
d.smart = true; d.smart = true;
let id = d.id; let id = d.id;
sim.drones.push(d); sim.drones.push(d);
sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 60.0), 0, 2, Arc::new(Vec::new()), None).with_intent(Intent::Plan)); sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 60.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Plan));
assert_eq!(sim.retargets.len(), JOBS_MAX, "the bound was broken"); assert_eq!(sim.retargets.len(), JOBS_MAX, "the bound was broken");
assert!(sim.retargets.back().is_some_and(|j| j.drone == id && j.intent == Intent::Plan), "the plan's job did not make room"); assert!(sim.retargets.back().is_some_and(|j| j.drone == id && j.intent == Intent::Plan), "the plan's job did not make room");
} }
+7
View File
@@ -67,6 +67,13 @@ pub fn level(age: f64, life: f64) -> (f32, f32) {
} }
impl Fires { impl Fires {
/// What the fires hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.list)
+ self.list.iter().map(|f| vec_bytes(&f.blocks)).sum::<usize>()
+ self.cleanup.iter().map(|s| s.capacity()).sum::<usize>()
}
/// Fires burning now. /// Fires burning now.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.list.len() self.list.len()
+23 -42
View File
@@ -1,21 +1,11 @@
//! Logistics: once a depot stands, magazines are no longer refilled from //! Empty magazines are replenished from finite depot stock, either directly or via a truck.
//! nowhere. A system out of missiles waits; one within reach of a depot
//! reloads from its stock; the reload trucks fill up at a depot and drive
//! reloads to the systems that wait, nearest first, and back.
use super::*; use super::*;
impl Sim { impl Sim {
/// Whether ammunition is counted: a depot was set up (without one, magazines refill as
/// before). A destroyed depot still counts: losing the last one leaves the systems short,
/// not supplied from nowhere again.
pub fn logistics(&self) -> bool {
self.sams.iter().any(|s| s.kind == SamKind::Depot)
}
/// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there. /// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there.
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> { pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?; let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 { return Err("Для этого комплекса нет игрового профиля RM48U".into()); } if !s.kind.supports_rm48u() { return Err("Для этого комплекса нет игрового профиля RM48U".into()); }
if !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 { if !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 {
return Err("Комплекс должен быть исправен и развёрнут".into()); return Err("Комплекс должен быть исправен и развёрнут".into());
} }
@@ -50,7 +40,7 @@ impl Sim {
/// Return a loaded ground round to a nearby depot; restore a previously removed air round if available. /// Return a loaded ground round to a nearby depot; restore a previously removed air round if available.
pub fn unload_ground_round(&mut self, i: usize) -> Result<String, String> { pub fn unload_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?; let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 { if !s.kind.supports_rm48u() || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 {
return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into()); return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into());
} }
if s.ground_return { return Err("Заявка на вывоз RM48U уже ожидает ТЗМ".into()); } if s.ground_return { return Err("Заявка на вывоз RM48U уже ожидает ТЗМ".into()); }
@@ -76,7 +66,7 @@ impl Sim {
pub fn cancel_ground_request(&mut self, i: usize) -> Result<String, String> { pub fn cancel_ground_request(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get_mut(i).ok_or("Нет такого комплекса")?; let s = self.sams.get_mut(i).ok_or("Нет такого комплекса")?;
if s.kind != SamKind::S400 || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); } if !s.kind.supports_rm48u() || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); }
s.ground_request = false; s.ground_request = false;
s.ground_return = false; s.ground_return = false;
Ok(format!("С-400 №{}: заявка RM48U отменена", i + 1)) Ok(format!("С-400 №{}: заявка RM48U отменена", i + 1))
@@ -84,12 +74,6 @@ impl Sim {
/// Reloads from depots near the systems, and the trucks' rounds. /// Reloads from depots near the systems, and the trucks' rounds.
pub(super) fn step_supply(&mut self, out: &mut Out) { pub(super) fn step_supply(&mut self, out: &mut Out) {
if !self.logistics() {
for s in &mut self.sams {
s.empty = false;
}
return;
}
let now = self.tick; let now = self.tick;
// Systems by a depot reload from it. // Systems by a depot reload from it.
for i in 0..self.sams.len() { for i in 0..self.sams.len() {
@@ -127,20 +111,19 @@ impl Sim {
// untouched and only real RM48U demand pulls the truck away from its watch. // untouched and only real RM48U demand pulls the truck away from its watch.
let return_cargo = truck.return_cargo && truck.ground_stock > 0; let return_cargo = truck.return_cargo && truck.ground_stock > 0;
let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD; let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD;
let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return)); let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return));
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect(); let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let target = if return_cargo { let target = if return_cargo {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else if can_pick { } else if can_pick {
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else { } else {
None None
}.map(|s| (s.id, s.pos)); }.map(|s| (s.id, s.pos));
if let Some((id, to)) = target { if let Some((id, to)) = target {
self.sams[t].job = Some(id); self.sams[t].job = Some(id);
if at.distance(to) > HANDOVER { if at.distance(to) > HANDOVER {
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); self.order_move_near(t, to, HANDOVER - 0.75);
self.order_move_near(t, to + side, 3.5);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) { } else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo { if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1; self.sams[j].ground_stock += 1;
@@ -165,7 +148,7 @@ impl Sim {
// The impossible return still outranks a mere stock run: without RM48U demand // The impossible return still outranks a mere stock run: without RM48U demand
// the truck holds its watch (and drops a stale job) exactly as before. // the truck holds its watch (and drops a stale job) exactly as before.
let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request)) let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request))
|| (self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) || (self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request)
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0)); && self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
if !supply_demand { if !supply_demand {
self.sams[t].job = None; self.sams[t].job = None;
@@ -175,11 +158,11 @@ impl Sim {
// Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed // Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed
// after loading a save; the request and physical cargo survive independently. // after loading a save; the request and physical cargo survive independently.
let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 || let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 ||
(self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) (self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request)
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0)); && self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
if typed_work { if typed_work {
if let Some(id) = self.sams[t].job { if let Some(id) = self.sams[t].job {
let valid = self.sams.iter().find(|s| s.id == id).is_some_and(|s| s.alive() && !self.routes.out_of_reach(truck_id, s.id, now) && (s.kind == SamKind::Depot || (self.sams[t].ground_stock > 0 && s.kind == SamKind::S400 && s.ground_request))); let valid = self.sams.iter().find(|s| s.id == id).is_some_and(|s| s.alive() && !self.routes.out_of_reach(truck_id, s.id, now) && (s.kind == SamKind::Depot || (self.sams[t].ground_stock > 0 && s.kind.supports_rm48u() && s.ground_request)));
if !valid { self.sams[t].job = None; } if !valid { self.sams[t].job = None; }
} }
if let Some(id) = self.sams[t].job { if let Some(id) = self.sams[t].job {
@@ -197,11 +180,11 @@ impl Sim {
// The last reserved round left the truck: nothing marks as return cargo any more. // The last reserved round left the truck: nothing marks as return cargo any more.
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; } if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
} }
if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) { if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request) {
self.sams[j].ground_stock -= 1; self.sams[j].ground_stock -= 1;
self.sams[t].ground_stock += 1; self.sams[t].ground_stock += 1;
} }
} else if self.sams[j].kind == SamKind::S400 && self.sams[j].ground_request && !self.sams[j].moving() && self.sams[j].preparing.is_none() && self.sams[j].reloading == 0 && self.sams[j].part(Part::Launcher) > 0.0 && self.sams[j].ground_rounds < self.sams[j].cells() && self.sams[t].ground_stock > 0 { } else if self.sams[j].kind.supports_rm48u() && self.sams[j].ground_request && !self.sams[j].moving() && self.sams[j].preparing.is_none() && self.sams[j].reloading == 0 && self.sams[j].part(Part::Launcher) > 0.0 && self.sams[j].ground_rounds < self.sams[j].cells() && self.sams[t].ground_stock > 0 {
let displaced = u32::from(self.sams[j].missiles + self.sams[j].ground_rounds >= self.sams[j].cells()); let displaced = u32::from(self.sams[j].missiles + self.sams[j].ground_rounds >= self.sams[j].cells());
self.sams[j].missiles -= displaced; self.sams[j].missiles -= displaced;
self.sams[j].ground_rounds += 1; self.sams[j].ground_rounds += 1;
@@ -217,29 +200,29 @@ impl Sim {
self.sams[t].job = None; self.sams[t].job = None;
} else { } else {
let to = self.sams[j].pos; let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); self.order_move_near(t, to, HANDOVER - 0.75);
self.order_move_near(t, to + side, 3.5);
continue; continue;
} }
} else { self.sams[t].job = None; } } else { self.sams[t].job = None; }
} }
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect(); let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let next = if self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request) { let next = if self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request) {
self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds < s.cells() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds < s.cells() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else { } else {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && (self.sams[t].air_48n6_stock > 0 || (self.sams[t].ground_stock > 0 && s.ground_stock < STOCK_LIMIT) || (self.sams[t].ground_stock == 0 && s.ground_stock > 0)) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && (self.sams[t].air_48n6_stock > 0 || (self.sams[t].ground_stock > 0 && s.ground_stock < STOCK_LIMIT) || (self.sams[t].ground_stock == 0 && s.ground_stock > 0)) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
}.map(|s| (s.id, s.pos)); }.map(|s| (s.id, s.pos));
if let Some((id, to)) = next { if let Some((id, to)) = next {
self.sams[t].job = Some(id); self.sams[t].job = Some(id);
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); if to.distance(at) > HANDOVER { self.order_move_near(t, to, HANDOVER - 0.75); }
if to.distance(at) > HANDOVER { self.order_move_near(t, to + side, 3.5); }
} }
continue; continue;
} }
// Where it was going: hand over, or load up. // Where it was going: hand over, or load up.
if let Some(job) = truck.job if let Some(job) = truck.job {
&& let Some(j) = self.sams.iter().position(|s| s.id == job) let Some(j) = self.sams.iter().position(|s| s.id == job && s.alive()) else {
{ self.sams[t].job = None;
continue;
};
if self.sams[j].pos.distance(at) <= HANDOVER { if self.sams[j].pos.distance(at) <= HANDOVER {
if self.sams[j].kind == SamKind::Depot { if self.sams[j].kind == SamKind::Depot {
let take = TRUCK_LOAD.saturating_sub(self.sams[t].cargo).min(self.sams[j].cargo); let take = TRUCK_LOAD.saturating_sub(self.sams[t].cargo).min(self.sams[j].cargo);
@@ -251,11 +234,10 @@ impl Sim {
self.reload_now(j, out); self.reload_now(j, out);
} }
self.sams[t].job = None; self.sams[t].job = None;
} else if self.sams[j].alive() && (self.sams[j].empty || self.sams[j].kind == SamKind::Depot) { } else if self.sams[j].empty || self.sams[j].kind == SamKind::Depot {
// Stopped short of it (it drove off meanwhile): on to where it stands now. // Stopped short of it (it drove off meanwhile): on to where it stands now.
let to = self.sams[j].pos; let to = self.sams[j].pos;
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6); self.order_move_near(t, to, HANDOVER - 0.75);
self.order_move_near(t, to + side, 3.5);
continue; continue;
} else { } else {
self.sams[t].job = None; self.sams[t].job = None;
@@ -286,9 +268,8 @@ impl Sim {
if let Some((id, to)) = next { if let Some((id, to)) = next {
self.sams[t].job = Some(id); self.sams[t].job = Some(id);
// Stop beside it, not on it. // Stop beside it, not on it.
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
if to.distance(at) > HANDOVER { if to.distance(at) > HANDOVER {
self.order_move_near(t, to + side, 3.5); self.order_move_near(t, to, HANDOVER - 0.75);
} }
} }
} }
+181
View File
@@ -0,0 +1,181 @@
//! Where the mod's memory goes: an estimate of what each consumer holds, for the budget
//! tests and the diagnostics. The whole mod lives in one 64 MiB WASM linear memory
//! (`horizon-mods` runtime `MEMORY`): the simulation, the ground and block caches, the
//! recordings and the enemy's memory all share it, and a hashbrown rehash briefly holds
//! the old and the new table at once. The estimates count allocated capacity, not len,
//! and the tables' control bytes; they are a lower bound on the allocator's footprint
//! (fragmentation and the transient query/answer vectors come on top).
use super::*;
/// A hashbrown table's allocation for `len` entries of `entry` bytes (key + value):
/// the capacity grows 3, 7, 14, 28, … at a 7/8 load, and the allocation is
/// `(capacity + group) * (entry + 1)` (one control byte per slot).
pub(super) fn map_bytes(len: usize, entry: usize) -> usize {
if len == 0 {
return 0;
}
let mut cap = 3usize;
while cap * 7 / 8 < len {
cap = if cap == 3 { 7 } else { cap * 2 };
}
(cap + 16) * (entry + 1)
}
/// A `BTreeMap`'s nodes, about: the entry plus the node's share of pointers and slack.
pub(super) fn btree_bytes(len: usize, entry: usize) -> usize {
len * (entry + 32)
}
pub(super) fn vec_bytes<T>(v: &Vec<T>) -> usize {
v.capacity() * std::mem::size_of::<T>()
}
pub(super) fn vecdeque_bytes<T>(v: &std::collections::VecDeque<T>) -> usize {
v.capacity() * std::mem::size_of::<T>()
}
/// What each consumer holds, in bytes (estimated allocated capacity).
#[derive(Clone, Copy, Default, Debug)]
pub struct MemoryReport {
/// `Ground::known`: the answered land heights by column.
pub ground_known: usize,
/// The ground's other bookkeeping: loading, questions waiting, chunks wanted.
pub ground_other: usize,
/// `WorldCache::secs`: the block sections, table and the mixed ones' bits.
pub world_sections: usize,
/// The block cache's other bookkeeping: exact rays, queues, questions, blasts expected.
pub world_other: usize,
/// The simulation's vectors: drones (and their routes), missiles, systems, objects,
/// effects, blasts, the launch queue and the rest of the live state.
pub units: usize,
/// The radars' tracks and horizons.
pub tracks: usize,
/// The recording in progress.
pub recording: usize,
/// The replays kept.
pub replays: usize,
/// The enemy's memory of the layout (contacts and outcomes).
pub intel: usize,
/// The recon memory (sorties, marks, checked zones).
pub recon: usize,
/// The vehicles' ground routes and their searches.
pub routes: usize,
/// The raid's launch sites.
pub sites: usize,
/// The counter-strikes on the sites.
pub strikes: usize,
/// The raid being planned (its grid, prices, routes, knowledge) and the retarget jobs.
pub plan: usize,
/// The rest: fires, flares, roles, tallies, the smart refresh.
pub other: usize,
}
impl MemoryReport {
pub fn total(&self) -> usize {
self.ground_known
+ self.ground_other
+ self.world_sections
+ self.world_other
+ self.units
+ self.tracks
+ self.recording
+ self.replays
+ self.intel
+ self.recon
+ self.routes
+ self.sites
+ self.strikes
+ self.plan
+ self.other
}
/// The largest table a rehash could double while the old one is still held: the
/// transient peak is the total plus twice this (old + new − steady).
pub fn rehash_headroom(&self) -> usize {
2 * self.ground_known.max(self.world_sections)
}
/// One line per consumer, biggest first: the budget report's shape.
pub fn text(&self) -> String {
let mut rows = [
("ground.known", self.ground_known),
("ground.other", self.ground_other),
("world.secs", self.world_sections),
("world.other", self.world_other),
("sim.units", self.units),
("sim.tracks", self.tracks),
("recording", self.recording),
("replays", self.replays),
("intel", self.intel),
("recon", self.recon),
("routes", self.routes),
("sites", self.sites),
("strikes", self.strikes),
("plan", self.plan),
("other", self.other),
];
rows.sort_by(|a, b| b.1.cmp(&a.1));
let mut out = format!("total {:.2} MiB (+{:.2} MiB rehash transient)", self.total() as f64 / (1024.0 * 1024.0), self.rehash_headroom() as f64 / (1024.0 * 1024.0));
for (name, bytes) in rows {
if bytes > 0 {
out.push_str(&format!("\n {name}: {:.2} MiB", bytes as f64 / (1024.0 * 1024.0)));
}
}
out
}
}
impl Sim {
/// What the simulation and the ground cache hold, about: the budget tests measure it
/// under load, and the diagnostics can show where the memory went.
pub fn memory(&self, ground: &Ground) -> MemoryReport {
let mut r = MemoryReport::default();
r.ground_known = map_bytes(ground.known.len(), std::mem::size_of::<(i32, i32)>() + std::mem::size_of::<(i32, u64)>());
r.ground_other = map_bytes(ground.loading.len(), std::mem::size_of::<(i32, i32)>() + std::mem::size_of::<u64>())
+ vec_bytes(&ground.wanted)
+ map_bytes(ground.asked.len(), std::mem::size_of::<(i32, i32)>())
+ vec_bytes(&ground.chunks);
let (sections, other) = ground.world.memory();
r.world_sections = sections;
r.world_other = other;
r.units = vec_bytes(&self.drones)
+ self.drones.iter().map(|d| vec_bytes(&d.route)).sum::<usize>()
+ vec_bytes(&self.missiles)
+ vec_bytes(&self.sams)
+ vec_bytes(&self.targets)
+ vec_bytes(&self.target_health)
+ vec_bytes(&self.fx)
+ vec_bytes(&self.blasts)
+ vec_bytes(&self.queue)
+ vec_bytes(&self.settling)
+ vec_bytes(&self.later)
+ vec_bytes(&self.flares)
+ vec_bytes(&self.lit);
r.tracks = self.sams.iter().map(|s| {
vec_bytes(&s.tracks) + map_bytes(s.class_plots.capacity(), std::mem::size_of::<(u32, sight::ClassPlot)>())
}).sum::<usize>()
+ map_bytes(self.horizons.len(), std::mem::size_of::<u32>() + std::mem::size_of::<sight::Horizon>())
+ self.horizons.values().map(|h| vec_bytes(&h.rays) + h.rays.iter().map(|ray| vec_bytes(ray)).sum::<usize>()).sum::<usize>();
r.recording = self.rec.as_ref().map_or(0, |rec| rec.bytes());
r.replays = self.replays.iter().map(|rec| rec.bytes()).sum();
r.intel = self.intel.bytes();
r.recon = vec_bytes(&self.recon.sorties)
+ btree_bytes(self.recon.marks.len(), std::mem::size_of::<u32>() + std::mem::size_of::<recon::Mark>())
+ btree_bytes(self.recon.truth.len(), 2 * std::mem::size_of::<u32>())
+ btree_bytes(self.recon.checked.len(), std::mem::size_of::<(i64, i64)>() + std::mem::size_of::<u64>());
r.routes = self.routes.bytes();
r.sites = self.sites.bytes();
r.strikes = self.strikes.bytes();
r.plan = self.plan.as_ref().map_or(0, |p| p.bytes())
+ vecdeque_bytes(&self.retargets)
+ self.retargets.iter().map(|j| j.known.bytes() + j.relief.as_ref().map_or(0, |k| k.bytes())).sum::<usize>()
+ self.known_relief.as_ref().map_or(0, |k| k.bytes());
r.other = map_bytes(self.roles.len(), std::mem::size_of::<SamKind>() + std::mem::size_of::<u8>())
+ self.fires.bytes()
+ self.breakthroughs.bytes()
+ std::mem::size_of::<record::Tally>()
+ std::mem::size_of::<Self>();
r
}
}
+230 -110
View File
@@ -25,10 +25,12 @@ pub mod record;
mod sight; mod sight;
mod terrain; mod terrain;
mod ew; mod ew;
mod observe;
mod optical; mod optical;
mod recon; mod recon;
mod durable; mod durable;
pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport, ReconReport, ReconSortieReport}; pub use ew::{AimReport, BearingReason, BearingReport, Confidence, ContactReport, EnemyPictureReport, Intent, ObservationReport, PendingReport, ReconReport, ReconSortieReport};
pub use observe::Observation;
pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts}; pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts};
pub mod lights; pub mod lights;
mod logistics; mod logistics;
@@ -38,13 +40,20 @@ mod voices;
pub mod outcome; pub mod outcome;
mod units; mod units;
pub mod why; pub mod why;
mod breakthrough;
pub mod decision;
pub mod world; pub mod world;
pub mod memory;
pub use memory::MemoryReport;
pub mod profile;
#[cfg(test)] #[cfg(test)]
mod balance; mod balance;
#[cfg(test)] #[cfg(test)]
mod regress; mod regress;
#[cfg(test)] #[cfg(test)]
mod sensor_tests; mod sensor_tests;
#[cfg(test)]
mod smart_tests;
pub use ew::EW_RADIUS; pub use ew::EW_RADIUS;
pub use damage::{Comps, Part, PartState}; pub use damage::{Comps, Part, PartState};
pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS}; pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS};
@@ -72,6 +81,13 @@ pub struct Model {
pub glow: bool, pub glow: bool,
} }
impl Model {
/// Multipart models use the IDs immediately after their owning object.
pub fn object_id(&self) -> u32 {
self.id - self.id % PARTS
}
}
pub struct Particle { pub struct Particle {
pub kind: &'static str, pub kind: &'static str,
pub at: DVec3, pub at: DVec3,
@@ -281,8 +297,6 @@ pub struct Ground {
chunks: Vec<(i32, i32)>, chunks: Vec<(i32, i32)>,
/// The game has answered "loading" at least once: it loads chunks on request (a server doesn't). /// The game has answered "loading" at least once: it loads chunks on request (a server doesn't).
pub loads: bool, pub loads: bool,
/// The tick of the last full clean-up (a big cache would otherwise be scanned on every answer).
swept: u64,
/// The tick of the last answer round: what the heights' ages are measured against. /// The tick of the last answer round: what the heights' ages are measured against.
now: u64, now: u64,
/// The world's epoch when the last questions went out: an answer to them is of that world or dimension, or of none. /// The world's epoch when the last questions went out: an answer to them is of that world or dimension, or of none.
@@ -313,8 +327,15 @@ const HEIGHT_TTL: u64 = 1200;
/// Ticks a flight waits for an unanswered section, and for a chunk the game doesn't have while low over the land (#61). /// Ticks a flight waits for an unanswered section, and for a chunk the game doesn't have while low over the land (#61).
pub const HOLD_PENDING: u16 = 45; pub const HOLD_PENDING: u16 = 45;
pub const HOLD_NO_CHUNK: u16 = 240; pub const HOLD_NO_CHUNK: u16 = 240;
/// Ticks between full clean-ups of a big ground cache. /// Columns whose heights are kept: the ground cache's share of the 64 MiB WASM linear memory
const SWEEP_EVERY: u64 = 200; /// the whole mod lives in (shared with the block cache, the recordings and the simulation).
/// An entry is 24 bytes plus a control byte at a 7/8 load (~29 B): 100_000 columns are ~2.7 MiB
/// steady, and a hashbrown rehash holds the old and the new table at once (~8.2 MiB transient).
/// Beyond the cap the oldest answers go first — the cache is reconstructible: an evicted column
/// is asked again when it is next needed, exactly as one never seen.
const KNOWN_MAX: usize = 100_000;
/// Heights older than this go in a sweep: past `HEIGHT_TTL`, due to be asked again anyway.
const SWEEP_AGE: u64 = 2000;
impl Ground { impl Ground {
/// One above the highest solid block, if known; the column is asked for /// One above the highest solid block, if known; the column is asked for
@@ -369,11 +390,22 @@ impl Ground {
self.world.note_settled(how); self.world.note_settled(how);
self.forget(at, 8); self.forget(at, 8);
} }
if self.known.len() > 300_000 && now.saturating_sub(self.swept) >= SWEEP_EVERY { if self.known.len() > KNOWN_MAX {
self.swept = now; self.sweep_known(now);
self.known.retain(|_, (_, when)| now.saturating_sub(*when) < 2000);
} }
} }
/// The cache over its budget: the oldest answers go, down to three quarters of the cap so
/// a sweep is not every tick (at most a few hundred answers arrive in one). Heights past
/// `SWEEP_AGE` go with them. A height reported changed (`STALE`) is still in use and stays:
/// it sorts as the newest and is asked again within the refresh budget. Equally old answers
/// are ordered by column, so the same cache always sweeps to the same state.
fn sweep_known(&mut self, now: u64) {
let keep = KNOWN_MAX * 3 / 4;
let mut ages: Vec<(u64, (i32, i32))> = self.known.iter().map(|(&k, (_, when))| (*when, k)).collect();
ages.sort_unstable();
let cut = ages[ages.len() - keep];
self.known.retain(|&k, (_, when)| (*when, k) >= cut && now.saturating_sub(*when) < SWEEP_AGE);
}
/// Heights over blocks that changed (the block cache's notes of changes, chunk replacements and a new world) /// Heights over blocks that changed (the block cache's notes of changes, chunk replacements and a new world)
/// are marked old (`when` = STALE): still used, asked again within the budget. #64. /// are marked old (`when` = STALE): still used, asked again within the budget. #64.
fn age_heights(&mut self) { fn age_heights(&mut self) {
@@ -449,6 +481,10 @@ impl Ground {
pub fn chunks_wanted(&self) -> usize { pub fn chunks_wanted(&self) -> usize {
self.chunks.len() self.chunks.len()
} }
/// How many columns' heights are cached (the budget tests and the diagnostics read it).
pub fn known_len(&self) -> usize {
self.known.len()
}
/// The chunks to ask the game to load this tick. /// The chunks to ask the game to load this tick.
pub fn take_chunks(&mut self) -> Vec<(i32, i32)> { pub fn take_chunks(&mut self) -> Vec<(i32, i32)> {
std::mem::take(&mut self.chunks) std::mem::take(&mut self.chunks)
@@ -730,25 +766,6 @@ pub fn roles_text(mask: u8) -> String {
Class::ALL.iter().filter(|c| mask & c.bit() != 0).map(|c| c.letter()).collect::<Vec<_>>().join("") Class::ALL.iter().filter(|c| mask & c.bit() != 0).map(|c| c.letter()).collect::<Vec<_>>().join("")
} }
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum DroneKind {
Shahed,
Geran3,
Lancet,
Gerbera,
Kh101,
Kalibr,
Kh22,
Zircon,
Iskander,
Kinzhal,
/// An IRBM: its bus releases six blocks high over the target.
Oreshnik,
/// One of the Oreshnik's blocks: it splits into six glowing submunitions.
OreshnikBlock,
OreshnikSub,
}
/// What a drone carries on its tail. /// What a drone carries on its tail.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
enum Engine { enum Engine {
@@ -774,6 +791,8 @@ pub struct DroneSpec {
dive: f64, dive: f64,
/// Primed TNT on impact. /// Primed TNT on impact.
warhead: u32, warhead: u32,
/// Impact scatter in blocks and the probability of a large miss in the game.
accuracy: (f64, f64),
scale: f64, scale: f64,
engine: Engine, engine: Engine,
/// No warhead: it only draws fire. /// No warhead: it only draws fire.
@@ -802,21 +821,6 @@ impl DroneSpec {
} }
impl DroneKind { impl DroneKind {
pub const ALL: [DroneKind; 13] = [
DroneKind::Shahed,
DroneKind::Geran3,
DroneKind::Lancet,
DroneKind::Gerbera,
DroneKind::Kh101,
DroneKind::Kalibr,
DroneKind::Kh22,
DroneKind::Zircon,
DroneKind::Iskander,
DroneKind::Kinzhal,
DroneKind::Oreshnik,
DroneKind::OreshnikBlock,
DroneKind::OreshnikSub,
];
/// The sound of a launch from the ground: a light catapult shot, a rocket booster, a heavy ballistic launch. /// The sound of a launch from the ground: a light catapult shot, a rocket booster, a heavy ballistic launch.
pub fn launch_sound(self) -> &'static str { pub fn launch_sound(self) -> &'static str {
self.spec().launch_sound self.spec().launch_sound
@@ -972,22 +976,10 @@ impl Drone {
// ---------------------------------------------------------------- interceptors // ---------------------------------------------------------------- interceptors
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum MissileKind {
Pac3,
M57e6,
M48n6,
M77n6,
IrisT,
Amraam,
M9m317,
M9m338,
/// Not a missile: an interceptor drone, slow and cheap, that rams Shaheds.
P1sun,
}
struct MissileSpec { struct MissileSpec {
model: &'static str, model: &'static str,
/// Extra game blast damage when a loaded round burns in its launcher.
launcher_blast: f64,
speed: f64, speed: f64,
accel: f64, accel: f64,
turn: f64, turn: f64,
@@ -1147,7 +1139,7 @@ pub enum SamState {
Packing, Packing,
Moving, Moving,
Deploying, Deploying,
/// Out of missiles, waiting for a reload truck (logistics on: a depot stands). /// Out of missiles, waiting for a resupply.
Waiting, Waiting,
} }
@@ -1250,6 +1242,7 @@ pub struct Sam {
/// Where its radar beam points (radians), and the tracks it holds: its own radar's and the network's. /// Where its radar beam points (radians), and the tracks it holds: its own radar's and the network's.
pub(super) beam: f64, pub(super) beam: f64,
pub tracks: Vec<Track>, pub tracks: Vec<Track>,
class_plots: HashMap<u32, sight::ClassPlot>,
/// The ids of the tracks it holds this tick: its own radar's and the network's. /// The ids of the tracks it holds this tick: its own radar's and the network's.
pub seen: Vec<u32>, pub seen: Vec<u32>,
/// The drones its own radar (or optics) holds: guns need these. /// The drones its own radar (or optics) holds: guns need these.
@@ -1263,7 +1256,7 @@ pub struct Sam {
pub cargo: u32, pub cargo: u32,
/// A reload truck's job: the system it is driving to, or a depot. /// A reload truck's job: the system it is driving to, or a depot.
job: Option<u32>, job: Option<u32>,
/// Out of ammunition, waiting for a reload (logistics on). /// Out of ammunition, waiting for a resupply.
pub empty: bool, pub empty: bool,
/// An EW station: jamming, and its transmitter's heat (0 cold, 1 forced off). /// An EW station: jamming, and its transmitter's heat (0 cold, 1 forced off).
pub ew_on: bool, pub ew_on: bool,
@@ -1335,6 +1328,7 @@ impl Sam {
jam: 0, jam: 0,
beam: id as f64 * 2.4, beam: id as f64 * 2.4,
tracks: Vec::new(), tracks: Vec::new(),
class_plots: HashMap::new(),
seen: Vec::new(), seen: Vec::new(),
own: Vec::new(), own: Vec::new(),
kill_view: None, kill_view: None,
@@ -1404,6 +1398,7 @@ enum Fx {
// ---------------------------------------------------------------- the simulation // ---------------------------------------------------------------- the simulation
pub struct Sim { pub struct Sim {
breakthroughs: breakthrough::Breakthroughs,
/// Roles set for a kind of system (`/airdef roles`), new ones included. /// Roles set for a kind of system (`/airdef roles`), new ones included.
pub roles: HashMap<SamKind, u8>, pub roles: HashMap<SamKind, u8>,
pub drones: Vec<Drone>, pub drones: Vec<Drone>,
@@ -1416,6 +1411,8 @@ pub struct Sim {
/// The next blast's id (separate from `next`, so the other units' ids stay as they were). /// The next blast's id (separate from `next`, so the other units' ids stay as they were).
blast_seq: u32, blast_seq: u32,
next: u32, next: u32,
/// The optical probe sequence: a ready post is served oldest-probe first (fair queue, #138).
optical_seq: u64,
/// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never /// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never
/// spend it (#85). /// spend it (#85).
pub rng: Rng, pub rng: Rng,
@@ -1459,6 +1456,8 @@ pub struct Sim {
horizons: HashMap<u32, sight::Horizon>, horizons: HashMap<u32, sight::Horizon>,
/// Blasts to come: (tick, where, TNT, small) — a magazine cooking off. /// Blasts to come: (tick, where, TNT, small) — a magazine cooking off.
later: Vec<(u64, DVec3, u32, bool)>, later: Vec<(u64, DVec3, u32, bool)>,
/// New unit targets the current raid may adopt after planning.
diversions_left: u32,
/// A planned raid's drones waiting for their launch tick. /// A planned raid's drones waiting for their launch tick.
pub queue: Vec<(u64, Drone)>, pub queue: Vec<(u64, Drone)>,
/// The raid's launch sites and their jobs (#100). /// The raid's launch sites and their jobs (#100).
@@ -1492,6 +1491,16 @@ pub struct Sim {
intel: ew::Intel, intel: ew::Intel,
/// Reconnaissance flights and the partial picture they radioed home (#135). /// Reconnaissance flights and the partial picture they radioed home (#135).
recon: recon::Recon, recon: recon::Recon,
/// The smart enemy runs the legacy picks (#149's comparison runner): the two separate hint
/// lists and their old scales, the lifetime bearing tally with its fixed share, no mark
/// pricing and no refresh of the unreleased portion. The light modes never read it.
pub smart_legacy: bool,
/// The bounded refresh of the last smart raid's unreleased portion (#149), while it waits.
refresh: Option<ew::Refresh>,
/// Aims the refresh has re-chosen (#149; diagnostics).
refresh_applied: u32,
/// The bearing picker's last decision and its typed reason (#149).
bearing: ew::BearingReport,
/// Night: guns need light (the mod sets it from the game's clock). /// Night: guns need light (the mod sets it from the game's clock).
pub night: bool, pub night: bool,
/// The long fires at crash and impact points (#52). /// The long fires at crash and impact points (#52).
@@ -1520,6 +1529,7 @@ fn fx_ident(counter: &mut u32) -> u32 {
impl Sim { impl Sim {
pub fn new(seed: u64) -> Self { pub fn new(seed: u64) -> Self {
Self { Self {
breakthroughs: Default::default(),
roles: HashMap::new(), roles: HashMap::new(),
drones: Vec::new(), drones: Vec::new(),
missiles: Vec::new(), missiles: Vec::new(),
@@ -1529,6 +1539,7 @@ impl Sim {
blasts: Vec::new(), blasts: Vec::new(),
blast_seq: 0, blast_seq: 0,
next: 1, next: 1,
optical_seq: 0,
rng: Rng::new(seed), rng: Rng::new(seed),
vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B), vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B),
fx_next: 0, fx_next: 0,
@@ -1553,6 +1564,7 @@ impl Sim {
far_shots: true, far_shots: true,
horizons: HashMap::new(), horizons: HashMap::new(),
later: Vec::new(), later: Vec::new(),
diversions_left: u32::MAX,
queue: Vec::new(), queue: Vec::new(),
sites: sites::Sites::default(), sites: sites::Sites::default(),
strikes: strike::Strikes::new(), strikes: strike::Strikes::new(),
@@ -1569,6 +1581,10 @@ impl Sim {
tally: record::Tally::default(), tally: record::Tally::default(),
intel: ew::Intel::default(), intel: ew::Intel::default(),
recon: recon::Recon::default(), recon: recon::Recon::default(),
smart_legacy: false,
refresh: None,
refresh_applied: 0,
bearing: ew::BearingReport::default(),
night: false, night: false,
fires: fires::Fires::default(), fires: fires::Fires::default(),
day_time: None, day_time: None,
@@ -1590,6 +1606,16 @@ impl Sim {
self.next * PARTS self.next * PARTS
} }
/// The bearing picker's last decision and its typed reason (#149; diagnostics).
pub fn bearing_report(&self) -> ew::BearingReport {
self.bearing
}
/// Aims the bounded refresh of the unreleased portion has re-chosen (#149; diagnostics).
pub fn refresh_applied(&self) -> u32 {
self.refresh_applied
}
/// What a system's camera follows: its guns' or missiles' target, else what its missiles in /// What a system's camera follows: its guns' or missiles' target, else what its missiles in
/// flight are after. /// flight are after.
pub fn watched(&self, sam: &Sam) -> Option<&Drone> { pub fn watched(&self, sam: &Sam) -> Option<&Drone> {
@@ -1638,6 +1664,7 @@ impl Sim {
fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) { fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) {
// Its navigation error is drawn in `make_drone`, the one path of manual and raid launches (#65). // Its navigation error is drawn in `make_drone`, the one path of manual and raid launches (#65).
let d = self.make_drone(kind, from, dir, target); let d = self.make_drone(kind, from, dir, target);
self.breakthroughs.begin(d.id, true);
self.drones.push(d); self.drones.push(d);
self.launched += 1; self.launched += 1;
} }
@@ -1673,6 +1700,7 @@ impl Sim {
self.strikes.pending.clear(); self.strikes.pending.clear();
for sam in &mut self.sams { sam.cancel_prepare(); } for sam in &mut self.sams { sam.cancel_prepare(); }
self.drones.clear(); self.drones.clear();
self.breakthroughs.active.clear();
self.missiles.clear(); self.missiles.clear();
self.fx.clear(); self.fx.clear();
self.blasts.clear(); self.blasts.clear();
@@ -1682,6 +1710,7 @@ impl Sim {
self.retargets.clear(); self.retargets.clear();
self.known_relief = None; self.known_relief = None;
self.recon.clear_sorties(); self.recon.clear_sorties();
self.refresh = None;
self.wave = None; self.wave = None;
// Ammunition still to cook off, flares in the sky. // Ammunition still to cook off, flares in the sky.
self.later.clear(); self.later.clear();
@@ -1720,24 +1749,27 @@ impl Sim {
}); });
} }
/// One game tick. /// One game tick. The named phases are timed for the CPU profile (#147 step
/// 3.1); the timing reads no randomness and changes no decision.
pub fn step(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) { pub fn step(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
profile::begin_step();
self.tick += 1; self.tick += 1;
self.plan_step(Some(&mut *ground), out); profile::time(profile::PLAN, || self.plan_step(Some(&mut *ground), out));
self.adapt(); profile::time(profile::ADAPT, || self.adapt());
self.step_refresh(out);
self.step_settling(ground); self.step_settling(ground);
self.release_queue(ground, out); self.release_queue(ground, out);
self.begin_recording_if_active(); self.begin_recording_if_active();
self.step_drones(ground, player, out); profile::time(profile::DRONES, || self.step_drones(ground, player, out));
self.step_recon(out); self.step_recon(out);
self.step_later(ground, player, out); self.step_later(ground, player, out);
self.step_moves(ground, out); profile::time(profile::MOVES, || self.step_moves(ground, out));
self.step_supply(out); self.step_supply(out);
self.step_ew(out); self.step_ew(out);
self.update_sight(ground); profile::time(profile::SIGHT, || self.update_sight(ground));
self.step_lights(ground, out); self.step_lights(ground, out);
self.prepare_ground_strikes(out); self.prepare_ground_strikes(out);
self.step_sams(ground, out); profile::time(profile::SAMS, || self.step_sams(ground, out));
self.step_missiles(ground, out); self.step_missiles(ground, out);
self.step_strikes(ground, player, out); self.step_strikes(ground, player, out);
self.step_fx(ground, out); self.step_fx(ground, out);
@@ -1746,9 +1778,10 @@ impl Sim {
self.step_wrecks(out); self.step_wrecks(out);
self.step_fires(ground, out); self.step_fires(ground, out);
self.report_wave(out); self.report_wave(out);
self.record(); profile::time(profile::RECORD, || self.record());
let now = self.tick; let now = self.tick;
self.blasts.retain(|b| now - b.start < b.life as u64); self.blasts.retain(|b| now - b.start < b.life as u64);
profile::end_step();
} }
// ------------------------------------------------ drones // ------------------------------------------------ drones
@@ -1993,7 +2026,7 @@ impl Sim {
let safe = if need.is_finite() { need + 2.0 } else { d.target.y + spec.clearance }; let safe = if need.is_finite() { need + 2.0 } else { d.target.y + spec.clearance };
let mut height = base.max(safe).max(d.nav.dive + 1.0); let mut height = base.max(safe).max(d.nav.dive + 1.0);
// Blind: it does not come down over land nobody has told of; it holds the height it has. // Blind: it does not come down over land nobody has told of; it holds the height it has.
if d.nav.blind && d.low && to_target > 300.0 { if d.nav.blind && (d.low || d.pos.y >= raid::VANILLA_BUILD_CEILING) && to_target > 300.0 {
height = height.max(d.pos.y); height = height.max(d.pos.y);
} }
let full = climb.pitch.tan(); let full = climb.pitch.tan();
@@ -2097,6 +2130,7 @@ impl Sim {
}; };
let object = self.targets.iter().position(|t| t.distance(pos) < 16.0); let object = self.targets.iter().position(|t| t.distance(pos) < 16.0);
let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i)); let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i));
self.breakthrough_hit(drone, kind, pos, object);
self.emit_combat_event(pos, record::EventKind::Hit { drone, kind, power, object, sam }); self.emit_combat_event(pos, record::EventKind::Hit { drone, kind, power, object, sam });
let vel = self.drones.iter().find(|x| x.id == drone).map_or(DVec3::ZERO, |x| x.vel); let vel = self.drones.iter().find(|x| x.id == drone).map_or(DVec3::ZERO, |x| x.vel);
self.direct_hit(pos, vel, tnt, out); self.direct_hit(pos, vel, tnt, out);
@@ -2108,9 +2142,11 @@ impl Sim {
for (pos, warhead, small) in boom { for (pos, warhead, small) in boom {
self.explode(pos, warhead, small, ground, player, out); self.explode(pos, warhead, small, ground, player, out);
} }
for id in &removed { self.breakthroughs.active.remove(id); }
self.drones.retain(|d| !removed.contains(&d.id)); self.drones.retain(|d| !removed.contains(&d.id));
for (kind, pos, vel, target, sector) in released { for (kind, pos, vel, target, sector) in released {
let id = self.id(); let id = self.id();
self.breakthroughs.begin(id, true);
self.drones.push(Drone { self.drones.push(Drone {
id, id,
kind, kind,
@@ -2178,14 +2214,16 @@ impl Sim {
} }
} }
/// What the enemy's munitions just watched (#127): for every impact, the fate of each known /// What the enemy's munitions just watched (#127): a destroyed known unit near an impact is
/// unit near it — dead or alive as the explosion showed, at the place it showed. Units the /// removed from the planner's leads. Surviving contacts keep their last observed areas.
/// blasts missed keep their contacts exactly as they were: unobserved is unobserved.
fn observe_outcomes(&mut self, impacts: &[(u32, DroneKind, DVec3, u32)]) { fn observe_outcomes(&mut self, impacts: &[(u32, DroneKind, DVec3, u32)]) {
let now = self.tick; let now = self.tick;
for &(_, _, pos, _) in impacts { for &(_, _, pos, _) in impacts {
for s in self.sams.iter().filter(|s| s.pos.distance(pos) < 16.0) { for s in self.sams.iter().filter(|s| s.pos.distance(pos) < 16.0) {
self.intel.outcome(s.id, s.alive(), s.pos, now); if !s.alive() {
self.intel.outcome(s.id, false, s.pos, now);
self.recon.forget_wreck(s.id);
}
} }
} }
} }
@@ -2355,6 +2393,7 @@ impl Sim {
// ------------------------------------------------ air defence // ------------------------------------------------ air defence
fn step_sams(&mut self, ground: &mut Ground, out: &mut Out) { fn step_sams(&mut self, ground: &mut Ground, out: &mut Out) {
use decision::{Block, Channel, Outcome as Decision};
for sam in &mut self.sams { for sam in &mut self.sams {
sam.sync_tube_cells(); sam.sync_tube_cells();
if (self.hold && !sam.preparing.is_some_and(|p| p.ground)) || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.part(Part::Launcher) <= 0.0 { if (self.hold && !sam.preparing.is_some_and(|p| p.ground)) || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.part(Part::Launcher) <= 0.0 {
@@ -2366,12 +2405,17 @@ impl Sim {
for i in 0..self.sams.len() { for i in 0..self.sams.len() {
if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical { if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical {
self.sams[i].state = SamState::Hold; self.sams[i].state = SamState::Hold;
if let Some(rec) = &mut self.rec
&& self.sams[i].kind.armed()
&& !self.sams[i].tracks.is_empty()
{
rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Hold));
}
} }
self.draw_sam(i, out); self.draw_sam(i, out);
} }
return; return;
} }
let logistics = self.logistics();
// Drones by id (none come or go while the systems act), and how many systems have each as their // Drones by id (none come or go while the systems act), and how many systems have each as their
// missile target and as their gun target: counted once, then kept up to date as targets change. // missile target and as their gun target: counted once, then kept up to date as targets change.
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect(); let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
@@ -2416,6 +2460,12 @@ impl Sim {
} }
} }
if self.sams[i].moving() { if self.sams[i].moving() {
if let Some(rec) = &mut self.rec
&& self.sams[i].kind.armed()
&& !self.sams[i].tracks.is_empty()
{
rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Moving));
}
continue; continue;
} }
if !self.sams[i].kind.armed() { if !self.sams[i].kind.armed() {
@@ -2455,24 +2505,45 @@ impl Sim {
let radars: Vec<&Sam> = if me.mode == battery::SamMode::LauncherOnly || (me.kind.far_shooter() && opts.far_shots) { self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect() } else { Vec::new() }; let radars: Vec<&Sam> = if me.mode == battery::SamMode::LauncherOnly || (me.kind.far_shooter() && opts.far_shots) { self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect() } else { Vec::new() };
let cued = |id: u32| !radars.is_empty() && why::radar_cue(me, &radars, id, now); let cued = |id: u32| !radars.is_empty() && why::radar_cue(me, &radars, id, now);
let basis = |tr: &Track, k: f64, role_in_reach: bool| { let basis = |tr: &Track, k: f64, role_in_reach: bool| {
drone(tr).filter(|_| open(tr.id)).and_then(|d| why::basis(me, load, tr, d, now, claimed(d), k, opts, cued(tr.id), role_in_reach)) let d = drone(tr).filter(|_| open(tr.id))?;
why::basis(me, load, tr, d, now, claimed(d), k, opts, cued(tr.id), role_in_reach)
.filter(|b| *b != why::Basis::LastChance || self.last_chance_for(me, tr.class, d, claimed(d)))
}; };
// A target held too long without a launch (the mount can't lay on it, the land) is let go, // A target held too long without a launch (the mount can't lay on it, the land) is let go,
// and not taken again for a while: another system gets it. // and not taken again for a while: another system gets it.
let shy = |id: u32| me.shy.is_some_and(|(s, until)| s == id && until > now); let shy = |id: u32| me.shy.is_some_and(|(s, until)| s == id && until > now);
let stuck = me.held > why::HOLD_MAX; let stuck = me.held > why::HOLD_MAX;
let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| tr.id == *t && basis(tr, 1.1, false).is_some())); let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d));
keep.or_else(|| { // Long shots only while nothing of the system's roles is in its normal reach.
let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d)); let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role));
// Long shots only while nothing of the system's roles is in its normal reach. let keep = had_target.filter(|_| !stuck).and_then(|id| {
let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role)); let tr = tracks.iter().find(|tr| tr.id == id)?;
tracks let b = basis(tr, 1.1, role_in_reach)?;
.iter() (b != why::Basis::LastChance).then_some((me.shot_priority(tr.class, b), id))
.filter(|tr| free(tr) && !shy(tr.id) && basis(tr, 1.0, role_in_reach).is_some()) });
.filter_map(|tr| drone(tr).map(|d| (tr, d))) if let Some((_, id)) = keep
.max_by(|a, b| a.1.threat_at(pos, a.0.est(now)).total_cmp(&b.1.threat_at(pos, b.0.est(now)))) && !me.specializes_in_missiles()
.map(|(_, d)| d.id) {
}) return Some(id);
}
tracks
.iter()
.filter(|tr| free(tr) && !shy(tr.id))
.filter_map(|tr| {
if keep.is_some_and(|(held, _)| me.shot_priority(tr.class, why::Basis::Role) <= held) {
return None;
}
let b = basis(tr, if had_target == Some(tr.id) { 1.1 } else { 1.0 }, role_in_reach)?;
let priority = me.shot_priority(tr.class, b);
if keep.is_some_and(|(held, _)| priority <= held) {
return None;
}
let d = drone(tr)?;
Some((priority, d.threat_at(pos, tr.est(now)), d.id))
})
.max_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)))
.map(|(_, _, id)| id)
.or(keep.map(|(_, id)| id))
}); });
// Guns: the nearest, spread over the targets the other guns and missiles aren't on. // Guns: the nearest, spread over the targets the other guns and missiles aren't on.
let gun_target = spec.gun.as_ref().map(|gun| { let gun_target = spec.gun.as_ref().map(|gun| {
@@ -2537,12 +2608,8 @@ impl Sim {
// combined system's crew would), not only once both are spent. // combined system's crew would), not only once both are spent.
let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0 && sam.cells() > sam.ground_rounds) || (spec.gun.is_some() && sam.bursts == 0); let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0 && sam.cells() > sam.ground_rounds) || (spec.gun.is_some() && sam.bursts == 0);
if spent && sam.reloading == 0 && !sam.empty { if spent && sam.reloading == 0 && !sam.empty {
if logistics { sam.empty = true;
sam.empty = true; ammo_waits += 1;
ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
} }
sam.state = if sam.reloading > 0 { sam.state = if sam.reloading > 0 {
SamState::Reload SamState::Reload
@@ -2551,6 +2618,20 @@ impl Sim {
} else { } else {
SamState::Search SamState::Search
}; };
if let Some(rec) = &mut self.rec {
rec.decisions.resume(sam.id, Channel::Gun);
rec.decisions.resume(sam.id, Channel::Launcher);
if !sam.tracks.is_empty() {
let block = match sam.state {
SamState::Reload => Block::Reload,
SamState::Waiting => Block::Empty,
_ => Block::NoSelection,
};
rec.decisions.note(rec.len, now, sam, Channel::Unit, None, Decision::Held(block));
} else {
rec.decisions.resume(sam.id, Channel::Unit);
}
}
// Nothing to fire at: the mount watches the nearest track of its classes (by the class // Nothing to fire at: the mount watches the nearest track of its classes (by the class
// the network estimates, the unknown among them: a reaction a turn shorter), else it // the network estimates, the unknown among them: a reaction a turn shorter), else it
// goes back to the rest position, under the drive's limits like any other turn. // goes back to the rest position, under the drive's limits like any other turn.
@@ -2572,6 +2653,15 @@ impl Sim {
} }
continue; continue;
}; };
if let Some(rec) = &mut self.rec {
rec.decisions.resume(sam.id, Channel::Unit);
if sam.target.is_none() {
rec.decisions.resume(sam.id, Channel::Launcher);
}
if sam.gun_target.is_none() {
rec.decisions.resume(sam.id, Channel::Gun);
}
}
let (mount, _) = sam.mount(); let (mount, _) = sam.mount();
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
let (aim_id, aim_pos, aim_vel) = aim; let (aim_id, aim_pos, aim_vel) = aim;
@@ -2621,12 +2711,8 @@ impl Sim {
sam.flash = 2; sam.flash = 2;
sam.recoil = 1.0; sam.recoil = 1.0;
if sam.bursts == 0 && sam.missiles == 0 { if sam.bursts == 0 && sam.missiles == 0 {
if logistics { sam.empty = true;
sam.empty = true; ammo_waits += 1;
ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
} }
let (_, rot) = sam.mount(); let (_, rot) = sam.mount();
let s = spec.scale; let s = spec.scale;
@@ -2657,17 +2743,26 @@ impl Sim {
// The aim point is the track's forecast: the farther it is from the truth, the more shells miss. // The aim point is the track's forecast: the farther it is from the truth, the more shells miss.
let off = est.distance(t.pos); let off = est.distance(t.pos);
let p = gun.p * sam.gun_fit() * dark / (t.kind.spec().stealth * (1.0 + (off / 8.0).powi(2))) * (1.0 - dist / (gun.range * 1.3)).max(0.35); let p = gun.p * sam.gun_fit() * dark / (t.kind.spec().stealth * (1.0 + (off / 8.0).powi(2))) * (1.0 - dist / (gun.range * 1.3)).max(0.35);
if self.rng.chance(p) { let hit = self.rng.chance(p);
if let Some(rec) = &mut self.rec {
let outcome = if hit { Decision::Burst } else { Decision::BurstMissed };
rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), outcome);
}
if hit {
gun_hits.push((gt, sam.id)); gun_hits.push((gt, sam.id));
} else { } else {
out.particles("minecraft:crit", t.pos, 1.2, DVec3::ZERO, 0.2, 4); out.particles("minecraft:crit", t.pos, 1.2, DVec3::ZERO, 0.2, 4);
} }
} else if let Some(rec) = &mut self.rec {
rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), Decision::Held(Block::gun(blocks)));
} }
} }
} }
// Missiles. // Missiles.
if let (Some(load), Some(mt)) = (&spec.missile, sam.target) { if let (Some(load), Some(mt)) = (&spec.missile, sam.target) {
let ready = why::missile_blocks(sam) == 0 && !sam.preparing.is_some_and(|p| p.ground); let blocks = why::missile_blocks(sam);
let busy = sam.preparing.is_some_and(|p| p.ground);
let ready = blocks == 0 && !busy;
// The missile turns after its boost, but the launcher must point near the target. // The missile turns after its boost, but the launcher must point near the target.
let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now)); let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now));
let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error); let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error);
@@ -2697,13 +2792,23 @@ impl Sim {
} else { } else {
0 0
}; };
let fire = land == 0 && ready && aligned && sam.prepare_tube(mt, now);
if !fire && let Some(rec) = &mut self.rec {
let block = if land == terrain::WAIT { Block::WaitingForTerrain }
else if land != 0 { Block::Terrain }
else if blocks != 0 { Block::launcher(blocks) }
else if busy { Block::BusyWithGroundShot }
else if !aligned { Block::Aim }
else { Block::Opening };
rec.decisions.note(rec.len, now, sam, Channel::Launcher, Some(mt), Decision::Held(block));
}
if land == terrain::WAIT { if land == terrain::WAIT {
// The land under the shot is not known yet: it waits. // The land under the shot is not known yet: it waits.
} else if land != 0 { } else if land != 0 {
sam.cancel_prepare(); sam.cancel_prepare();
retarget(&mut missile_on, Some(mt), None); retarget(&mut missile_on, Some(mt), None);
sam.target = None; sam.target = None;
} else if ready && aligned && sam.prepare_tube(mt, now) { } else if fire {
sam.eject_cell(n); sam.eject_cell(n);
// Past its normal reach: a long shot, and the next waits. // Past its normal reach: a long shot, and the next waits.
if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) { if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) {
@@ -2722,12 +2827,8 @@ impl Sim {
sam.fired += 1; sam.fired += 1;
sam.cooldown = load.interval; sam.cooldown = load.interval;
if sam.missiles == 0 && (spec.gun.is_none() || sam.bursts == 0) { if sam.missiles == 0 && (spec.gun.is_none() || sam.bursts == 0) {
if logistics {
sam.empty = true; sam.empty = true;
ammo_waits += 1; ammo_waits += 1;
} else {
sam.reloading = sam.reload_time()
}
} }
} }
} }
@@ -2737,9 +2838,11 @@ impl Sim {
t.ammo_waits += ammo_waits; t.ammo_waits += ammo_waits;
}); });
for (kind, muzzle, dir, target, sam) in launches { for (kind, muzzle, dir, target, sam) in launches {
// A launch gives the system away: the enemy saw it fire, no more than that. // A witnessed launch reveals a launcher's area, not its type or loadout.
if let Some(s) = self.sams.iter().find(|s| s.id == sam) { if let Some(s) = self.sams.iter().find(|s| s.id == sam)
self.intel.observe(s, self.tick, ew::Seen::Launch); && recon::has_signal_witness(&self.drones, s.pos)
{
self.recon.signal(s, self.tick, recon::Source::Launch);
} }
// It leaves with the track the system fired on (#66). // It leaves with the track the system fired on (#66).
let fix = self let fix = self
@@ -2750,7 +2853,13 @@ impl Sim {
.map(|tr| Fix { pos: tr.pos, vel: tr.vel, tick: tr.tick, seeker: false }); .map(|tr| Fix { pos: tr.pos, vel: tr.vel, tick: tr.tick, seeker: false });
let spec = kind.spec(); let spec = kind.spec();
let id = self.id(); let id = self.id();
if let Some(rec) = &mut self.rec
&& let Some(unit) = self.sams.iter().find(|s| s.id == sam)
{
rec.decisions.note(rec.len, self.tick, unit, Channel::Launcher, Some(target), Decision::Launched(id));
}
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 }; let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
self.breakthrough_launch(target);
self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0, hold: 0, fix, seen: 0 }); self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0, hold: 0, fix, seen: 0 });
if spec.cold > 0 { if spec.cold > 0 {
// Thrown out by gas: a puff, a thump; the motor lights later. // Thrown out by gas: a puff, a thump; the motor lights later.
@@ -2774,8 +2883,11 @@ impl Sim {
self.fx.push((id, Fx::Tracer { pos, vel, life })); self.fx.push((id, Fx::Tracer { pos, vel, life }));
} }
for (t, by) in gun_hits { for (t, by) in gun_hits {
if let Some(i) = self.drones.iter().position(|d| d.id == t) { if let Some(i) = self.drones.iter().position(|d| d.id == t)
let _ = self.shoot_down(i, by, None, ground, out); && self.shoot_down(i, by, None, ground, out).is_some()
&& let Some(rec) = &mut self.rec
{
rec.decisions.outcome(rec.len, by, t, Channel::Gun, Decision::BurstHit);
} }
} }
for i in 0..self.sams.len() { for i in 0..self.sams.len() {
@@ -3015,11 +3127,12 @@ impl Sim {
self.fireball(m.pos, 2.5 * m.kind.spec().scale, 7); self.fireball(m.pos, 2.5 * m.kind.spec().scale, 7);
out.particles("minecraft:explosion", m.pos, 0.4, DVec3::ZERO, 0.0, 3); out.particles("minecraft:explosion", m.pos, 0.4, DVec3::ZERO, 0.0, 3);
out.sound(sound::BLAST_AIR, m.pos, 1.0, 1.25); out.sound(sound::BLAST_AIR, m.pos, 1.0, 1.25);
let mut hit = false;
if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) { if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) {
self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1); self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1);
if kill { if kill {
let (at, closing) = impacts[&mid]; let (at, closing) = impacts[&mid];
let _ = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out); hit = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out).is_some();
} }
} }
// A missile that lost its target frees it for others. // A missile that lost its target frees it for others.
@@ -3028,6 +3141,13 @@ impl Sim {
{ {
d.engaged = d.engaged.saturating_sub(1); d.engaged = d.engaged.saturating_sub(1);
} }
if let Some(rec) = &mut self.rec {
use decision::{Channel, Outcome};
let outcome = if hit { Outcome::Intercepted(mid) }
else if !kill && impacts.contains_key(&mid) { Outcome::InterceptorMissed(mid) }
else { Outcome::InterceptorEnded(mid) };
rec.decisions.outcome(rec.len, sam, m.target, Channel::Launcher, outcome);
}
} }
} }
for m in &self.missiles { for m in &self.missiles {
+270
View File
@@ -0,0 +1,270 @@
//! The planner's one public observation (#149): a disclosure `Contact` and a recon `Mark` are
//! two channels hinting at the same game objects, on two different scales. This module projects
//! both into a single [`Observation`] — an area, a channel, an age, a confidence and the public
//! game features — and matches them by those public features alone: a mark whose area holds a
//! contact's fix and whose observed category agrees is the same hint, not a second target.
//!
//! A match is a belief, never a fact: it is made only on an exact public category agreement and
//! area overlap, it is flagged (`matched`), and it invents nothing — the contact keeps the kind
//! and place it was observed with, the mark only adds what it publicly saw (a refined radar role,
//! a fresher look). A coarse `Unknown` mark or a contradicting category is *not* matched: it stays
//! a separate hint. The observer's truth map and the units' real ids play no part here.
use super::*;
/// A contact fix this far inside a mark's area (on top of its radius) reads as the same public
/// hint. The fix is exact, the area is coarse: the slack is the cell jitter a report carries.
const MATCH_SLACK: f64 = 8.0;
/// One public hint about one game object, from either channel (#149). There is no health,
/// magazine, link, hidden switch or true place in it: `kind` is `Some` only for a disclosure
/// contact, whose type was identified at the observation; a mark carries its coarse category.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Observation {
/// The hint's public id: a contact's id, or a mark's synthetic one. Never a matched unit's truth.
pub id: u32,
/// The best public place: a contact's fix, or a mark's area centre.
pub at: DVec3,
/// 0 for an exact fix; the area's radius for a mark.
pub radius: f64,
/// The channel that showed it last: flyby, emission, jamming or launch.
pub channel: recon::Source,
/// The tick of the observation this hint rests on.
pub observed: u64,
pub category: recon::Category,
/// A radar's role, once a refined look told it.
pub role: Option<battery::RadarRole>,
/// The type identified at a disclosure observation; `None` for a recon mark.
pub kind: Option<SamKind>,
pub quality: recon::Quality,
/// A second public hint agreed by area and category. A belief for the diagnostic, not a fact.
pub matched: bool,
}
impl Observation {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.observed)
}
pub fn confidence(&self, now: u64) -> Confidence {
ew::confidence_for_age(self.age(now))
}
/// An exact disclosure fix, rather than a coarse area.
pub fn exact(&self) -> bool {
self.radius == 0.0
}
pub fn live(&self, now: u64) -> bool {
self.age(now) < ew::CONTACT_TTL
}
/// The one ranking scale both channels share (#149): the mark's priority parts (freshness,
/// quality, observed role) plus a small premium for being a fix rather than an area.
pub fn rank(&self, now: u64) -> u8 {
let (f, q, r) = recon::priority_parts(self.confidence(now), self.quality, self.category, self.role);
f * 4 + q * 3 + r + u8::from(self.exact()) * 3
}
}
/// The disclosure channel in the one scale the marks already use.
pub(super) fn channel_of(seen: ew::Seen) -> recon::Source {
match seen {
ew::Seen::Launch => recon::Source::Launch,
ew::Seen::Emission => recon::Source::Emission,
ew::Seen::Jamming => recon::Source::Jamming,
}
}
/// Projects contacts and marks into one list of public hints, best first. A mark is matched to a
/// contact only by public features (area overlap and an exact category agreement); a matched mark
/// is consumed — the object is one hint, priced and assigned once. Unmatched marks stand as areas.
pub(super) fn merge(contacts: &[ew::Contact], marks: &[recon::Mark], now: u64) -> Vec<Observation> {
let mut out: Vec<Observation> = contacts
.iter()
.filter(|c| c.live(now))
.map(|c| Observation {
id: c.id,
at: c.at,
radius: 0.0,
channel: channel_of(c.seen),
observed: c.tick,
category: recon::Category::of(c.kind),
role: None,
kind: Some(c.kind),
quality: recon::Quality::Refined,
matched: false,
})
.collect();
let mut areas = Vec::new();
for m in marks.iter().filter(|m| m.live(now)) {
let hit = out.iter_mut().find(|o| {
o.kind.is_some()
&& m.category != recon::Category::Unknown
&& m.category == o.category
&& (m.role.is_none() || o.category == recon::Category::Radar)
&& horizontal(o.at - m.area).length() <= m.radius + MATCH_SLACK
});
match hit {
Some(o) => {
// The match is public evidence, not truth: the fresher look and the refined role
// are what the mark itself saw; the contact's kind and fix are never rewritten.
o.matched = true;
if m.observed > o.observed {
o.observed = m.observed;
o.channel = m.source;
}
if o.category == recon::Category::Radar && m.role.is_some() {
o.role = m.role;
}
}
None => areas.push(Observation {
id: m.id,
at: m.area,
radius: m.radius,
channel: m.source,
observed: m.observed,
category: m.category,
role: m.role,
kind: None,
quality: m.quality,
matched: false,
}),
}
}
out.extend(areas);
out.sort_by(|a, b| b.rank(now).cmp(&a.rank(now)).then(b.observed.cmp(&a.observed)).then(a.id.cmp(&b.id)));
out
}
/// The small game policy (#149): which observed categories a kind is worth turning onto. One
/// place for the fit both the plan's picks and the adaptive assignments read — no hidden state,
/// only the public category and the kind's published role.
pub(super) fn fits(kind: DroneKind, category: recon::Category) -> bool {
use recon::Category as C;
match kind {
DroneKind::Lancet => matches!(category, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(category, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(category, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(category, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false,
}
}
/// The public worst-case envelope of a category: the furthest missile reach and gun range any
/// published kind of that category has, for this drone at this height. What a mark's area may
/// hold is priced by the catalog, never by a hidden unit's actual load (#149).
pub(super) fn category_envelope(category: recon::Category) -> (f64, f64, f64) {
let mut lo = f64::INFINITY;
let mut hi = 0.0f64;
let mut gun = 0.0f64;
for k in SamKind::ALL {
if recon::Category::of(k) != category {
continue;
}
let sp = k.spec();
if let Some(m) = &sp.missile {
lo = lo.min(m.min);
hi = hi.max(m.max);
}
if let Some(g) = &sp.gun {
gun = gun.max(g.range);
}
}
(lo.min(hi), hi, gun)
}
/// The published reach of the strongest radar kind, for a mark that only says "a radar is here".
pub(super) fn radar_envelope(drone: DroneKind, height: f64) -> f64 {
SamKind::ALL
.into_iter()
.filter(|k| recon::Category::of(*k) == recon::Category::Radar)
.map(|k| ew::published_reach(k, drone, height))
.fold(0.0, f64::max)
}
#[cfg(test)]
mod tests {
use super::*;
fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact {
ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }
}
fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark {
recon::Mark {
id,
area: at,
radius: recon::COARSE_AREA,
category,
role: None,
source: recon::Source::Flyby,
observed,
reported: observed,
quality: recon::Quality::Coarse,
looks: 1,
launches: 0,
last_launch: None,
}
}
// #149: one object, two channels, one hint. A mark whose area holds the contact's fix and
// whose category agrees is matched and consumed — not a second target. The match reads only
// public features: two marks of different hidden truths but the same public area/category
// both fold into the one contact.
#[test]
fn a_matching_mark_is_one_hint_not_two() {
let at = DVec3::new(100.0, 70.0, 0.0);
let c = contact(16, SamKind::Radar, at, 100);
let m1 = mark(recon::ID_BASE + 1, at + DVec3::new(20.0, 0.0, 0.0), recon::Category::Radar, 120);
let m2 = mark(recon::ID_BASE + 2, at + DVec3::new(-30.0, 0.0, 10.0), recon::Category::Radar, 130);
let obs = merge(&[c], &[m1, m2], 200);
assert_eq!(obs.len(), 1, "the same public object stayed two hints");
assert!(obs[0].matched && obs[0].exact() && obs[0].kind == Some(SamKind::Radar));
assert_eq!(obs[0].observed, 130, "the fresher public look was not taken");
assert_eq!(obs[0].id, 16, "the hint kept the mark's synthetic id over the contact's");
}
// #149: an unconfirmed match is not a fact. A coarse Unknown mark, a contradicting category,
// or an area that does not hold the fix stays a separate hint — nothing is merged on a guess.
#[test]
fn an_unconfirmed_match_stays_separate() {
let at = DVec3::new(100.0, 70.0, 0.0);
let c = contact(16, SamKind::Radar, at, 100);
let unknown = mark(recon::ID_BASE + 1, at, recon::Category::Unknown, 120);
let wrong = mark(recon::ID_BASE + 2, at, recon::Category::Launcher, 120);
let far = mark(recon::ID_BASE + 3, at + DVec3::new(400.0, 0.0, 0.0), recon::Category::Radar, 120);
let obs = merge(&[c], &[unknown, wrong, far], 200);
assert_eq!(obs.len(), 4, "a weak match was treated as a fact");
assert!(obs.iter().filter(|o| o.kind.is_some()).all(|o| !o.matched));
// A refined role is public only for a radar; a launcher mark never lends one.
let mut radar = mark(recon::ID_BASE + 4, at, recon::Category::Radar, 140);
radar.quality = recon::Quality::Refined;
radar.role = Some(battery::RadarRole::Engagement);
let obs = merge(&[c], &[radar], 200);
assert_eq!(obs.len(), 1);
assert_eq!(obs[0].role, Some(battery::RadarRole::Engagement));
}
// #149: one scale. A fresh confirmed fix outranks an old doubtful area; a refined big-role
// mark outranks a coarse modest one of the same age; the order never reads an id or a truth.
#[test]
fn the_rank_is_one_public_scale() {
let fresh = contact(16, SamKind::Radar, DVec3::ZERO, 190);
let old = mark(recon::ID_BASE + 1, DVec3::X * 500.0, recon::Category::Launcher, 0);
let obs = merge(&[fresh], &[old], 200);
assert_eq!(obs[0].id, 16, "a fresh fix did not lead an old area");
let mut big = mark(recon::ID_BASE + 2, DVec3::X * 900.0, recon::Category::Radar, 190);
big.quality = recon::Quality::Refined;
big.role = Some(battery::RadarRole::Engagement);
let modest = mark(recon::ID_BASE + 3, DVec3::X * 1300.0, recon::Category::Radar, 190);
let obs = merge(&[], &[modest, big], 200);
assert_eq!(obs[0].id, big.id, "the bigger observed role did not lead");
assert!(obs[0].rank(200) > obs[1].rank(200));
}
// #149: the policy fit is the public category, the same for the plan and the adaptive picks.
#[test]
fn the_fit_is_the_public_category() {
assert!(fits(DroneKind::Lancet, recon::Category::Gun));
assert!(!fits(DroneKind::Lancet, recon::Category::Radar));
assert!(fits(DroneKind::Kh22, recon::Category::Radar));
assert!(!fits(DroneKind::Iskander, recon::Category::Gun));
assert!(!fits(DroneKind::Gerbera, recon::Category::Launcher));
}
}
+239 -38
View File
@@ -16,6 +16,12 @@
//! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own //! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own
//! day/night state and the world geometry are used here. //! day/night state and the world geometry are used here.
//! //!
//! An automatic contact is kept while it is within the optics' own reach; after a few failed probes
//! it is let go and not picked again for a while, so a visible alternative can be tried without the
//! post thrashing between hopeless contacts. A player's explicit command is different: it waits
//! until the player changes it, and the status says so. Ready posts are served oldest-probe first,
//! so posts whose phases coincide all get their turn under the same per-tick probe budget.
//!
//! #133 owns the shared class-estimate contract. The observation stays an independent //! #133 owns the shared class-estimate contract. The observation stays an independent
//! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`] //! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`]
//! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through //! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through
@@ -48,6 +54,14 @@ const LOCAL_CANDIDATES: usize = 8;
const TERRAIN_SAMPLES: usize = 6; const TERRAIN_SAMPLES: usize = 6;
/// A relayed track older than this is not worth turning the head for. /// A relayed track older than this is not worth turning the head for.
const CUE_MAX_AGE: u64 = 120; const CUE_MAX_AGE: u64 = 120;
/// Consecutive failed probes before an automatic contact is let go.
const MISS_LIMIT: u32 = 3;
/// Unknown world geometry is a wait, not a verdict: it takes longer to let a contact go.
const UNKNOWN_LIMIT: u32 = 8;
/// Ticks a contact let go after failures is not picked again (no constant switching).
const RETRY_AFTER: u64 = PERIOD * 20;
/// Let-go contacts remembered at once.
const AVOID_MAX: usize = 8;
/// What the post is doing, in the words the map and monitor use. /// What the post is doing, in the words the map and monitor use.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
@@ -192,6 +206,12 @@ pub struct Optical {
/// The freshest relayed track: a direction to look, never a measurement and never a track. /// The freshest relayed track: a direction to look, never a measurement and never a track.
cue: Option<Track>, cue: Option<Track>,
checks: u64, checks: u64,
/// Consecutive failed probes of the current automatic contact.
misses: u32,
/// Automatic contacts let go after failures: not picked again before the tick (anti-thrash).
avoid: Vec<(u32, u64)>,
/// The probe sequence number this post was last served at: the fair queue serves the oldest.
served: Option<u64>,
} }
impl Optical { impl Optical {
@@ -238,6 +258,7 @@ impl Optical {
fn clear_activity(&mut self) { fn clear_activity(&mut self) {
self.target = None; self.target = None;
self.held = 0; self.held = 0;
self.misses = 0;
self.state = OpticalState::Searching; self.state = OpticalState::Searching;
self.block = None; self.block = None;
} }
@@ -245,6 +266,7 @@ impl Optical {
self.target = None; self.target = None;
self.commanded = None; self.commanded = None;
self.held = 0; self.held = 0;
self.misses = 0;
self.observations = 0; self.observations = 0;
self.seen = None; self.seen = None;
self.state = OpticalState::Searching; self.state = OpticalState::Searching;
@@ -253,18 +275,42 @@ impl Optical {
fn select(&mut self, id: Option<u32>) { fn select(&mut self, id: Option<u32>) {
if self.target != id { if self.target != id {
self.held = 0; self.held = 0;
self.observations = 0; self.misses = 0;
self.seen = None; self.seen = None;
// The old picture belongs to the old contact: it must not be read as this one's. // The old picture belongs to the old contact: it must not be read as this one's. Letting
self.observation = None; // the contact go (None) or picking the same one again keeps it: it is a record and ages.
if let Some(id) = id {
if !self.observation.is_some_and(|o| o.target == id) {
self.observations = 0;
self.observation = None;
}
}
} }
self.target = id; self.target = id;
self.block = None; self.block = None;
self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching }; self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching };
} }
fn avoided(&self, id: u32, now: u64) -> bool {
self.avoid.iter().any(|&(other, until)| other == id && until > now)
}
/// Let an automatic contact go after its failed probes and keep it out of the next picks for a
/// while, so the post can try a visible alternative instead of thrashing on this one.
fn release(&mut self, id: u32, now: u64) {
self.target = None;
self.held = 0;
self.misses = 0;
self.state = OpticalState::Searching;
self.block = None;
self.seen = None;
self.avoid.retain(|&(_, until)| until > now);
self.avoid.push((id, now + RETRY_AFTER));
if self.avoid.len() > AVOID_MAX {
self.avoid.remove(0);
}
}
/// A short line for the panel and the monitor: status, class and uncertainty, never a model name. /// A short line for the panel and the monitor: status, class and uncertainty, never a model name.
pub fn status_text(&self) -> String { pub fn status_text(&self) -> String {
match self.state { let body = match self.state {
OpticalState::Searching => "ищет".into(), OpticalState::Searching => "ищет".into(),
OpticalState::Holding => "занят: удерживает контакт".into(), OpticalState::Holding => "занят: удерживает контакт".into(),
OpticalState::Observing => match self.observation { OpticalState::Observing => match self.observation {
@@ -275,7 +321,8 @@ impl Optical {
Some(b) => format!("нет видимости: {}", b.name()), Some(b) => format!("нет видимости: {}", b.name()),
None => "нет видимости".into(), None => "нет видимости".into(),
}, },
} };
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
} }
fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport { fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport {
OpticalReport { OpticalReport {
@@ -290,6 +337,7 @@ impl Optical {
required: self.required(night), required: self.required(night),
seen: self.seen(now).map(|(_, p)| p), seen: self.seen(now).map(|(_, p)| p),
checks: self.checks, checks: self.checks,
commanded: self.commanded,
night, night,
} }
} }
@@ -305,6 +353,8 @@ pub struct OpticalReport {
pub state: OpticalState, pub state: OpticalState,
pub block: Option<SightBlock>, pub block: Option<SightBlock>,
pub target: Option<u32>, pub target: Option<u32>,
/// The contact the player has pinned, if any: the post waits for it until the command changes.
pub commanded: Option<u32>,
pub observation: Option<OpticalObservation>, pub observation: Option<OpticalObservation>,
pub observations: u32, pub observations: u32,
pub held: u32, pub held: u32,
@@ -324,7 +374,7 @@ impl OpticalReport {
format!("оптический пост №{}", self.index) format!("оптический пост №{}", self.index)
} }
pub fn line(&self) -> String { pub fn line(&self) -> String {
match self.state { let body = match self.state {
OpticalState::Searching => "ищет".into(), OpticalState::Searching => "ищет".into(),
OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required), OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required),
OpticalState::Observing => match self.observation { OpticalState::Observing => match self.observation {
@@ -340,7 +390,8 @@ impl OpticalReport {
Some(b) => format!("нет видимости: {}", b.name()), Some(b) => format!("нет видимости: {}", b.name()),
None => "нет видимости".into(), None => "нет видимости".into(),
}, },
} };
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
} }
/// The observation's age, if it has one; an old observation only ages. /// The observation's age, if it has one; an old observation only ages.
pub fn age(&self, now: u64) -> Option<u64> { pub fn age(&self, now: u64) -> Option<u64> {
@@ -377,6 +428,7 @@ impl Sim {
if sam.optical.target != target { if sam.optical.target != target {
sam.optical.target = None; sam.optical.target = None;
sam.optical.held = 0; sam.optical.held = 0;
sam.optical.misses = 0;
sam.optical.observations = 0; sam.optical.observations = 0;
sam.optical.seen = None; sam.optical.seen = None;
// An explicit switch drops the old contact's picture; it was never this contact's. // An explicit switch drops the old contact's picture; it was never this contact's.
@@ -387,33 +439,39 @@ impl Sim {
true true
} }
/// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact. /// The post's own pick: a manual command, the contact it already holds, a cue within reach or
/// the near sector, and only then a far cue that merely points the head. At most one contact.
fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet<u32>) -> Option<u32> { fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet<u32>) -> Option<u32> {
let sam = &self.sams[i]; let sam = &self.sams[i];
let optical = &sam.optical; let optical = &sam.optical;
let alive = |id: u32| alive.contains(&id); let alive = |id: u32| alive.contains(&id);
// A player's command keeps its contact until the command changes, reachable or not.
if let Some(id) = optical.commanded() { if let Some(id) = optical.commanded() {
if alive(id) { if alive(id) {
return Some(id); return Some(id);
} }
} }
if let Some(id) = optical.target() { // Keep the current contact while it is still within the optics' own reach: observations
if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) { // accumulate instead of the post hopping between equally good contacts.
if d.pos.distance(sam.pos) <= CUE_RANGE { if let Some(id) = optical.target()
return Some(id); && alive(id)
} && !optical.avoided(id, now)
} && let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive())
&& d.pos.distance(sam.pos) <= RANGE
{
return Some(id);
} }
// The network's freshest cue: the post measures it itself, the relay only points the head. // A cue within reach is a known contact: the head turns to it and the post measures it itself.
if let Some(t) = optical.cue() if let Some(t) = optical.cue()
&& t.age(now) <= CUE_MAX_AGE && t.age(now) <= CUE_MAX_AGE
&& alive(t.id) && alive(t.id)
&& t.est(now).distance(sam.pos) <= CUE_RANGE && !optical.avoided(t.id, now)
&& t.est(now).distance(sam.pos) <= RANGE
{ {
return Some(t.id); return Some(t.id);
} }
// Nothing cued: search a narrow near sector, nearest first, comparing no more than a few. // Search a narrow near sector, nearest first, comparing no more than a few. The sector is
// The sector is the head's (`dish`, which turns while it searches), not the base's heading. // the head's (`dish`, which turns while it searches), not the base's heading.
let mut local: Vec<(f64, u32)> = self let mut local: Vec<(f64, u32)> = self
.drones .drones
.iter() .iter()
@@ -421,7 +479,7 @@ impl Sim {
.filter_map(|d| { .filter_map(|d| {
let rel = d.pos - sam.pos; let rel = d.pos - sam.pos;
let dist = rel.length(); let dist = rel.length();
if dist > RANGE { if dist > RANGE || optical.avoided(d.id, now) {
return None; return None;
} }
let bearing = heading_of(rel); let bearing = heading_of(rel);
@@ -430,7 +488,19 @@ impl Sim {
.collect(); .collect();
local.sort_by(|a, b| a.0.total_cmp(&b.0)); local.sort_by(|a, b| a.0.total_cmp(&b.0));
local.truncate(LOCAL_CANDIDATES); local.truncate(LOCAL_CANDIDATES);
local.first().map(|&(_, id)| id) if let Some(&(_, id)) = local.first() {
return Some(id);
}
// A far cue points the head but never displaces a visible local contact above.
if let Some(t) = optical.cue()
&& t.age(now) <= CUE_MAX_AGE
&& alive(t.id)
&& !optical.avoided(t.id, now)
&& t.est(now).distance(sam.pos) <= CUE_RANGE
{
return Some(t.id);
}
None
} }
/// One tick of every optical post: age state, then spend the bounded line-of-sight budget. /// One tick of every optical post: age state, then spend the bounded line-of-sight budget.
@@ -481,22 +551,31 @@ impl Sim {
sam.dish = (sam.dish + 0.02) % TAU; sam.dish = (sam.dish + 0.02) % TAU;
} }
} }
// Fair round-robin: a crowd of posts does not starve the last ones for ever. // A fair queue over the posts ready this tick: the post probed longest ago goes first, so
let start = (now as usize) % posts.len(); // posts whose phases coincide all get their turn. The per-tick probe budget still caps work.
let mut ready: Vec<usize> = posts
.iter()
.copied()
.filter(|&i| {
let sam = &self.sams[i];
sam.alive()
&& !sam.moving()
&& sam.part(Part::Sensor) > 0.0
&& now % PERIOD == (sam.id / PARTS) as u64 % PERIOD
})
.collect();
ready.sort_by(|&a, &b| {
self.sams[a]
.optical
.served
.cmp(&self.sams[b].optical.served)
.then(self.sams[a].id.cmp(&self.sams[b].id))
});
let mut checks = 0usize; let mut checks = 0usize;
for k in 0..posts.len() { for i in ready {
if checks >= CHECKS_PER_TICK { if checks >= CHECKS_PER_TICK {
break; break;
} }
let i = posts[(start + k) % posts.len()];
// A dead, moving or blinded post spends none of the tick's probe budget.
if !self.sams[i].alive() || self.sams[i].moving() || self.sams[i].part(Part::Sensor) <= 0.0 {
continue;
}
let phase = (self.sams[i].id / PARTS) as u64 % PERIOD;
if now % PERIOD != phase {
continue;
}
let Some(target) = self.optical_target(i, now, &alive) else { let Some(target) = self.optical_target(i, now, &alive) else {
self.sams[i].optical.select(None); self.sams[i].optical.select(None);
continue; continue;
@@ -516,10 +595,14 @@ impl Sim {
let night = self.night; let night = self.night;
let sight = line_of_sight(ground, from, to, now, range, night); let sight = line_of_sight(ground, from, to, now, range, night);
checks += 1; checks += 1;
self.optical_seq = self.optical_seq.wrapping_add(1);
let seq = self.optical_seq;
let sam = &mut self.sams[i]; let sam = &mut self.sams[i];
sam.optical.checks += 1; sam.optical.checks += 1;
sam.optical.served = Some(seq);
match sight { match sight {
Ok(()) => { Ok(()) => {
sam.optical.misses = 0;
sam.optical.block = None; sam.optical.block = None;
sam.optical.seen = Some((target, d.pos, d.vel, now)); sam.optical.seen = Some((target, d.pos, d.vel, now));
sam.optical.held = sam.optical.held.saturating_add(1); sam.optical.held = sam.optical.held.saturating_add(1);
@@ -554,11 +637,19 @@ impl Sim {
sam.optical.held = 0; sam.optical.held = 0;
sam.optical.block = Some(block); sam.optical.block = Some(block);
sam.optical.state = OpticalState::NoSight; sam.optical.state = OpticalState::NoSight;
// A player's pin waits for the player. An automatic contact that keeps failing
// is let go, then left out of the picks for a while so an alternative can win.
if sam.optical.commanded().is_none() {
sam.optical.misses = sam.optical.misses.saturating_add(1);
let limit = if block == SightBlock::UnknownGeometry { UNKNOWN_LIMIT } else { MISS_LIMIT };
if sam.optical.misses >= limit {
sam.optical.release(target, now);
}
}
} }
} }
// The post's own state is `OpticalState`: it never claims a fire-control track. // The post's own state is `OpticalState`: it never claims a fire-control track.
sam.state = SamState::Search; sam.state = SamState::Search;
sam.optical.target = Some(target);
} }
self.apply_optical_classes(); self.apply_optical_classes();
} }
@@ -707,7 +798,8 @@ mod tests {
let post = optical_at(&mut sim, 0.0, 0.0, 0.0); let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6)); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6));
let mut ground = clear_ground(); let mut ground = clear_ground();
run(&mut sim, &mut ground, 200); // Two night probes: beyond the reduced reach, before the post lets the contact go.
run(&mut sim, &mut ground, 2 * PERIOD);
let r = sim.optical_report(post).unwrap(); let r = sim.optical_report(post).unwrap();
assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.state, OpticalState::NoSight);
assert_eq!(r.block, Some(SightBlock::Night)); assert_eq!(r.block, Some(SightBlock::Night));
@@ -734,11 +826,17 @@ mod tests {
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6));
let mut ground = clear_ground(); let mut ground = clear_ground();
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0); ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0);
run(&mut sim, &mut ground, 200); run(&mut sim, &mut ground, 2 * PERIOD);
let r = sim.optical_report(post).unwrap(); let r = sim.optical_report(post).unwrap();
assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.state, OpticalState::NoSight);
assert_eq!(r.block, Some(SightBlock::Obstacle)); assert_eq!(r.block, Some(SightBlock::Obstacle));
assert!(r.observation.is_none()); assert!(r.observation.is_none());
// With no alternative the post lets the blocked contact go after its failed probes; it does
// not sit on it for ever, and it may try again only after the retry delay.
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
// The same clear land and sky, but no answered sections: unknown, not clear. // The same clear land and sky, but no answered sections: unknown, not clear.
let mut unknown = Sim::new(5); let mut unknown = Sim::new(5);
@@ -752,10 +850,15 @@ mod tests {
} }
} }
ground.answer(cols, 0); ground.answer(cols, 0);
run(&mut unknown, &mut ground, 200); run(&mut unknown, &mut ground, 2 * PERIOD);
let r = unknown.optical_report(post).unwrap(); let r = unknown.optical_report(post).unwrap();
assert_eq!(r.block, Some(SightBlock::UnknownGeometry)); assert_eq!(r.block, Some(SightBlock::UnknownGeometry));
assert!(r.observation.is_none()); assert!(r.observation.is_none());
// Waiting for the world is bounded too: the unknown line is not an eternal block.
run(&mut unknown, &mut ground, UNKNOWN_LIMIT as u64 * PERIOD + 2);
let r = unknown.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
} }
// Once the view is lost, the old observation only ages: no new observation is invented. // Once the view is lost, the old observation only ages: no new observation is invented.
@@ -769,13 +872,20 @@ mod tests {
let first = sim.optical_report(post).unwrap().observation.expect("no day observation"); let first = sim.optical_report(post).unwrap().observation.expect("no day observation");
let count = sim.optical_report(post).unwrap().observations; let count = sim.optical_report(post).unwrap().observations;
sim.night = true; sim.night = true;
// The first night probes fail: the old picture is not refreshed.
run(&mut sim, &mut ground, 2 * PERIOD);
let mid = sim.optical_report(post).unwrap();
assert_eq!(mid.state, OpticalState::NoSight);
assert_eq!(mid.block, Some(SightBlock::Night));
assert_eq!(mid.observation.unwrap().tick, first.tick);
// The post lets the contact go and only rechecks it now and then; the old observation ages.
run(&mut sim, &mut ground, 300); run(&mut sim, &mut ground, 300);
let r = sim.optical_report(post).unwrap(); let r = sim.optical_report(post).unwrap();
let last = r.observation.expect("the old observation was thrown away"); let last = r.observation.expect("the old observation was thrown away");
assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost"); assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost");
assert_eq!(r.observations, count); assert_eq!(r.observations, count);
assert!(last.age(sim.tick) > 200); assert!(last.age(sim.tick) > 200);
assert_eq!(r.state, OpticalState::NoSight); assert_ne!(r.state, OpticalState::Observing);
} }
// The class comes from observable motion, never from DroneKind: two true models with the same // The class comes from observable motion, never from DroneKind: two true models with the same
@@ -841,12 +951,17 @@ mod tests {
}); });
let mut ground = clear_ground(); let mut ground = clear_ground();
// The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach. // The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach.
run(&mut sim, &mut ground, 60); run(&mut sim, &mut ground, 2 * PERIOD);
let r = sim.optical_report(post).unwrap(); let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(id)); assert_eq!(r.target, Some(id));
assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.state, OpticalState::NoSight);
assert_eq!(r.block, Some(SightBlock::OutOfRange)); assert_eq!(r.block, Some(SightBlock::OutOfRange));
assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement"); assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement");
// A far cue may point the head, but after a few failed probes the post lets it go.
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, None);
assert_eq!(r.state, OpticalState::Searching);
} }
// A searching post turns its head: a near contact outside the base heading comes into the sector. // A searching post turns its head: a near contact outside the base heading comes into the sector.
@@ -927,12 +1042,98 @@ mod tests {
run(&mut sim, &mut ground, 60); run(&mut sim, &mut ground, 60);
let r = sim.optical_report(post).unwrap(); let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(far)); assert_eq!(r.target, Some(far));
assert_eq!(r.commanded, Some(far));
assert!(r.line().starts_with("по команде"), "the pin is not in the status: {}", r.line());
// A manual pin is predictable: it waits even when the contact leaves the optics' reach.
sim.drones.iter_mut().find(|d| d.id == far).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
run(&mut sim, &mut ground, 60);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(far), "a manual pin was dropped when the contact left the reach");
assert_eq!(r.block, Some(SightBlock::OutOfRange));
assert!(r.line().starts_with("по команде"), "{}", r.line());
assert!(sim.assign_optical(post, Some(near))); assert!(sim.assign_optical(post, Some(near)));
run(&mut sim, &mut ground, 10); run(&mut sim, &mut ground, 10);
assert_eq!(sim.optical_report(post).unwrap().target, Some(near)); assert_eq!(sim.optical_report(post).unwrap().target, Some(near));
assert!(sim.assign_optical(post, None));
run(&mut sim, &mut ground, 10);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.commanded, None);
assert!(!r.line().contains("по команде"), "{}", r.line());
assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned"); assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned");
} }
// #138: a contact that leaves the optics' reach must not keep the post for ever. The visible
// alternative is picked instead, and it is observed once the post has had its bounded probes.
#[test]
fn an_unreachable_contact_yields_to_a_visible_alternative() {
let mut sim = Sim::new(21);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let gone = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -50.0), DVec3::ZERO);
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -90.0), DVec3::ZERO);
let mut ground = clear_ground();
run(&mut sim, &mut ground, 30);
assert_eq!(sim.optical_report(post).unwrap().target, Some(gone), "the near contact was not picked");
// The held contact is moved far outside the optics' own reach; the alternative stays visible.
sim.drones.iter_mut().find(|d| d.id == gone).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
run(&mut sim, &mut ground, 20);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt), "the post still sat on the unreachable contact");
assert_ne!(r.block, Some(SightBlock::OutOfRange));
run(&mut sim, &mut ground, 200);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt));
let obs = r.observation.expect("the visible alternative was never observed");
assert_eq!(obs.target, alt);
}
// #138: a contact hidden behind a wall is let go after its failed probes, not held for ever,
// and the post observes the visible alternative in the same sector.
#[test]
fn a_blocked_contact_yields_to_a_visible_alternative() {
let mut sim = Sim::new(22);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let hidden = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::ZERO);
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(20.0, 95.0, -100.0), DVec3::ZERO);
let mut ground = clear_ground();
// A wall on the hidden contact's line only: the alternative at x=20 clears it.
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -6), fill: world::Fill::Full }], 0);
run(&mut sim, &mut ground, 300);
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(alt), "the post never tried the visible alternative to {hidden}");
assert_eq!(r.state, OpticalState::Observing);
assert_eq!(r.observation.expect("no observation of the alternative").target, alt);
}
// #138: five posts whose phases coincide must all advance under the per-tick probe budget. The
// ready queue serves the post probed longest ago first, so the fifth is not starved for ever.
#[test]
fn five_posts_in_one_phase_each_get_their_turn() {
let mut sim = Sim::new(23);
let mut posts = Vec::new();
for k in 0..5 {
let x = k as f64 * 5.0;
let post = optical_at(&mut sim, x, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(x, 95.0, -100.0), DVec3::ZERO);
posts.push(post);
// The contact consumed one id; three ordinary ids make four between deployments, so
// every post lands in the same `(id / PARTS) % PERIOD` phase.
for _ in 0..3 {
sim.id();
}
}
assert!(
posts.iter().all(|&post| (post / PARTS) as u64 % PERIOD == (posts[0] / PARTS) as u64 % PERIOD),
"the posts do not share a phase: {posts:?}"
);
let mut ground = clear_ground();
run(&mut sim, &mut ground, 500);
let counts: Vec<u32> = posts.iter().map(|&p| sim.optical_report(p).unwrap().observations).collect();
assert!(counts.iter().all(|&c| c > 0), "a post never got a probe in 500 ticks: {counts:?}");
let min = counts.iter().copied().min().unwrap();
let max = counts.iter().copied().max().unwrap();
assert!(max - min <= 1, "the phase collision starved a post: {counts:?}");
}
// A dead post neither probes nor invents an observation. // A dead post neither probes nor invents an observation.
#[test] #[test]
fn a_dead_post_does_not_probe() { fn a_dead_post_does_not_probe() {
+55 -40
View File
@@ -35,10 +35,29 @@ impl Sam {
} }
} }
fn finish_move(sam: &mut Sam, routes: &mut route::Routes, index: usize, now: u64, why: Option<route::Why>, out: &mut Out) {
if let Some(why) = why {
let report = sam.job.take().is_none_or(|job| {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR).is_none()
});
if report {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), index + 1, why.text()));
}
}
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
}
impl Sim { impl Sim {
/// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear). /// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear).
pub fn order_move(&mut self, i: usize, to: DVec3) -> bool { pub fn order_move(&mut self, i: usize, to: DVec3) -> bool {
self.order_move_near(i, to, 0.0) if !self.order_move_near(i, to, 0.0) {
return false;
}
self.sams[i].job = None;
true
} }
/// The same, where arriving within `slack` blocks of `to` will do (a truck stops beside its job). /// The same, where arriving within `slack` blocks of `to` will do (a truck stops beside its job).
@@ -97,45 +116,45 @@ impl Sim {
sam.dest = None; sam.dest = None;
} }
let Some(to) = sam.dest else { let Some(to) = sam.dest else {
routes.map.remove(&sam.id); finish_move(sam, routes, n, now, None, out);
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
continue; continue;
}; };
let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind, now)); let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind, now));
let (go, last) = match route.drive(ground, now, sam.pos, share) { let (go, last) = match route.drive(ground, now, sam.pos, share) {
route::Drive::Wait(why) => { route::Drive::Wait(why) => {
if route.waited(now) > 40 && !route.told { if sam.job.is_none() && route.waited(now) > 40 && !route.told {
route.told = true; route.told = true;
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text())); out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text()));
} }
continue; continue;
} }
route::Drive::Fail(why) => { route::Drive::Fail(why) => {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text())); if why == route::Why::NoWay && route.approach_works() {
// A truck leaves that job alone for a while, and takes another. continue;
if let Some(job) = sam.job.take() {
routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR);
} }
routes.map.remove(&sam.id); if matches!(why, route::Why::NoWay | route::Why::Stuck)
sam.dest = None; && route.try_works(ground, sam.pos, now, out)
sam.state = SamState::Deploying; {
sam.march = sam.kind.march_ticks(); continue;
}
finish_move(sam, routes, n, now, Some(why), out);
continue; continue;
} }
route::Drive::Go(p, last) => (p, last), route::Drive::Go(p, last) => (p, last),
}; };
let flat = horizontal(go - sam.pos); let flat = horizontal(go - sam.pos);
if last && flat.length() < SPEED * 2.0 { if last && flat.length() < SPEED * 2.0 {
let partial = route.partial; let why = if route.work_approach() {
sam.pos = DVec3::new(go.x, sam.pos.y, go.z); if route.try_works(ground, sam.pos, now, out) {
sam.dest = None; continue;
routes.map.remove(&sam.id); }
if partial { Some(route::Why::NoWay)
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::Partial.text())); } else {
} // A partial route already made measurable progress. A delivery
sam.state = SamState::Deploying; // continues from here when the next stretch of terrain is ready.
sam.march = sam.kind.march_ticks(); (route.partial && sam.job.is_none()).then_some(route::Why::Partial)
};
finish_move(sam, routes, n, now, why, out);
out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6); out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6);
continue; continue;
} }
@@ -143,37 +162,33 @@ impl Sim {
sam.heading = slew(sam.heading, heading_of(flat), 0.06); sam.heading = slew(sam.heading, heading_of(flat), 0.06);
let ahead = DQuat::from_rotation_y(sam.heading) * DVec3::NEG_Z; let ahead = DQuat::from_rotation_y(sam.heading) * DVec3::NEG_Z;
let turning = angle_diff(sam.heading, heading_of(flat)).abs(); let turning = angle_diff(sam.heading, heading_of(flat)).abs();
if sam.kind == SamKind::Tzm && turning > 0.45 {
sam.yaw = sam.heading;
continue;
}
let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2); let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2);
let next = sam.pos + ahead * step; let next = sam.pos + ahead * step;
// The column and chassis clearance ahead: a wall, low ceiling or a change after planning // The column and chassis clearance ahead: a wall, low ceiling or a change after planning
// turns the vehicle back to the planner. Unknown voxels remain a wait, never a drive. // turns the vehicle back to the planner. Unknown voxels remain a wait, never a drive.
let Some(y) = ground.at(next, now) else { let y = match route.clearance(ground, next, now) {
if route.wait_ahead() { route::Clearance::Clear(height) => height,
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text()));
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
}
continue;
};
match route.clearance(ground, next, now) {
route::Clearance::Clear => {}
route::Clearance::Pending => { route::Clearance::Pending => {
if route.wait_ahead() { if route.wait_ahead() {
out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, route::Why::NoMap.text())); finish_move(sam, routes, n, now, Some(route::Why::NoMap), out);
routes.map.remove(&sam.id);
sam.dest = None;
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
} }
continue; continue;
} }
route::Clearance::Blocked => { route::Clearance::Blocked => {
// The folded footprint already fits at the current position. When
// a wide turn would clip a wall, finish the turn before judging the route.
if turning > 0.45 {
sam.yaw = sam.heading;
continue;
}
route.blocked_ahead(next, sam.pos); route.blocked_ahead(next, sam.pos);
continue; continue;
} }
} };
route.ahead_ok(); route.ahead_ok();
let rise = y - sam.pos.y; let rise = y - sam.pos.y;
if rise > route::STEP_UP || rise < -route::STEP_DOWN { if rise > route::STEP_UP || rise < -route::STEP_DOWN {
+149
View File
@@ -0,0 +1,149 @@
//! Per-phase wall time of `Sim::step` (#147 step 3.1): observation only, never
//! a combat input. The simulation stays SDK-independent (it is also built as
//! `airdef-core`), so the adapter installs the host clock
//! (`game.monotonic-nanos`, API level 32) with [`set_clock`] before the first
//! tick; native tests fall back to `std::time::Instant`. The counters are
//! fixed-size and per-thread (a mod instance is single-threaded); timing reads
//! no randomness and changes no decision, so the ordered combat trace is
//! identical with or without it.
use std::cell::RefCell;
/// The named phases of `Sim::step`, as indices into the counters.
pub const PLAN: usize = 0;
pub const ADAPT: usize = 1;
pub const DRONES: usize = 2;
pub const MOVES: usize = 3;
pub const SIGHT: usize = 4;
pub const SAMS: usize = 5;
pub const RECORD: usize = 6;
const NAMED: usize = 7;
/// The phases' report names, in index order.
const NAMES: [&str; NAMED] = ["plan", "adapt", "drones", "moves", "sight", "sams", "record"];
#[derive(Default)]
struct Prof {
total_ns: [u64; NAMED],
max_ns: [u64; NAMED],
steps: u64,
step_ns: u64,
step_max_ns: u64,
other_ns: u64,
other_max_ns: u64,
cur_start: u64,
cur_named: u64,
}
thread_local! {
static PROF: RefCell<Prof> = const { RefCell::new(Prof {
total_ns: [0; NAMED],
max_ns: [0; NAMED],
steps: 0,
step_ns: 0,
step_max_ns: 0,
other_ns: 0,
other_max_ns: 0,
cur_start: 0,
cur_named: 0,
}) };
}
/// The clock the adapter installs (the host's monotonic import); none in native
/// tests, which use the process clock below.
static CLOCK: std::sync::OnceLock<fn() -> u64> = std::sync::OnceLock::new();
/// Installs the monotonic clock, once, before the first timed step.
pub fn set_clock(f: fn() -> u64) {
let _ = CLOCK.set(f);
}
fn now_ns() -> u64 {
match CLOCK.get() {
Some(f) => f(),
None => native_now_ns(),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn native_now_ns() -> u64 {
use std::time::Instant;
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
}
/// Only reached if the adapter never installed a clock; the mod always does in
/// `init`, so the counters stay zero rather than reading an unsupported clock.
#[cfg(target_arch = "wasm32")]
fn native_now_ns() -> u64 {
0
}
/// Marks the start of one `Sim::step`.
pub fn begin_step() {
let start = now_ns();
PROF.with(|p| {
let p = &mut *p.borrow_mut();
p.cur_start = start;
p.cur_named = 0;
});
}
/// Times one named phase: its wall time joins the phase's counters and the
/// step's named sum, so `end_step` can derive the untimed remainder.
pub fn time<T>(phase: usize, f: impl FnOnce() -> T) -> T {
let start = now_ns();
let out = f();
let dt = now_ns().saturating_sub(start);
PROF.with(|p| {
let p = &mut *p.borrow_mut();
p.total_ns[phase] += dt;
p.max_ns[phase] = p.max_ns[phase].max(dt);
p.cur_named += dt;
});
out
}
/// Marks the end of one `Sim::step`: the whole step and its untimed remainder.
pub fn end_step() {
let end = now_ns();
PROF.with(|p| {
let p = &mut *p.borrow_mut();
let total = end.saturating_sub(p.cur_start);
let other = total.saturating_sub(p.cur_named);
p.steps += 1;
p.step_ns += total;
p.step_max_ns = p.step_max_ns.max(total);
p.other_ns += other;
p.other_max_ns = p.other_max_ns.max(other);
});
}
/// Clears the counters (a new world opens).
pub fn reset() {
PROF.with(|p| *p.borrow_mut() = Prof::default());
}
/// Parseable chat lines for `/airdef stats`: each `PROFILE key=value ...` with
/// millisecond totals and per-step maxima (three decimals) and the step count.
/// `other` is the whole step minus the named phases. Split to stay under the
/// game's 256-character chat line; the bench merges every `PROFILE` line.
pub fn report() -> Vec<String> {
PROF.with(|p| {
let p = p.borrow();
let ms = |ns: u64| ns as f64 / 1e6;
let phase = |i: usize| {
format!(
"{}_ms={:.3} {}_max_ms={:.3}",
NAMES[i], ms(p.total_ns[i]), NAMES[i], ms(p.max_ns[i]),
)
};
vec![
format!(
"PROFILE steps={} step_ms={:.3} step_max_ms={:.3} other_ms={:.3} other_max_ms={:.3}",
p.steps, ms(p.step_ns), ms(p.step_max_ns), ms(p.other_ns), ms(p.other_max_ns),
),
format!("PROFILE {} {} {} {}", phase(0), phase(1), phase(2), phase(3)),
format!("PROFILE {} {} {}", phase(4), phase(5), phase(6)),
]
})
}
+307 -96
View File
@@ -100,6 +100,9 @@ struct Item {
/// A raid being planned: its drones, the prices and routes so far, and the planned ones. /// A raid being planned: its drones, the prices and routes so far, and the planned ones.
pub(super) struct Plan { pub(super) struct Plan {
grid: Grid, grid: Grid,
/// The one knowledge version the whole order was chosen on and is routed on (#146): every
/// kind's prices are worked out on it, whenever the budget reaches that kind.
knowledge: ew::KnowledgeSnapshot,
prices: HashMap<DroneKind, Vec<f32>>, prices: HashMap<DroneKind, Vec<f32>>,
routes: HashMap<(DroneKind, i32, i32, i32), Vec<DVec3>>, routes: HashMap<(DroneKind, i32, i32, i32), Vec<DVec3>>,
items: Vec<Item>, items: Vec<Item>,
@@ -124,6 +127,23 @@ pub(super) struct Plan {
mapped: bool, mapped: bool,
} }
impl Plan {
/// What the plan holds, about: the grid's heights, prices, routes and items (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes};
map_bytes(self.prices.len(), std::mem::size_of::<DroneKind>() + std::mem::size_of::<Vec<f32>>())
+ self.prices.values().map(|p| vec_bytes(p)).sum::<usize>()
+ map_bytes(self.routes.len(), std::mem::size_of::<(DroneKind, i32, i32, i32)>() + std::mem::size_of::<Vec<DVec3>>())
+ self.routes.values().map(|r| vec_bytes(r)).sum::<usize>()
+ vec_bytes(&self.items)
+ vec_bytes(&self.done)
+ vec_bytes(&self.wants)
+ vec_bytes(&self.heights)
+ vec_bytes(&self.unanswered)
+ self.knowledge.bytes()
}
}
/// The raid in progress: the counts at its start, for the report. /// The raid in progress: the counts at its start, for the report.
pub(super) struct WaveStats { pub(super) struct WaveStats {
kills: u32, kills: u32,
@@ -262,9 +282,52 @@ impl PartialOrd for Open {
} }
} }
/// Ticks an air start waits for the land under it to be told of. /// Ticks a scheduled launch waits for the local terrain before using a high entry.
const AIR_START_WAIT: u32 = 120; const AIR_START_WAIT: u32 = 120;
/// The build ceiling of the vanilla terrain supported by AirDef.
pub(super) const VANILLA_BUILD_CEILING: f64 = 320.0;
fn unit_strike_limit(total: u32) -> u32 {
(total / 4).max(1).min(total.saturating_sub(1))
}
fn ballistic_velocity(from: DVec3, aim: DVec3, speed: f64) -> DVec3 {
let flat = horizontal(aim - from);
let time = (flat.length() / speed).max(30.0);
flat / time + DVec3::Y * ((aim.y - from.y + 0.5 * GRAVITY * time * time) / time)
}
/// Sample the actual launch column and the first stretch ahead at block resolution.
fn launch_floor(ground: &mut Ground, d: &Drone, offmap: bool) -> (f64, bool) {
let spec = d.kind.spec();
let ballistic = spec.ballistic.is_some();
let heading = horizontal(d.vel).normalize_or(DVec3::NEG_Z);
let climb = d.kind.climb();
let mut floor = d.pos.y;
let mut pending = false;
for blocks in 0..=if ballistic { 8 } else { 24 } {
let dist = f64::from(blocks);
let p = d.pos + heading * dist;
let x = p.x.floor() as i32;
let z = p.z.floor() as i32;
if let Some(Some(height)) = ground.column(x, z, 384) {
let clear = if ballistic { 10.0 } else if offmap { spec.clearance } else { 2.0 };
let rise = if ballistic {
let t = dist / horizontal(d.vel).length().max(0.1);
(d.vel.y * t - 0.5 * GRAVITY * t * t).max(0.0)
} else {
climb.gain(dist)
};
floor = floor.max(height + clear - rise);
} else {
ground.want_chunk((x >> 4, z >> 4));
pending = true;
}
}
(floor, pending)
}
impl Sim { impl Sim {
/// Orders a raid on `objects` (at least one point). A smart raid is planned over the next ticks /// Orders a raid on `objects` (at least one point). A smart raid is planned over the next ticks
/// (each route found in full, a few a tick) and launched when its plan is ready. /// (each route found in full, a few a tick) and launched when its plan is ready.
@@ -280,13 +343,14 @@ impl Sim {
return 0; return 0;
} }
let smart = order.aim == Aim::Smart; let smart = order.aim == Aim::Smart;
// The planner's picture of the layout: one snapshot for the whole order. It is // The planner's picture of the layout: one snapshot for the whole order, kept in the plan
// read-only while the plan is built, and taking it per drone made a big second order // (#146). It is read-only while the plan is built, and taking it per drone made a big second
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127). // order quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let picture = self.picture_of_defences(); let knowledge = self.knowledge_now();
let picture = &knowledge.contacts;
// The partial picture the recon flights have radioed home. It is memory, not the // The partial picture the recon flights have radioed home. It is memory, not the
// force: a mark has an area, a category and an age, never a unit's exact place (#135). // force: a mark has an area, a category and an age, never a unit's exact place (#135).
let leads = self.recon.leads(self.tick); let leads = &knowledge.marks;
// A smart enemy comes from where its raids got through best. // A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU }; let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100). // The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -299,7 +363,8 @@ impl Sim {
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 }; let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
let mut items = Vec::new(); let mut items = Vec::new();
// A smart raid goes for the radars too (a few strikers each); the others pick as they always did. // A smart raid goes for the radars too (a few strikers each); the others pick as they always did.
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &picture) } else { Vec::new() }; let radar_jobs = if smart { self.radar_strikes(&order.kinds, picture, leads) } else { Vec::new() };
let mut diversions_left = unit_strike_limit(total).saturating_sub(radar_jobs.iter().flatten().count() as u32);
let mut index = 0usize; let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() { for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec(); let spec = kind.spec();
@@ -315,8 +380,12 @@ impl Sim {
index += 1; index += 1;
let (target, at_sam) = match job { let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)), Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim, &picture, &leads), None if smart && diversions_left == 0 => (object, None),
None => self.choose_target(kind, object, order.aim, picture, leads),
}; };
if smart && job.is_none() && at_sam.is_some() {
diversions_left -= 1;
}
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0); let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0; let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 }; let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 };
@@ -329,8 +398,8 @@ impl Sim {
let confidence = picture let confidence = picture
.iter() .iter()
.find(|c| c.id == id) .find(|c| c.id == id)
.map(|c| c.confidence(self.tick)) .map(|c| c.confidence(knowledge.tick))
.or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick))); .or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(knowledge.tick)));
d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan }; d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan };
d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c)); d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c));
} else { } else {
@@ -352,6 +421,7 @@ impl Sim {
} }
self.plan = Some(Plan { self.plan = Some(Plan {
grid, grid,
knowledge,
prices: HashMap::new(), prices: HashMap::new(),
routes: HashMap::new(), routes: HashMap::new(),
items, items,
@@ -451,10 +521,7 @@ impl Sim {
from.y = floor; from.y = floor;
d.pos.y = floor; d.pos.y = floor;
if spec.ballistic.is_some() { if spec.ballistic.is_some() {
let aimed = aim + d.err; d.vel = ballistic_velocity(from, d.target, spec.speed);
let flat = horizontal(aimed - from);
let time = (flat.length() / spec.speed).max(30.0);
d.vel = flat / time + DVec3::Y * ((aimed.y - from.y + 0.5 * GRAVITY * time * time) / time);
} }
} }
} }
@@ -465,7 +532,7 @@ impl Sim {
None => { None => {
if !plan.prices.contains_key(&kind) { if !plan.prices.contains_key(&kind) {
let heights = (!plan.heights.is_empty()).then_some(plan.heights.as_slice()); let heights = (!plan.heights.is_empty()).then_some(plan.heights.as_slice());
let (p, cost) = self.price_grid_on(&plan.grid, kind, heights); let (p, cost) = self.price_grid_on(&plan.grid, kind, heights, &plan.knowledge);
work += cost; work += cost;
plan.prices.insert(kind, p); plan.prices.insert(kind, p);
} }
@@ -501,6 +568,7 @@ impl Sim {
// Timing: smart raids arrive at once; others leave at once (a moment apart). // Timing: smart raids arrive at once; others leave at once (a moment apart).
let now = self.tick; let now = self.tick;
let arrive = plan.done.iter().map(|(_, t, e, g, _)| t + e - g).fold(0.0, f64::max); let arrive = plan.done.iter().map(|(_, t, e, g, _)| t + e - g).fold(0.0, f64::max);
let unit_strikes = plan.done.iter().filter(|(d, ..)| d.aim.unit != 0).count() as u32;
for (mut d, time, early, gap, site) in plan.done { for (mut d, time, early, gap, site) in plan.done {
d.smart = plan.smart; d.smart = plan.smart;
let wait = if plan.smart { arrive - (early - gap) - time } else { gap + self.rng.f() * 40.0 }; let wait = if plan.smart { arrive - (early - gap) - time } else { gap + self.rng.f() * 40.0 };
@@ -514,6 +582,14 @@ impl Sim {
if plan.smart && !plan.heights.is_empty() { if plan.smart && !plan.heights.is_empty() {
self.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(plan.grid, std::mem::take(&mut plan.heights)))); self.known_relief = Some(std::sync::Arc::new(ew::KnownRelief::new(plan.grid, std::mem::take(&mut plan.heights))));
} }
// The bounded refresh moment for the unreleased portion (#149): a recon flight is still
// out, so a report may arrive while the drones wait to launch, and the plan's own picks
// may be re-aimed once on it. The deadline is absolute and the launches keep their times
// — no report never pauses the raid.
if plan.smart && !self.smart_legacy && !self.recon.sorties.is_empty() {
self.refresh = Some(ew::Refresh { deadline: self.tick + ew::REFRESH_WINDOW, reports: self.recon.reports });
}
self.diversions_left = unit_strike_limit(plan.total).saturating_sub(unit_strikes);
self.wave = Some(WaveStats { self.wave = Some(WaveStats {
kills: self.kills, kills: self.kills,
hits: self.hits, hits: self.hits,
@@ -529,6 +605,14 @@ impl Sim {
out.sound("minecraft:event.raid.horn", plan.centre, 64.0, 1.0); out.sound("minecraft:event.raid.horn", plan.centre, 64.0, 1.0);
} }
/// Start a new scenario with a fresh enemy picture while preserving the player's layout.
pub fn reset_raid_intelligence(&mut self) {
self.intel = ew::Intel::default();
self.recon = recon::Recon::default();
self.bearing = ew::BearingReport::default();
self.refresh = None;
}
/// Whether a raid is still being planned. /// Whether a raid is still being planned.
pub fn planning(&self) -> bool { pub fn planning(&self) -> bool {
self.plan.is_some() self.plan.is_some()
@@ -546,6 +630,13 @@ impl Sim {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default() self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default()
} }
/// The plan's grid, land, knowledge version and the prices worked out so far (#146; tests).
#[cfg(test)]
pub(super) fn plan_pricing(&self) -> Option<(Grid, Vec<f32>, ew::KnowledgeSnapshot, HashMap<DroneKind, Vec<f32>>)> {
let p = self.plan.as_ref()?;
Some((p.grid, p.heights.clone(), p.knowledge.clone(), p.prices.clone()))
}
/// A drone ready to fly from `from`, not yet in the sky. /// A drone ready to fly from `from`, not yet in the sky.
pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone { pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone {
let id = self.id(); let id = self.id();
@@ -555,10 +646,7 @@ impl Sim {
let err = self.aim_error(kind); let err = self.aim_error(kind);
let target = target + err; let target = target + err;
let (vel, flight) = if spec.ballistic.is_some() { let (vel, flight) = if spec.ballistic.is_some() {
let flat = horizontal(target - from); (ballistic_velocity(from, target, spec.speed), Flight::Ballistic)
let time = (flat.length() / spec.speed).max(30.0);
let up = (target.y - from.y + 0.5 * GRAVITY * time * time) / time;
(flat / time + DVec3::Y * up, Flight::Ballistic)
} else { } else {
(dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise) (dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise)
}; };
@@ -591,24 +679,34 @@ impl Sim {
/// the last observed place and id for those that go for one. Each radar /// the last observed place and id for those that go for one. Each radar
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid. /// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
/// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile. /// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec<Option<(DVec3, u32)>> { pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact], leads: &[recon::Mark]) -> Vec<Option<(DVec3, u32)>> {
// Exact disclosure contacts and recon marks of radars, best first. The order is the // Radars the picture trusts, best first. The candidate ranks the one merged hint list on
// observed role, freshness and quality -- never the id: a hidden station has no id, // the single public scale (#149): a mark matched to a contact is not a second radar. The
// and a big observed radar is worth more than a modest one (#135). // legacy mode keeps the two chains and their old scales. The order is the observed role,
// freshness and quality -- never the id (#135). Both lists are the order's own knowledge
// version, not a later picture (#146).
let now = self.tick; let now = self.tick;
let mut radars: Vec<(u8, u64, u32, DVec3)> = picture let mut radars: Vec<(u8, u64, u32, DVec3)> = if self.smart_legacy {
.iter() picture
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable) .iter()
.map(|c| { .filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
let seen = match c.confidence(now) { .map(|c| {
ew::Confidence::Confirmed => 4, let seen = match c.confidence(now) {
ew::Confidence::Probable => 2, ew::Confidence::Confirmed => 4,
ew::Confidence::Doubtful => 0, ew::Confidence::Probable => 2,
}; ew::Confidence::Doubtful => 0,
(seen * 10 + 3, c.tick, c.id, c.at) };
}) (seen * 10 + 3, c.tick, c.id, c.at)
.chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area))) })
.collect(); .chain(leads.iter().copied().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area)))
.collect()
} else {
observe::merge(picture, leads, now)
.into_iter()
.filter(|o| o.category == recon::Category::Radar && o.confidence(now) >= ew::Confidence::Probable)
.map(|o| (o.rank(now), o.observed, o.id, o.at))
.collect()
};
radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))); radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect(); let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect();
let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect(); let flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
@@ -617,12 +715,12 @@ impl Sim {
return jobs; return jobs;
} }
// Fast ones first (a stable sort keeps the raid's order among equals). // Fast ones first (a stable sort keeps the raid's order among equals).
const RANK: [DroneKind; 8] = const RANK: [DroneKind; 6] =
[DroneKind::Kh22, DroneKind::Zircon, DroneKind::Iskander, DroneKind::Kinzhal, DroneKind::Kh101, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Shahed]; [DroneKind::Kh22, DroneKind::Zircon, DroneKind::Kh101, DroneKind::Geran3, DroneKind::Lancet, DroneKind::Shahed];
let mut ranked: Vec<(usize, usize)> = flat.iter().enumerate().filter_map(|(i, k)| Some((RANK.iter().position(|r| r == k)?, i))).collect(); let mut ranked: Vec<(usize, usize)> = flat.iter().enumerate().filter_map(|(i, k)| Some((RANK.iter().position(|r| r == k)?, i))).collect();
ranked.sort_by_key(|r| r.0); ranked.sort_by_key(|r| r.0);
let want = if flat.len() >= 24 { 3 } else { 2 }; let want = if flat.len() >= 24 { 3 } else { 2 };
let cap = (flat.len() / 4).max(1); let cap = unit_strike_limit(flat.len() as u32) as usize;
for (n, &(_, i)) in ranked.iter().take((radars.len() * want).min(cap)).enumerate() { for (n, &(_, i)) in ranked.iter().take((radars.len() * want).min(cap)).enumerate() {
let radar = radars[n % radars.len()]; let radar = radars[n % radars.len()];
jobs[i] = Some((radar.1, radar.0)); jobs[i] = Some((radar.1, radar.0));
@@ -635,7 +733,7 @@ impl Sim {
/// unit is the last observation — the place seen then, the type identified then — never where /// unit is the last observation — the place seen then, the type identified then — never where
/// the unit actually is or what it has become since. /// the unit actually is or what it has become since.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) { fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option<u32>) {
if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects { if kind.spec().class == Class::Ballistic || kind.spec().decoy || aim == Aim::Objects || (picture.is_empty() && leads.is_empty()) {
return (object, None); return (object, None);
} }
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> { let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
@@ -647,7 +745,41 @@ impl Sim {
if aim == Aim::ObjectsAndSams { if aim == Aim::ObjectsAndSams {
return if roll < 0.33 { pick(picture, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) }; return if roll < 0.33 { pick(picture, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
} }
// Smart: each kind at what it is good against; what gave itself away first (a jamming // The candidate picks from the one merged hint list (#149): a matched mark is not a
// second target, and the fit is the small public policy, not a per-kind guess.
if !self.smart_legacy {
let obs = observe::merge(picture, leads, self.tick);
let pick_o = |list: &[&Observation], r: f64| -> Option<(DVec3, u32)> {
let o = list.get((r * list.len() as f64) as usize)?;
Some((o.at, o.id))
};
let jammers: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Ew && o.channel == recon::Source::Jamming).collect();
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !jammers.is_empty() && roll < 0.6 {
if let Some((at, id)) = pick_o(&jammers, r) {
return (at, Some(id));
}
}
let guns: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Gun || o.kind.is_some_and(|k| k.armed() && k.range() <= 350.0)).collect();
let long: Vec<&Observation> = obs.iter().filter(|o| o.category == recon::Category::Radar || o.kind.is_some_and(|k| k.range() >= 450.0)).collect();
let all: Vec<&Observation> = obs.iter().collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_o(&guns, r).or_else(|| pick_o(&all, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_o(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_o(&all, r),
_ => None,
};
if let Some((at, id)) = choice {
return (at, Some(id));
}
// Nothing the kind's usual preference picked: an unmerged mark whose observed
// category fits is the next best reason to turn a strike off the object.
let fits: Vec<&Observation> = obs.iter().filter(|o| o.kind.is_none() && observe::fits(kind, o.category)).collect();
if let Some((at, id)) = pick_o(&fits, r) {
return (at, Some(id));
}
return (object, None);
}
// Legacy smart: each kind at what it is good against; what gave itself away first (a jamming
// station, a radar, a system that fired). // station, a radar, a system that fired).
let known_ew: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect(); let known_ew: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind == SamKind::Ew).collect();
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 { if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 {
@@ -656,13 +788,12 @@ impl Sim {
} }
// Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars // Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars
// that feed them for the fast missiles. // that feed them for the fast missiles.
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 300.0).collect(); let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 350.0).collect();
let long: Vec<ew::Contact> = let long: Vec<ew::Contact> =
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect(); picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
let choice = match kind { let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)), DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(picture, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r), DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r), DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None, _ => None,
}; };
@@ -681,25 +812,28 @@ impl Sim {
/// system sees it there (its radar's reach for it, the land) and can shoot it. /// system sees it there (its radar's reach for it, the land) and can shoot it.
#[cfg(test)] #[cfg(test)]
pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec<f32>, usize) { pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec<f32>, usize) {
self.price_grid_on(grid, kind, None) self.price_grid_on(grid, kind, None, &self.knowledge_now())
} }
/// The same over the picture this moment holds: a smart plan's own prices are priced on the /// The same over a knowledge version given explicitly: a smart plan's prices are priced on the
/// picture the plan was ordered with (#127). Later observations change nothing here. /// snapshot the plan was ordered with (#127, #146), whenever the budget reaches this kind.
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec<f32>, usize) { /// Later observations change nothing here.
self.price_grid_known(grid, kind, land, &self.picture_of_defences()) pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec<f32>, usize) {
self.price_grid_known(grid, kind, land, knowledge)
} }
/// The same over a picture of the defences: a retarget is priced on the picture its target was /// The same over a snapshot of the defences: a retarget is priced on the knowledge its target was
/// chosen from, so the jobs of one adaptive tick do not each see a different world (#127). Every /// chosen from, so the jobs of one adaptive tick do not each see a different world (#127), and a
/// job reached on a later tick still ages its contacts at its own version's tick (#146). Every
/// capability read here is the contact's published kind and the contact's own observations — /// capability read here is the contact's published kind and the contact's own observations —
/// never the unit's actual switch settings, damage, roles, link health or magazine. /// never the unit's actual switch settings, damage, roles, link health or magazine.
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, picture: &[ew::Contact]) -> (Vec<f32>, usize) { pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec<f32>, usize) {
let mut cost = 0; let mut cost = 0;
let spec = kind.spec(); let spec = kind.spec();
let height = spec.clearance.max(6.0); let height = spec.clearance.max(6.0);
let n = grid.size; let n = grid.size;
let now = self.tick; let now = knowledge.tick;
let picture = &knowledge.contacts;
let mut prices = vec![1.0f32; (n * n) as usize]; let mut prices = vec![1.0f32; (n * n) as usize];
// Known jamming stations: drones that navigate by satellite keep away. // Known jamming stations: drones that navigate by satellite keep away.
if kind.jammable() { if kind.jammable() {
@@ -730,6 +864,17 @@ impl Sim {
.filter(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(pos) <= sight::LINK) .filter(|d| d.kind == SamKind::Radar && d.id != c.id && d.at.distance(pos) <= sight::LINK)
.map(|d| ew::published_reach(d.kind, kind, height)) .map(|d| ew::published_reach(d.kind, kind, height))
.fold(0.0, f64::max); .fold(0.0, f64::max);
// A trusted radar mark near the observed place feeds the network too (#149): the
// strongest published radar reach, since the mark does not name the kind.
let net = if self.smart_legacy {
net
} else {
knowledge.marks
.iter()
.filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable && m.area.distance(pos) <= sight::LINK)
.map(|_| observe::radar_envelope(kind, height))
.fold(net, f64::max)
};
let (hi, gun) = (hi.min(own.max(net)), gun.min(own)); let (hi, gun) = (hi.min(own.max(net)), gun.min(own));
let far = hi.max(gun); let far = hi.max(gun);
// Only the cells round it. // Only the cells round it.
@@ -752,13 +897,57 @@ impl Sim {
} }
} }
} }
// The marks the contacts do not already stand for (#149): an area is priced by its public
// category's published envelope, weighted by the confidence the age alone gives. A mark
// matched to a contact is one hint and was priced through the contact above.
if !self.smart_legacy {
for o in knowledge.observations().into_iter().filter(|o| o.kind.is_none() && o.confidence(now) >= ew::Confidence::Probable) {
let scale: f32 = if o.confidence(now) == ew::Confidence::Confirmed { 1.0 } else { 0.5 };
let pos = o.at;
match o.category {
recon::Category::Ew if kind.jammable() => {
let reach = ew::EW_RADIUS + o.radius;
let (ci, cj) = grid.index(pos);
let r = (reach / grid.cell).ceil() as i32;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
cost += 1;
if horizontal(grid.centre((i, j), pos.y) - pos).length() < reach {
prices[(i * n + j) as usize] += 12.0 * scale;
}
}
}
}
recon::Category::Launcher | recon::Category::Gun => {
let (lo, hi, gun) = observe::category_envelope(o.category);
let far = hi.max(gun) + o.radius;
let (ci, cj) = grid.index(pos);
let r = (far / grid.cell).ceil() as i32 + 1;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
cost += 1;
let ground = land.map(|l| l[(i * n + j) as usize]).filter(|g| g.is_finite());
let p = grid.centre((i, j), ground.map_or(pos.y + height, |g| f64::from(g) + height));
let d = horizontal(p - pos).length();
if d > far {
continue;
}
let missile = (lo..hi).contains(&d);
if !(missile || d < gun) {
continue;
}
prices[(i * n + j) as usize] += (if missile { 30.0 } else { 18.0 }) * scale;
}
}
}
_ => {}
}
}
}
(prices, cost) (prices, cost)
} }
/// Ticks an air start waits for the land under it to be told of. /// A planned raid's drones take off when their time comes.
const AIR_START_WAIT: u32 = 120;
/// A planned raid's drones take off when their time comes.
pub(super) fn release_queue(&mut self, ground: &mut Ground, out: &mut Out) { pub(super) fn release_queue(&mut self, ground: &mut Ground, out: &mut Out) {
let now = self.tick; let now = self.tick;
if self.queue.iter().all(|q| q.0 > now) { if self.queue.iter().all(|q| q.0 > now) {
@@ -770,25 +959,24 @@ const AIR_START_WAIT: u32 = 120;
for (t, mut d) in go { for (t, mut d) in go {
// A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it. // A site's job leaves its site one at a time, from its stock; a destroyed or empty site cancels it.
let from_site = self.sites.site_of(d.id); let from_site = self.sites.site_of(d.id);
// An air start (an off-map site's drone) was planned over land nobody had read. It waits (a second or if let Some(site) = from_site.and_then(|id| self.sites.get(id)).filter(|s| s.alive && s.stock > 0) {
// two) for the land under it to be known, and begins above it if that is higher than the start: else it if site.next_free > now {
// is born inside a hill and crashes at once. self.queue.push((t, d));
let air = from_site.is_some_and(|id| self.sites.list.iter().any(|s| s.id == id && s.offmap)); continue;
if air { }
let clear = if d.kind.spec().ballistic.is_some() { 10.0 } else { d.kind.spec().clearance }; let (floor, pending) = launch_floor(ground, &d, site.offmap);
match ground.at(d.pos, now) { if site.offmap && pending && d.age < AIR_START_WAIT {
None if d.age < AIR_START_WAIT => { d.age += 1;
// The game has no chunk there: it is asked to load the ones round the start (and kept a while). self.queue.push((t, d));
let c = ((d.pos.x.floor() as i32) >> 4, (d.pos.z.floor() as i32) >> 4); continue;
for (dx, dz) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] { }
ground.want_chunk((c.0 + dx, c.1 + dz)); d.pos.y = if site.offmap && pending {
} floor.max(VANILLA_BUILD_CEILING + 10.0 + d.kind.spec().clearance)
d.age += 1; } else {
self.queue.push((t, d)); floor
continue; };
} if d.flight == Flight::Ballistic {
Some(g) if d.pos.y < g + clear => d.pos.y = g + clear, d.vel = ballistic_velocity(d.pos, d.target, d.kind.spec().speed);
_ => {}
} }
d.age = 0; d.age = 0;
} }
@@ -797,11 +985,7 @@ const AIR_START_WAIT: u32 = 120;
self.scout_launch(d.id, site, d.kind, d.pos); self.scout_launch(d.id, site, d.kind, d.pos);
} }
match slot { match slot {
// Free: not a site's job. Air: an off-map site's drone, already in flight position. sites::Slot::Free | sites::Slot::Air => {}
sites::Slot::Free => {}
// The air start was planned over land nobody had read; if it is read by now and the land there is
// higher than the start, it begins above it (else it is born inside a hill and crashes at once).
sites::Slot::Air => {}
sites::Slot::Busy => { sites::Slot::Busy => {
self.queue.push((t, d)); self.queue.push((t, d));
continue; continue;
@@ -811,20 +995,13 @@ const AIR_START_WAIT: u32 = 120;
continue; continue;
} }
sites::Slot::Go => { sites::Slot::Go => {
// On a slope the pad's side or the muzzle's far end can stand in the land that rises there: the
// drone leaves from above the land at its own column, not from inside the hill.
if let Some(g) = ground.at(d.pos, now)
&& d.pos.y < g + 1.5
&& g < d.pos.y + 40.0
{
d.pos.y = g + 1.5;
}
let dir = d.vel.normalize_or_zero(); let dir = d.vel.normalize_or_zero();
out.sound(d.kind.launch_sound(), d.pos, 1.0, 1.0); out.sound(d.kind.launch_sound(), d.pos, 1.0, 1.0);
out.particles("minecraft:flame", d.pos - dir * 1.5, 0.15, -dir * 0.1, 0.02, 4); out.particles("minecraft:flame", d.pos - dir * 1.5, 0.15, -dir * 0.1, 0.02, 4);
out.particles("minecraft:large_smoke", d.pos - dir * 2.5, 0.5, DVec3::new(0.0, 0.05, 0.0), 0.02, 4); out.particles("minecraft:large_smoke", d.pos - dir * 2.5, 0.5, DVec3::new(0.0, 0.05, 0.0), 0.02, 4);
} }
} }
self.breakthroughs.begin(d.id, true);
self.drones.push(d); self.drones.push(d);
self.launched += 1; self.launched += 1;
} }
@@ -908,9 +1085,7 @@ const AIR_START_WAIT: u32 = 120;
it.from = from; it.from = from;
it.d.pos = from; it.d.pos = from;
if spec.ballistic.is_some() { if spec.ballistic.is_some() {
let flat = horizontal(it.d.target - from); it.d.vel = ballistic_velocity(from, it.d.target, spec.speed);
let time = (flat.length() / spec.speed).max(30.0);
it.d.vel = flat / time + DVec3::Y * ((it.d.target.y - from.y + 0.5 * GRAVITY * time * time) / time);
} else { } else {
let pitch = site.class.pitch(); let pitch = site.class.pitch();
let dir = horizontal(it.d.target - from).normalize_or(site.inward()); let dir = horizontal(it.d.target - from).normalize_or(site.inward());
@@ -1001,7 +1176,6 @@ fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::M
let fits = |c: C| match kind { let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew), DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew),
DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew), DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew),
DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher),
DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew), DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew),
_ => false, _ => false,
}; };
@@ -1059,6 +1233,43 @@ mod tests {
sim.drones.iter().chain(sim.queue.iter().map(|q| &q.1)).filter(|d| d.alive() && (d.target - d.err).distance(p) < 6.0).map(|d| d.kind).collect() sim.drones.iter().chain(sim.queue.iter().map(|q| &q.1)).filter(|d| d.alive() && (d.target - d.err).distance(p) < 6.0).map(|d| d.kind).collect()
} }
#[test]
fn smart_waves_reserve_ballistics_and_the_bulk_of_the_raid_for_marked_objects() {
let mut sim = Sim::new(32);
let object = DVec3::new(0.0, 70.0, 0.0);
let kinds = [(DroneKind::Kinzhal, 2), (DroneKind::Iskander, 2), (DroneKind::Oreshnik, 1),
(DroneKind::Kh22, 10), (DroneKind::Shahed, 25)];
for (i, kind) in [SamKind::Radar, SamKind::Pantsir, SamKind::Radar, SamKind::Gepard].into_iter().enumerate() {
let id = sim.id();
let sam = Sam::new(id, kind, DVec3::new(100.0 * i as f64 + 50.0, 70.0, 0.0), 0.0);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
}
let order = RaidOrder { kinds: kinds.to_vec(), approach: Approach::Waves, dist: 400.0, aim: Aim::Smart };
let mut out = Out::default();
sim.order_raid(&order, &[object], &mut out);
let items = &sim.plan.as_ref().unwrap().items;
let ballistic: Vec<_> = items.iter().filter(|item| item.d.kind.spec().class == Class::Ballistic).collect();
assert_eq!(ballistic.len(), 5);
assert!(ballistic.iter().all(|item| item.d.aim.unit == 0 && item.aim.distance(object) < 6.0));
let attacks_on_units = items.iter().filter(|item| item.d.aim.unit != 0).count();
assert!((1..=10).contains(&attacks_on_units), "{attacks_on_units}");
}
#[test]
fn the_launch_floor_checks_the_near_slope_between_coarse_terrain_samples() {
let mut sim = Sim::new(2);
let d = sim.make_drone(DroneKind::Shahed, DVec3::new(0.5, 86.0, 0.5), DVec3::X, DVec3::new(400.0, 64.0, 0.5));
let mut ground = Ground::default();
let unattained = launch_floor(&mut ground, &d, true);
assert!(unattained.1);
let land = Land(|x, _| if x == 5 { 160 } else { 64 });
serve(&mut ground, &land, 1);
let (floor, pending) = launch_floor(&mut ground, &d, true);
assert!(!pending);
assert!(floor > 160.0, "{floor}");
}
#[test] #[test]
fn sead_uses_only_unexpired_observations_at_the_last_known_position() { fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
let mut sim = Sim::new(121); let mut sim = Sim::new(121);
@@ -1067,23 +1278,23 @@ mod tests {
sim.sams.push(radar); sim.sams.push(radar);
let kinds = [(DroneKind::Kh22, 8)]; let kinds = [(DroneKind::Kh22, 8)];
let none = Vec::new(); let none = Vec::new();
assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none)); assert!(sim.radar_strikes(&kinds, &none, &[]).iter().all(Option::is_none));
sim.tick = 20; sim.tick = 20;
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission); sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
// The truth moving after the fix is not an observation: the strike goes to the seen place. // The truth moving after the fix is not an observation: the strike goes to the seen place.
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0); sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
sim.tick = 40; sim.tick = 40;
let picture = sim.picture_of_defences(); let picture = sim.picture_of_defences();
let jobs = sim.radar_strikes(&kinds, &picture); let jobs = sim.radar_strikes(&kinds, &picture, &[]);
assert_eq!(jobs.iter().flatten().count(), 2); assert_eq!(jobs.iter().flatten().count(), 2);
assert!(jobs.iter().flatten().all(|job| *job == (old, 1))); assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
// An old contact is not worth a strike either. // An old contact is not worth a strike either.
sim.tick = 3021; sim.tick = 3021;
let picture = sim.picture_of_defences(); let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none), "a doubtful contact was struck"); assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none), "a doubtful contact was struck");
sim.tick = 6020; sim.tick = 6020;
let picture = sim.picture_of_defences(); let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none)); assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none));
} }
#[test] #[test]
+468 -58
View File
@@ -11,7 +11,9 @@
//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a //! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a
//! kill does not rewrite a mark; only a later look can. A repeated report of the same //! kill does not rewrite a mark; only a later look can. A repeated report of the same
//! observation does not raise its confidence: confidence is the mark's age alone, and a //! observation does not raise its confidence: confidence is the mark's age alone, and a
//! second independent look may refine the area and (for a radar) its role. //! second independent look may refine the area and (for a radar) its role. A wreck a look
//! flies over is not a lead: a fresh one makes no mark, and one the picture already held is
//! radioed home as destroyed and its mark leaves the picture (#139).
use super::*; use super::*;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@@ -32,6 +34,8 @@ pub const REFINE_GAP: u64 = 600;
/// is the unit's place: the reported point is a cell centre, jittered away from it. /// is the unit's place: the reported point is a cell centre, jittered away from it.
pub const COARSE_AREA: f64 = 120.0; pub const COARSE_AREA: f64 = 120.0;
pub const REFINED_AREA: f64 = 48.0; pub const REFINED_AREA: f64 = 48.0;
/// Existing game radius in which an ordinary aircraft can report a nearby signal.
const SIGNAL_WITNESS_RANGE: f64 = 1600.0;
/// How long a mark is remembered (five minutes, as a disclosure contact). /// How long a mark is remembered (five minutes, as a disclosure contact).
pub const MARK_TTL: u64 = 6000; pub const MARK_TTL: u64 = 6000;
/// How long a checked empty zone is not worth another look (unless there is nothing else). /// How long a checked empty zone is not worth another look (unless there is nothing else).
@@ -63,6 +67,11 @@ pub fn is_drone_id(id: u32) -> bool {
id >= DRONE_BASE id >= DRONE_BASE
} }
pub(super) fn has_signal_witness(drones: &[Drone], at: DVec3) -> bool {
drones.iter().any(|drone| drone.alive() && !is_drone_id(drone.id)
&& drone.pos.distance_squared(at) <= SIGNAL_WITNESS_RANGE * SIGNAL_WITNESS_RANGE)
}
/// What a look can tell about a unit's role, in the terms the game already publishes. /// What a look can tell about a unit's role, in the terms the game already publishes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)] #[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Category { pub enum Category {
@@ -199,7 +208,10 @@ pub struct Mark {
/// The tick its report arrived (for the record; confidence is age alone). /// The tick its report arrived (for the record; confidence is age alone).
pub(super) reported: u64, pub(super) reported: u64,
pub(super) quality: Quality, pub(super) quality: Quality,
/// Delivered close looks only. Passive signals may keep an area fresh but cannot refine it.
pub(super) looks: u16, pub(super) looks: u16,
pub(super) launches: u16,
pub(super) last_launch: Option<u64>,
} }
impl Mark { impl Mark {
@@ -240,6 +252,8 @@ pub(super) struct Look {
pub(super) quality: Quality, pub(super) quality: Quality,
pub(super) source: Source, pub(super) source: Source,
pub(super) observed: u64, pub(super) observed: u64,
/// The unit was a wreck when it was seen: the report takes its mark out of the picture.
pub(super) wreck: bool,
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -297,6 +311,8 @@ impl Recon {
mix(m.observed); mix(m.observed);
mix(m.reported); mix(m.reported);
mix(u64::from(m.looks)); mix(u64::from(m.looks));
mix(u64::from(m.launches));
mix(m.last_launch.unwrap_or(u64::MAX));
mix(m.quality as u64); mix(m.quality as u64);
mix(m.category as u64); mix(m.category as u64);
mix(m.source as u64); mix(m.source as u64);
@@ -358,6 +374,77 @@ impl Recon {
self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten()) self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten())
} }
fn insert_mark(&mut self, truth: u32, mut mark: Mark) {
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 {
return;
}
self.next += 1;
mark.id = ID_BASE + self.next;
self.truth.insert(mark.id, truth);
self.marks.insert(mark.id, mark);
}
/// A witnessed game event gives an area and what the event itself showed. Only a sortie can
/// improve visual classification; repeating the same periodic signal cannot do so.
pub(super) fn signal(&mut self, sam: &Sam, now: u64, source: Source) {
let category = match source {
Source::Emission => Category::Radar,
Source::Jamming => Category::Ew,
Source::Launch => Category::Launcher,
Source::Flyby => return,
};
let cell = (sam.pos / COARSE_AREA).round();
let salt = (cell.x as i64 as u32) ^ (cell.z as i64 as u32).rotate_left(16);
let area = area_of(sam.pos, COARSE_AREA, salt);
if let Some(old) = self.mark_for_truth(sam.id) {
let mark = self.marks.get_mut(&old.id).unwrap();
if source == Source::Launch && mark.last_launch.is_none_or(|t| t < now) {
mark.launches = mark.launches.saturating_add(1);
mark.last_launch = Some(now);
}
if (old.looks != 0 && old.live(now) && same_area(&old, area, COARSE_AREA))
|| (now == old.observed && old.source == Source::Launch)
{
return;
}
mark.area = area;
mark.radius = COARSE_AREA;
mark.category = category;
mark.role = None;
mark.source = source;
mark.observed = now;
mark.reported = now;
mark.quality = Quality::Coarse;
mark.looks = 0;
} else {
self.insert_mark(sam.id, Mark {
id: 0,
area,
radius: COARSE_AREA,
category,
role: None,
source,
observed: now,
reported: now,
quality: Quality::Coarse,
looks: 0,
launches: u16::from(source == Source::Launch),
last_launch: (source == Source::Launch).then_some(now),
});
}
}
/// Only a new close look or a witnessed destruction removes a lead about a wreck.
pub(super) fn forget_wreck(&mut self, truth: u32) {
if let Some(mark) = self.mark_for_truth(truth) {
self.marks.remove(&mark.id);
self.truth.remove(&mark.id);
}
for sortie in &mut self.sorties {
sortie.pending.retain(|look| look.truth != truth);
}
}
/// A report that has arrived. The same observation twice changes nothing; a genuinely /// A report that has arrived. The same observation twice changes nothing; a genuinely
/// later look updates the mark and may refine it. The mark keeps its synthetic id. /// later look updates the mark and may refine it. The mark keeps its synthetic id.
pub(super) fn report(&mut self, look: Look, now: u64) { pub(super) fn report(&mut self, look: Look, now: u64) {
@@ -365,11 +452,29 @@ impl Recon {
match existing { match existing {
Some(id) => { Some(id) => {
let Some(old) = self.marks.get(&id).copied() else { return }; let Some(old) = self.marks.get(&id).copied() else { return };
if look.observed <= old.observed { // A visual report spent time in transit. A fresher signal in the same area
// can coexist with that first close look, but cannot supersede a newer place
// or an actual observation that the position is now wrecked.
let agrees_with_signal = old.looks == 0 && !look.wreck && same_area(&old, look.area, look.radius);
if look.observed <= old.observed && !agrees_with_signal {
return; return;
} }
let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP; // The flight saw the wreck itself: the station is off the planner's leads, and
// only the observation — never a hidden kill — takes the mark away (#139).
if look.wreck {
self.marks.remove(&id);
self.truth.remove(&id);
return;
}
let agrees = same_area(&old, look.area, look.radius);
let refine = agrees && old.looks != 0 && look.quality == Quality::Refined;
let m = self.marks.get_mut(&id).unwrap(); let m = self.marks.get_mut(&id).unwrap();
if !agrees {
m.looks = 0;
m.quality = Quality::Coarse;
m.role = None;
m.radius = COARSE_AREA;
}
m.area = look.area; m.area = look.area;
m.radius = if refine { REFINED_AREA } else { m.radius }; m.radius = if refine { REFINED_AREA } else { m.radius };
m.category = look.category; m.category = look.category;
@@ -383,14 +488,12 @@ impl Recon {
} }
} }
None => { None => {
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 { // A wreck is no target: a first look at one leaves no mark at all.
if look.wreck {
return; return;
} }
self.next += 1; self.insert_mark(look.truth, Mark {
let id = ID_BASE + self.next; id: 0,
self.truth.insert(id, look.truth);
self.marks.insert(id, Mark {
id,
area: look.area, area: look.area,
radius: look.radius, radius: look.radius,
category: look.category, category: look.category,
@@ -400,6 +503,8 @@ impl Recon {
reported: now, reported: now,
quality: look.quality, quality: look.quality,
looks: 1, looks: 1,
launches: 0,
last_launch: None,
}); });
} }
} }
@@ -419,6 +524,12 @@ impl Recon {
} }
} }
fn same_area(mark: &Mark, area: DVec3, radius: f64) -> bool {
let reach = mark.radius.max(radius);
horizontal(mark.area - area).length_squared() <= reach * reach
&& (mark.area.y - area.y).abs() <= 16.0
}
/// The rounded place a zone is remembered by (the report, not the truth). /// The rounded place a zone is remembered by (the report, not the truth).
pub(super) fn zone_key(center: DVec3) -> (i64, i64) { pub(super) fn zone_key(center: DVec3) -> (i64, i64) {
(center.x.round() as i64, center.z.round() as i64) (center.x.round() as i64, center.z.round() as i64)
@@ -431,7 +542,7 @@ pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 {
let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519); let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519);
(f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6 (f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6
}; };
DVec3::new((at.x / cell).round() * cell + j(1), at.y, (at.z / cell).round() * cell + j(2)) DVec3::new((at.x / cell).round() * cell + j(1), (at.y / 8.0).round() * 8.0, (at.z / cell).round() * cell + j(2))
} }
/// One look through a zone: the units inside it, as the channels can tell them. The true /// One look through a zone: the units inside it, as the channels can tell them. The true
@@ -439,40 +550,68 @@ pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 {
pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec<Look> { pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec<Look> {
let mut out = Vec::new(); let mut out = Vec::new();
for s in sams { for s in sams {
if !s.alive() || horizontal(s.pos - zone.center).length() > zone.radius { if horizontal(s.pos - zone.center).length() > zone.radius {
continue; continue;
} }
if out.len() >= MAX_OBSERVED { if out.len() >= MAX_OBSERVED {
break; break;
} }
let old = state.mark_for_truth(s.id); let old = state.mark_for_truth(s.id);
let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP); // The jitter is the zone's, not the unit's: the mark must not carry the unit id even
// indirectly.
let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16);
// A wreck is no lead and no emitter (#139). A fresh one makes no mark; one the picture
// already held is reported as destroyed, and the report takes the old mark away. A
// hidden kill never passes through here, so it never rewrites the picture.
if !s.alive() {
if old.is_none() {
continue;
}
out.push(Look {
truth: s.id,
area: area_of(s.pos, COARSE_AREA, salt),
radius: COARSE_AREA,
category: Category::of(s.kind),
role: None,
quality: Quality::Coarse,
source: Source::Flyby,
observed: now,
wreck: true,
});
continue;
}
let coarse = area_of(s.pos, COARSE_AREA, salt);
let refine = old.is_some_and(|m| m.looks != 0 && same_area(&m, coarse, COARSE_AREA)
&& (m.quality == Quality::Refined || now.saturating_sub(m.observed) >= REFINE_GAP));
let quality = if refine { Quality::Refined } else { Quality::Coarse }; let quality = if refine { Quality::Refined } else { Quality::Coarse };
let cell = if refine { REFINED_AREA } else { COARSE_AREA }; let cell = if refine { REFINED_AREA } else { COARSE_AREA };
let category = Category::of(s.kind); let category = Category::of(s.kind);
// A launch is a public event already watched by the disclosure channel; a look that // A launch is a public event already watched by the disclosure channel; a look that
// passes just after one can name that source too. Health, magazine and link never are. // passes just after one can name that source too. Health, magazine and link never are.
let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200); let launched = s.launched > 0
|| old.and_then(|m| m.last_launch).is_some_and(|t| now.saturating_sub(t) < 200)
|| intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200);
// The switch is intent, not work: a radar is an emitter only while `radar_up`, a jammer
// only while the transmitter is really on the air. A silent, packed or failed one is
// just a unit the flyby saw.
let source = match s.kind { let source = match s.kind {
SamKind::Ew if s.ew_on && !s.moving() && !s.ew_lock => Source::Jamming, SamKind::Ew if s.ew_up() => Source::Jamming,
SamKind::Radar if s.radar_up() => Source::Emission, SamKind::Radar if s.radar_up() => Source::Emission,
_ if launched => Source::Launch, _ if launched => Source::Launch,
_ => Source::Flyby, _ => Source::Flyby,
}; };
// The role is a public radar configuration only when a close second look can tell it. // The role is a public radar configuration only when a close second look can tell it.
let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role); let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role);
// The jitter is the zone's, not the unit's: the mark must not carry the unit id even
// indirectly.
let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16);
out.push(Look { out.push(Look {
truth: s.id, truth: s.id,
area: area_of(s.pos, cell, salt), area: if refine { area_of(s.pos, cell, salt) } else { coarse },
radius: cell, radius: cell,
category, category,
role, role,
quality, quality,
source, source,
observed: now, observed: now,
wreck: false,
}); });
} }
out out
@@ -683,6 +822,107 @@ mod tests {
(s.drone, sim.tick) (s.drone, sim.tick)
} }
#[test]
fn ordinary_flyby_reports_an_emitting_area_without_unit_truth() {
let run = |kind, at: DVec3, skip_id| {
let mut sim = Sim::new(135);
if skip_id {
sim.id();
}
let real_id = sam(&mut sim, kind, at);
sim.add_drone(DroneKind::Shahed, at + DVec3::new(20.0, 100.0, 0.0), DVec3::X, at);
sim.tick = 20;
sim.update_sight(&mut Ground::default());
let observations = sim.knowledge_now().observations();
assert!(sim.enemy_picture().contacts.is_empty());
assert_eq!(observations.len(), 1);
let observation = observations[0];
assert!(is_mark(observation.id) && observation.id != real_id);
assert_eq!((observation.kind, observation.role, observation.quality), (None, None, Quality::Coarse));
assert_eq!((observation.channel, observation.category), (Source::Emission, Category::Radar));
assert!(observation.radius > 0.0 && observation.at.distance(at) > 1.0);
sim.sams[0].radar_on = false;
sim.sams[0].pos.x += 630.0;
sim.tick += 20;
sim.update_sight(&mut Ground::default());
assert_eq!(sim.knowledge_now().observations(), observations);
observation
};
let a = run(SamKind::Radar, DVec3::new(37.25, 70.0, 19.75), false);
let b = run(SamKind::Patriot, DVec3::new(42.25, 71.0, 21.75), true);
assert_eq!(a, b, "same-area emission revealed exact unit type, ID or location");
}
#[test]
fn a_scout_alone_does_not_send_an_immediate_emission_or_jamming_report() {
let mut sim = Sim::new(135);
let at = DVec3::new(37.25, 70.0, 19.75);
sam(&mut sim, SamKind::Radar, at);
let jammer = sam(&mut sim, SamKind::Ew, at + DVec3::X * 50.0);
sim.sams.iter_mut().find(|s| s.id == jammer).unwrap().ew_on = true;
sim.add_drone(DroneKind::Gerbera, at + DVec3::Y * 90.0, DVec3::X, at);
sim.drones[0].id = DRONE_BASE + 1;
sim.tick = 20;
sim.update_sight(&mut Ground::default());
sim.step_ew(&mut Out::default());
assert!(sim.knowledge_now().observations().is_empty());
sim.add_drone(DroneKind::Shahed, at + DVec3::Y * 90.0, DVec3::X, at);
sim.update_sight(&mut Ground::default());
sim.step_ew(&mut Out::default());
let observations = sim.knowledge_now().observations();
assert!(observations.iter().any(|o| o.channel == Source::Emission));
assert!(observations.iter().any(|o| o.channel == Source::Jamming && o.category == Category::Ew));
}
#[test]
fn delayed_look_can_classify_an_area_without_turning_signals_into_visual_looks() {
let mut sim = Sim::new(135);
let at = DVec3::new(37.25, 70.0, 19.75);
sam(&mut sim, SamKind::Patriot, at);
let unit = &sim.sams[0];
let zone = Zone { center: at, radius: ZONE_RADIUS };
sim.recon.signal(unit, 20, Source::Emission);
sim.recon.signal(unit, 660, Source::Emission);
let signal = sim.recon.mark_for_truth(unit.id).unwrap();
assert!(signal.looks == 0 && signal.quality == Quality::Coarse);
let pending = look(&sim.sams, &sim.recon, &sim.intel, &zone, 670)[0];
sim.recon.signal(unit, 720, Source::Emission);
sim.recon.report(pending, 760);
let visual = sim.recon.mark_for_truth(unit.id).unwrap();
assert_eq!((visual.id, visual.category, visual.looks), (signal.id, Category::Launcher, 1));
let refined = look(&sim.sams, &sim.recon, &sim.intel, &zone, 1280)[0];
assert_eq!(refined.quality, Quality::Refined);
sim.recon.report(refined, 1370);
sim.recon.signal(unit, 1380, Source::Emission);
sim.recon.signal(unit, 1380, Source::Launch);
sim.recon.signal(unit, 1380, Source::Launch);
sim.recon.signal(unit, 1400, Source::Launch);
let mark = sim.recon.mark_for_truth(unit.id).unwrap();
assert_eq!((mark.quality, mark.launches, mark.last_launch), (Quality::Refined, 2, Some(1400)));
sim.tick = 1400;
assert_eq!(sim.enemy_picture().recon[0].launches, 2);
let text = sim.air_text().unwrap();
let mut loaded = Sim::new(1);
loaded.restore_air(Sim::parse_air(&text).unwrap().unwrap());
let loaded = loaded.recon.marks[&mark.id];
assert_eq!((loaded.launches, loaded.last_launch), (2, Some(1400)));
assert!(loaded.area.distance(mark.area) < 0.02);
let legacy = text.lines().map(|line| {
if line.starts_with("airreconmark ") {
line.rsplitn(3, ' ').last().unwrap()
} else {
line
}
}).collect::<Vec<_>>().join("\n");
let mut loaded = Sim::new(1);
loaded.restore_air(Sim::parse_air(&legacy).unwrap().unwrap());
assert_eq!((loaded.recon.marks[&mark.id].launches, loaded.recon.marks[&mark.id].last_launch), (0, None));
}
// #135: before anything is observed the recon flight and the strike's decisions are a // #135: before anything is observed the recon flight and the strike's decisions are a
// function of the seed, the objectives and the published plan alone. Two hidden layouts // function of the seed, the objectives and the published plan alone. Two hidden layouts
// -- different kinds and places, neither observed -- order the same flight and aims. // -- different kinds and places, neither observed -- order the same flight and aims.
@@ -795,6 +1035,7 @@ mod tests {
quality: Quality::Refined, quality: Quality::Refined,
source: before.source, source: before.source,
observed: before.observed, observed: before.observed,
wreck: false,
}; };
sim.recon.report(look, before.reported + 10_000); sim.recon.report(look, before.reported + 10_000);
let after = *sim.recon.marks.values().next().unwrap(); let after = *sim.recon.marks.values().next().unwrap();
@@ -824,60 +1065,224 @@ mod tests {
s.missiles = 0; s.missiles = 0;
sim.tick += 1000; sim.tick += 1000;
assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture"); assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture");
// A hidden kill does not take the mark away either: it is still a lead until its age
// runs out, and then it is forgotten like any other unrevisited mark (#139).
let mark = before.first().expect("the look made no mark").id;
let observed = sim.recon.marks.get(&mark).expect("the mark is gone").observed;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark), "a hidden kill removed an active lead");
assert!(sim.recon.leads(observed + MARK_TTL - 1).iter().any(|m| m.id == mark), "a mark died before its age");
assert!(sim.recon.leads(observed + MARK_TTL).iter().all(|m| m.id != mark), "a mark outlived its age");
} }
// #139: a look at a wreck is not a lead. A station destroyed before the flight arrives, with
// #135: the channel matters. A silent radar is seen only by the flyby, a transmitting // its switch still on, makes no mark and no lead; its report is an empty observation.
// radar by its emission, a jamming station by its transmission, and a just-fired system
// by the launch the disclosure channel already watched. A hidden switch or magazine is
// not read: only what the game shows.
#[test] #[test]
fn the_source_is_the_channel_that_showed_the_unit() { fn a_fresh_wreck_makes_no_mark_and_no_lead() {
let mut sim = Sim::new(21);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.health = 0.0;
s.radar_on = true;
assert!(!s.radar_up(), "a destroyed radar still reported itself working");
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
assert!(sim.recon.marks.is_empty(), "a look at a fresh wreck reached the picture");
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert!(sim.recon.marks.is_empty(), "a fresh wreck made a mark");
assert!(sim.recon.leads(sim.tick).is_empty(), "a fresh wreck became an active lead");
}
// #139: a hidden kill leaves the mark as the picture remembers it, but a look that flies over
// the wreck reports the destruction and the mark leaves the leads. Nothing of it stays to
// aim at, and a mark no look revisits still ages out on its own.
#[test]
fn a_known_mark_leaves_the_leads_when_its_wreck_is_seen() {
let mut sim = Sim::new(22);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("a live radar made no mark");
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id));
// A hidden kill is not an observation: the old assessment stands.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id), "a hidden kill removed the mark");
// A look that sees the wreck names it as a flyby, and its report takes the mark away.
let zone = Zone { center: object, radius: ZONE_RADIUS };
let wreck = super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).expect("the wreck was not observed");
assert!(wreck.wreck);
assert_eq!(wreck.source, Source::Flyby, "a wreck named an emission");
sim.recon.report(wreck, sim.tick + REPORT_DELAY);
assert!(sim.recon.marks.is_empty(), "the wreck's report left a mark");
assert!(sim.recon.truth.iter().all(|(_, t)| *t != id), "the wreck's truth mapping stayed");
assert!(sim.recon.leads(sim.tick + REPORT_DELAY).is_empty(), "the wreck stayed an active lead");
}
// #139: a wreck observation still waiting for its report is durable. A restored flight takes
// the mark away on its tick, while an older save without the wreck flag reads as before.
#[test]
fn a_wreck_report_survives_a_save_and_removes_the_mark() {
let mut sim = Sim::new(23);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("no mark to destroy");
// The radar dies unseen; a second flight looks at the wreck and its report is unsent
// when the save is taken.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
sim.recon.sorties.clear();
sim.recon.checked.clear();
sim.start_recon(&[object], 0.0, 900.0, &mut Out::default());
let (_, seen_wreck) = look_once(&mut sim);
assert!(sim.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the wreck was not pending");
let text = sim.air_text().expect("a wreck report is durable");
assert!(text.lines().any(|l| l.starts_with("airrecobs ") && l.ends_with(" true")), "the wreck flag was not written");
// An older save has no flag: the same look reads as a live re-observation.
let legacy: String = text
.lines()
.map(|l| {
if l.starts_with("airrecobs ") {
let mut w: Vec<&str> = l.split_whitespace().collect();
w.pop();
w.join(" ")
} else {
l.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let mut old = Sim::new(24);
old.restore_air(Sim::parse_air(&legacy).expect("an older save reads").expect("the air section is there"));
assert!(old.recon.sorties.iter().flat_map(|s| &s.pending).all(|l| !l.wreck), "an older save invented a wreck");
let mut back = Sim::new(25);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert!(back.recon.marks.contains_key(&mark.id), "the save forgot the mark before its wreck report");
assert!(back.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the save lost the wreck report");
back.tick = seen_wreck + REPORT_DELAY;
back.step_recon(&mut Out::default());
assert!(!back.recon.marks.contains_key(&mark.id), "a restored wreck report left the mark");
assert!(back.recon.leads(back.tick).is_empty(), "a restored wreck report stayed an active lead");
}
// #135/#139: the channel matters. A silent, packed or failed radar is only a flyby; so is a
// jammer whose transmitter is off, packed or destroyed. Only a station actually working shows
// its emission, and a wreck is no source at all. A just-fired system is still a launch the
// disclosure channel already watched. A hidden empty magazine is not read.
#[test]
fn the_source_is_the_channel_that_showed_a_working_unit() {
let mut sim = Sim::new(8); let mut sim = Sim::new(8);
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS }; let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0)); let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0)); let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0));
let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0)); let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0));
sim.recon.checked.clear(); let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).map(|l| l.source);
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).unwrap().source; fn unit(sim: &mut Sim, id: u32) -> &mut Sam {
sim.sams.iter_mut().find(|s| s.id == id).unwrap()
}
// Working: the radar emits and the jammer transmits.
assert_eq!(source(&sim, radar), Some(Source::Emission));
unit(&mut sim, ew).ew_on = true;
assert_eq!(source(&sim, ew), Some(Source::Jamming));
// Off: the switch is intent, not work.
unit(&mut sim, radar).radar_on = false;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a silent radar was read as emitting");
unit(&mut sim, radar).radar_on = true;
unit(&mut sim, ew).ew_on = false;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a silent jammer was read as transmitting");
unit(&mut sim, ew).ew_on = true;
// Packed for a march: neither is on the air, whatever the switch says.
unit(&mut sim, radar).state = SamState::Moving;
unit(&mut sim, ew).state = SamState::Moving;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar on the march was read as emitting");
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a jammer on the march was read as transmitting");
unit(&mut sim, radar).state = SamState::Search;
unit(&mut sim, ew).state = SamState::Search;
// Cooling down: a jammer locked by heat is not transmitting either.
unit(&mut sim, ew).ew_lock = true;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "an overheated jammer was read as transmitting");
unit(&mut sim, ew).ew_lock = false;
// Damage: a failed sensor is no radar; a damaged hull with a working sensor still emits.
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar with a failed sensor was read as emitting");
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 1.0;
unit(&mut sim, radar).health = 0.5;
assert_eq!(source(&sim, radar), Some(Source::Emission), "a damaged but working radar lost its emission");
// Destroyed: a wreck is no source and makes no lead at all.
unit(&mut sim, radar).health = 0.0;
unit(&mut sim, ew).health = 0.0;
assert_eq!(source(&sim, radar), None, "a wreck was reported as a lead");
assert_eq!(source(&sim, ew), None, "a wrecked jammer was reported as transmitting");
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = false;
assert_eq!(source(&sim, radar), Source::Flyby, "a silent radar was read as emitting");
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = true;
assert_eq!(source(&sim, radar), Source::Emission);
sim.sams.iter_mut().find(|s| s.id == radar).unwrap().state = super::super::SamState::Moving;
assert_eq!(source(&sim, radar), Source::Flyby, "a moving radar is not emitting");
assert_eq!(source(&sim, ew), Source::Flyby, "a silent jammer was read as transmitting");
sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_on = true;
assert_eq!(source(&sim, ew), Source::Jamming);
sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_lock = true;
assert_eq!(source(&sim, ew), Source::Flyby, "an overheated jammer is not transmitting");
sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch); sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch);
assert_eq!(source(&sim, s400), Source::Launch); assert_eq!(source(&sim, s400), Some(Source::Launch));
// A hidden empty magazine does not change the source. // A hidden empty magazine does not change the source.
sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0; sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0;
assert_eq!(source(&sim, s400), Source::Launch); assert_eq!(source(&sim, s400), Some(Source::Launch));
} }
// #139: a station the picture already holds, seen off, packed or damaged, stays a flyby
// contact: the switch never turns its mark into an emitter, and a working station seen
// again still names its emission.
#[test] #[test]
fn wrecks_do_not_create_targets_in_a_new_flyby_report() { fn a_known_station_that_stops_working_stays_a_flyby_contact() {
let mut sim = Sim::new(8); let mut sim = Sim::new(26);
let object = DVec3::new(0.0, 70.0, 0.0); let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
sam(&mut sim, SamKind::Radar, object); let id = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
sam(&mut sim, SamKind::Ew, object + DVec3::X * 10.0); let seen = |sim: &Sim, now: u64| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, now).into_iter().find(|l| l.truth == id).expect("the radar was not observed");
sim.sams[0].radar_on = true;
sim.sams[1].ew_on = true;
for s in &mut sim.sams { s.health = 0.0; }
sam(&mut sim, SamKind::Gepard, object + DVec3::X * 20.0);
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); let first = seen(&sim, 100);
let (_, seen) = look_once(&mut sim); assert_eq!(first.source, Source::Emission);
sim.tick = seen + REPORT_DELAY; sim.recon.report(first, 100);
sim.step_recon(&mut Out::default()); let mark = sim.recon.mark_for_truth(id).expect("the working look made no mark");
let leads = sim.recon.leads(sim.tick); // Off, then packed for a march, then with a failed sensor: the contact stays, the
assert_eq!(leads.len(), 1); // channel is the flyby alone.
assert_eq!(leads[0].category, Category::of(SamKind::Gepard)); for (change, now) in [(0, 200), (1, 900), (2, 1600)] {
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
match change {
0 => s.radar_on = false,
1 => {
s.radar_on = true;
s.state = SamState::Moving;
}
_ => {
s.state = SamState::Search;
s.comps.0[Part::Sensor as usize] = 0.0;
}
}
let look = seen(&sim, now);
assert!(!look.wreck, "case {change}: a working station was read as a wreck");
assert_eq!(look.source, Source::Flyby, "case {change}: the switch was read as work");
sim.recon.report(look, now);
assert!(sim.recon.marks.contains_key(&mark.id), "case {change}: the contact was lost");
}
// Working again: the refined look names the emission.
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.comps.0[Part::Sensor as usize] = 1.0;
let look = seen(&sim, 2300);
assert_eq!(look.source, Source::Emission);
assert_eq!(look.quality, Quality::Refined);
sim.recon.report(look, 2300);
assert_eq!(sim.recon.mark_for_truth(id).unwrap().source, Source::Emission);
} }
// #135: the planner's order is the observed public role, freshness and quality, not the // #135: the planner's order is the observed public role, freshness and quality, not the
@@ -897,6 +1302,8 @@ mod tests {
reported: observed, reported: observed,
quality, quality,
looks: 1, looks: 1,
launches: 0,
last_launch: None,
}; };
r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined)); r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined));
r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined)); r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined));
@@ -924,7 +1331,7 @@ mod tests {
for quality in [Quality::Coarse, Quality::Refined] { for quality in [Quality::Coarse, Quality::Refined] {
for category in [Category::Unknown, Category::Radar, Category::Launcher, Category::Gun, Category::Ew, Category::Support] { for category in [Category::Unknown, Category::Radar, Category::Launcher, Category::Gun, Category::Ew, Category::Support] {
for role in [None, Some(battery::RadarRole::Search), Some(battery::RadarRole::Engagement), Some(battery::RadarRole::Height), Some(battery::RadarRole::Multifunction)] { for role in [None, Some(battery::RadarRole::Search), Some(battery::RadarRole::Engagement), Some(battery::RadarRole::Height), Some(battery::RadarRole::Multifunction)] {
let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1 }; let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1, launches: 0, last_launch: None };
assert_eq!(m.confidence(now), confidence); assert_eq!(m.confidence(now), confidence);
let (f, q, r) = priority_parts(confidence, quality, category, role); let (f, q, r) = priority_parts(confidence, quality, category, role);
assert_eq!(f * 4 + q * 3 + r, m.priority(now), "{confidence:?} {quality:?} {category:?} {role:?}"); assert_eq!(f * 4 + q * 3 + r, m.priority(now), "{confidence:?} {quality:?} {category:?} {role:?}");
@@ -972,7 +1379,7 @@ mod tests {
d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick)); d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick));
let drone = d.id; let drone = d.id;
sim.drones.push(d); sim.drones.push(d);
sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(ew::KnowledgeSnapshot::empty(sim.tick)), None));
let text = sim.air_text().expect("a recon flight is durable"); let text = sim.air_text().expect("a recon flight is durable");
assert!(text.contains("airrecon"), "the recon section was not written"); assert!(text.contains("airrecon"), "the recon section was not written");
let mut back = Sim::new(6); let mut back = Sim::new(6);
@@ -1068,6 +1475,7 @@ mod tests {
quality: Quality::Coarse, quality: Quality::Coarse,
source: Source::Flyby, source: Source::Flyby,
observed: 100, observed: 100,
wreck: false,
}; };
r.report(coarse_look, 200); r.report(coarse_look, 200);
let coarse = r.mark(); let coarse = r.mark();
@@ -1096,12 +1504,13 @@ mod tests {
quality: Quality::Refined, quality: Quality::Refined,
source: Source::Emission, source: Source::Emission,
observed: 1000, observed: 1000,
wreck: false,
}; };
sim.recon.report(look(1, battery::RadarRole::Search), 1000); sim.recon.report(look(1, battery::RadarRole::Search), 1000);
sim.recon.report(look(2, battery::RadarRole::Engagement), 1000); sim.recon.report(look(2, battery::RadarRole::Engagement), 1000);
let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap(); let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap();
let (modest, big) = (id_of(1), id_of(2)); let (modest, big) = (id_of(1), id_of(2));
let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[]); let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[], &sim.recon.leads(sim.tick));
let first: Vec<u32> = jobs.iter().flatten().map(|(_, id)| *id).collect(); let first: Vec<u32> = jobs.iter().flatten().map(|(_, id)| *id).collect();
assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker"); assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker");
assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all"); assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all");
@@ -1142,6 +1551,7 @@ mod tests {
quality: Quality::Coarse, quality: Quality::Coarse,
source: Source::Flyby, source: Source::Flyby,
observed: 100, observed: 100,
wreck: false,
}, },
100, 100,
); );
File diff suppressed because it is too large Load Diff
+155 -15
View File
@@ -297,7 +297,9 @@ fn wall_relief() -> std::sync::Arc<super::ew::KnownRelief> {
for j in 0..g.size { for j in 0..g.size {
let x = g.min.x + (f64::from(i) + 0.5) * g.cell; let x = g.min.x + (f64::from(i) + 0.5) * g.cell;
let z = g.min.z + (f64::from(j) + 0.5) * g.cell; let z = g.min.z + (f64::from(j) + 0.5) * g.cell;
if (x + 1000.0).abs() < 80.0 && z.abs() < 420.0 { // The wall spans every approach lane: whichever drone the adaptive tick leaves last,
// its east-west route crosses the ridge, so the two relief versions must differ (#149).
if (x + 1000.0).abs() < 80.0 && z.abs() < 2000.0 {
h[(i * g.size + j) as usize] = 1000.0; h[(i * g.size + j) as usize] = 1000.0;
} }
} }
@@ -382,14 +384,14 @@ fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
destroyed: None, destroyed: None,
launches: 0, launches: 0,
}; };
let known_all = std::sync::Arc::new(vec![contact(threat, threat_at), contact(target, aim)]); let known_all = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 1, contacts: vec![contact(threat, threat_at), contact(target, aim)], marks: Vec::new() });
let known_target = std::sync::Arc::new(vec![contact(target, aim)]); let known_target = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 2, contacts: vec![contact(target, aim)], marks: Vec::new() });
// The picture holds both units: a job's unit is alive only while the picture believes in it. // The picture holds both units: a job's unit is alive only while the picture believes in it.
for c in known_all.iter() { for c in known_all.contacts.iter() {
sim.intel.note(c.id, c.kind, c.at, true, 0, super::ew::Seen::Emission); sim.intel.note(c.id, c.kind, c.at, true, 0, super::ew::Seen::Emission);
} }
let mut add = |known: std::sync::Arc<Vec<super::ew::Contact>>, version: u64| -> u32 { let mut add = |known: std::sync::Arc<super::ew::KnowledgeSnapshot>, version: u64| -> u32 {
let mut d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim); let mut d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim);
d.smart = true; d.smart = true;
d.err = DVec3::ZERO; d.err = DVec3::ZERO;
@@ -420,24 +422,162 @@ fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
assert_eq!(r1, r3, "jobs of one knowledge version did not reuse their route cache"); assert_eq!(r1, r3, "jobs of one knowledge version did not reuse their route cache");
} }
// #31: a big cache of fresh columns is not scanned on every answer // #146: one Smart order, two kinds, the land answers starved while the plan waits and a visible
// contact disclosed mid-wait: every kind's targets and routes stay on the snapshot the order was
// chosen with, not on whatever the picture holds when the budget reaches that kind. The plan is
// driven by `plan_step` alone so no adaptive tick retargets the queue before it is read.
#[test] #[test]
fn big_ground_cache_is_swept_rarely() { fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() {
use super::sites::testland::{serve, Land};
// What the order's drones end up with: kind, aim and route, in the plan's own order.
fn fly(extra_at_order: bool, extra_mid_wait: bool) -> Vec<(DroneKind, DVec3, Vec<DVec3>)> {
let mut sim = Sim::new(146);
let radar = sim.id();
sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(120.0, 70.0, 0.0), 0.0));
sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission);
sim.targets.push(DVec3::new(0.0, 70.0, 0.0));
sim.target_health.push(100.0);
let extra = sim.id();
let extra_at = DVec3::new(0.0, 70.0, 150.0);
if extra_at_order {
sim.intel.note(extra, SamKind::Patriot, extra_at, true, sim.tick, ew::Seen::Emission);
}
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Geran3, 4)], approach: Approach::AllSides, dist: 300.0, aim: Aim::Smart };
let at = sim.tick;
assert_eq!(sim.order_raid(&order, &sim.targets.clone(), &mut out), 10);
let (_, _, knowledge, _) = sim.plan_pricing().expect("the order was not accepted");
assert_eq!(knowledge.tick, at, "the plan does not keep the tick it was ordered at");
assert!(knowledge.contacts.iter().any(|c| c.id == radar));
assert_eq!(knowledge.contacts.iter().any(|c| c.id == extra), extra_at_order);
let (mut starved, mut added) = (0, !extra_mid_wait);
for _ in 0..600 {
if !sim.planning() {
break;
}
let mapping = sim.plan_pricing().is_some_and(|(_, h, _, _)| !h.is_empty());
if mapping && !added {
// The game tells of no land for a while: the plan waits for the relief, and the
// contact arrives while it waits, after the targets were already chosen.
if starved < 10 {
sim.plan_step(Some(&mut ground), &mut out);
sim.tick += 1;
starved += 1;
continue;
}
sim.intel.note(extra, SamKind::Patriot, extra_at, true, sim.tick, ew::Seen::Emission);
added = true;
}
serve(&mut ground, &land, sim.tick);
sim.plan_step(Some(&mut ground), &mut out);
sim.tick += 1;
}
assert!(!sim.planning(), "the plan never finished");
assert!(added, "the mid-wait contact was never disclosed");
if extra_mid_wait {
assert!(sim.picture_of_defences().iter().any(|c| c.id == extra), "the disclosure did not reach the picture");
}
sim.queue.iter().map(|(_, d)| (d.kind, d.target, d.route.clone())).collect()
}
// Patriot's stock roles include jet drones: Geran3 is the kind its report moves.
let waited = fly(false, true);
assert_eq!(waited, fly(false, false), "a contact disclosed while the plan waited for the land changed its routes");
assert_ne!(waited, fly(true, false), "the test does not distinguish the order's picture from a later one");
}
// #146: two jobs of one knowledge version, worked out on different ticks across the boundary
// where the current picture would stop believing a contact's own sensor, price the same world.
// An explicitly new retarget, with a fresh report of its own, may use the new report.
#[test]
fn retarget_jobs_of_one_version_age_at_their_own_tick() {
let mut sim = Sim::new(146);
let flat = flat_relief();
let start = DVec3::new(-1000.0, 100.0, 0.0);
let aim = DVec3::new(1000.0, 70.0, 0.0);
let threat = sim.id();
let threat_at = DVec3::new(0.0, 70.0, 0.0);
sim.sams.push(Sam::new(threat, SamKind::Patriot, threat_at, 0.0));
let target = sim.id();
sim.sams.push(Sam::new(target, SamKind::Patriot, aim, 0.0));
// The version sits one tick inside the emission belief's TTL: at the version the threat is
// believed to see on its own radar; one tick later the current picture would not believe it.
let version = ew::CONTACT_TTL - 1;
let contact = |id: u32, at: DVec3, tick: u64| ew::Contact { id, kind: SamKind::Patriot, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 };
let known = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version, contacts: vec![contact(threat, threat_at, 0), contact(target, aim, version)], marks: Vec::new() });
sim.intel.note(target, SamKind::Patriot, aim, true, version, ew::Seen::Emission);
fn add(sim: &mut Sim, version: u64, known: std::sync::Arc<ew::KnowledgeSnapshot>, target: u32, start: DVec3, aim: DVec3, flat: &std::sync::Arc<ew::KnownRelief>) -> u32 {
// A jet drone: Patriot's published roles engage it, so the belief in its radar prices it.
let mut d = sim.make_drone(DroneKind::Geran3, start, DVec3::X, aim);
d.smart = true;
d.err = DVec3::ZERO;
d.target = aim;
d.route = vec![start, aim];
// Past the switch cap: the adaptive tick may not turn these drones onto anything else.
d.aim = ew::Aim { unit: target, since: version, switches: ew::SWITCH_CAP, confidence: Some(ew::Confidence::Confirmed) };
let id = d.id;
sim.queue.push((0, d));
sim.retargets.push_back(ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone())));
id
}
let first = add(&mut sim, version, known.clone(), target, start, aim, &flat);
sim.tick = version;
sim.adapt();
assert!(sim.retargets.is_empty(), "the first job was not finished");
let r1 = retarget_route(&sim, first);
// The same version and the same snapshot, reached one tick past the boundary.
let second = add(&mut sim, version, known.clone(), target, start, aim, &flat);
sim.tick = version + 1;
sim.adapt();
assert!(sim.retargets.is_empty(), "the second job was not finished");
let r2 = retarget_route(&sim, second);
assert_eq!(r1, r2, "a job of the same version aged its contacts with the current tick");
// An explicitly new retarget: a fresh report of the threat at the new version is priced again.
sim.intel.note(threat, SamKind::Patriot, threat_at, true, version + 1, ew::Seen::Emission);
let fresh = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: vec![contact(threat, threat_at, version + 1), contact(target, aim, version)], marks: Vec::new() });
let third = add(&mut sim, version + 1, fresh, target, start, aim, &flat);
sim.adapt();
assert!(sim.retargets.is_empty(), "the new job was not finished");
let r3 = retarget_route(&sim, third);
assert_eq!(r1, r3, "an explicitly new retarget could not use the new report");
// A new version without a new report: its own tick is past the boundary, so it no longer
// believes the threat's radar and flies the direct line. This is what the same-version job
// above must NOT do, and what makes the two versions distinguishable.
let stale = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: known.contacts.clone(), marks: Vec::new() });
let fourth = add(&mut sim, version + 1, stale, target, start, aim, &flat);
sim.adapt();
assert!(sim.retargets.is_empty(), "the fourth job was not finished");
let r4 = retarget_route(&sim, fourth);
assert_ne!(r1, r4, "the test does not distinguish believing the threat from not believing it");
assert_ne!(r3, r4, "a new version without a new report kept the old belief");
}
// #31: the ground cache is bounded — beyond the cap the oldest answers go, and the sweep
// lands well under the cap so it is not every answer (the fullscreen-map OOM: a cache that
// only swept above 300_000 fresh columns grew without bound under a wide query pattern).
#[test]
fn big_ground_cache_is_bounded_and_swept_rarely() {
let mut ground = Ground::default(); let mut ground = Ground::default();
ground.known.extend((0..300_001).map(|x| ((x, 0), (64, 2000)))); ground.known.extend((0..KNOWN_MAX as i32).map(|x| ((x, 0), (64, 2000))));
ground.known.insert((-1, 0), (64, 0)); ground.known.insert((-1, 0), (64, 0));
// The first answer past the threshold sweeps what is stale and keeps what is fresh. // The answer past the cap sweeps: the stale column goes, the fresh stay, and the cache
// lands at three quarters of the cap.
ground.answer(vec![(-2, 0, 64)], 2100); ground.answer(vec![(-2, 0, 64)], 2100);
assert!(!ground.known.contains_key(&(-1, 0)), "a stale column was never swept"); assert!(!ground.known.contains_key(&(-1, 0)), "a stale column was never swept");
assert!(ground.known.len() > 300_000); assert!(ground.known.len() <= KNOWN_MAX * 3 / 4 + 1, "the sweep did not bound the cache: {}", ground.known.len());
// The next ones wait their pause: a stale column added now survives them. assert!(ground.known.len() > KNOWN_MAX / 2, "the sweep took too much: {}", ground.known.len());
// The next answers do not sweep again at once: a stale column added now survives them.
ground.known.insert((-1, 0), (64, 0)); ground.known.insert((-1, 0), (64, 0));
let swept = ground.swept; let len = ground.known.len();
ground.answer(vec![(-3, 0, 64)], 2101); ground.answer(vec![(-3, 0, 64)], 2101);
assert_eq!(ground.swept, swept, "swept again at once"); assert_eq!(ground.known.len(), len + 1, "swept again at once");
assert!(ground.known.contains_key(&(-1, 0))); assert!(ground.known.contains_key(&(-1, 0)));
ground.answer(vec![(-4, 0, 64)], 2100 + SWEEP_EVERY); // An evicted column is asked again when it is next needed: the cache is reconstructible.
assert!(!ground.known.contains_key(&(-1, 0)), "never swept again"); let evicted = (0, 0);
assert!(!ground.known.contains_key(&evicted));
assert!(ground.at(DVec3::new(evicted.0 as f64, 0.0, 0.0), 2102).is_none());
assert!(ground.take_wanted().contains(&evicted), "an evicted column was not asked again");
} }
// #32: the pieces of an Oreshnik teach the enemy about the sector it came from // #32: the pieces of an Oreshnik teach the enemy about the sector it came from
+378 -76
View File
@@ -66,7 +66,7 @@ pub(super) enum Drive {
/// Result of checking the vehicle's clearance at its next position. /// Result of checking the vehicle's clearance at its next position.
pub(super) enum Clearance { pub(super) enum Clearance {
Clear, Clear(f64),
Blocked, Blocked,
Pending, Pending,
} }
@@ -105,20 +105,22 @@ impl Chassis {
} }
/// Every voxel whose square intersects the conservative footprint, including grazing corners. /// Every voxel whose square intersects the conservative footprint, including grazing corners.
fn samples(self) -> Vec<(i32, i32)> { fn samples(self, pos: DVec3) -> impl Iterator<Item = (i32, i32)> {
let r = self.radius.ceil() as i32; let min_x = (pos.x - self.radius).floor() as i32;
(-r..=r).flat_map(|x| (-r..=r).filter_map(move |z| { let max_x = (pos.x + self.radius).floor() as i32;
let dx = (f64::from(x.abs()) - 0.5).max(0.0); let min_z = (pos.z - self.radius).floor() as i32;
let dz = (f64::from(z.abs()) - 0.5).max(0.0); let max_z = (pos.z + self.radius).floor() as i32;
(min_x..=max_x).flat_map(move |x| (min_z..=max_z).filter_map(move |z| {
let dx = (f64::from(x) - pos.x).max(pos.x - (f64::from(x) + 1.0)).max(0.0);
let dz = (f64::from(z) - pos.z).max(pos.z - (f64::from(z) + 1.0)).max(0.0);
(dx * dx + dz * dz <= self.radius * self.radius).then_some((x, z)) (dx * dx + dz * dz <= self.radius * self.radius).then_some((x, z))
})).collect() }))
} }
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
struct Info { struct Info {
h: f32, h: f32,
ok: bool,
} }
enum Eval { enum Eval {
@@ -127,6 +129,45 @@ enum Eval {
Pending, Pending,
} }
/// Look below the reachable ceiling rather than lifting a vehicle onto an overhang.
/// The heightmap still distinguishes exposed water from dry solid surfaces.
fn support(ground: &mut Ground, x: i32, z: i32, near: f64, up: f64, down: f64, now: u64) -> Eval {
let column = ground.column(x, z, 1024);
if ground.known.get(&(x, z)).is_some_and(|&(_, tick)| tick == STALE) {
return Eval::Pending;
}
let top = match column {
None => return Eval::Pending,
Some(None) => return Eval::Bad,
Some(Some(top)) => top,
};
let low = (near - down).ceil() as i32 - 1;
let high = (near + up).floor() as i32 - 1;
let top = top as i32 - 1;
if top < low {
return Eval::Bad;
}
let mut section = None;
match ground.world.road_block(&mut section, x, top, z, now) {
None => return Eval::Pending,
// The motion-blocking map includes the surface of an open body of water.
Some(Some(true)) => {}
Some(_) => return Eval::Bad,
}
if top <= high {
return Eval::Ok((top + 1) as f32);
}
for y in (low..=high).rev() {
match ground.world.road_block(&mut section, x, y, z, now) {
Some(Some(true)) => return Eval::Ok((y + 1) as f32),
Some(Some(false)) => {}
None => return Eval::Pending,
Some(None) => return Eval::Bad,
}
}
Eval::Bad
}
#[derive(PartialEq)] #[derive(PartialEq)]
struct Open(f32, (i32, i32)); struct Open(f32, (i32, i32));
impl Eq for Open {} impl Eq for Open {}
@@ -171,6 +212,10 @@ pub(super) struct Route {
near: ((i32, i32), f64), near: ((i32, i32), f64),
expanded: usize, expanded: usize,
goal_checked: bool, goal_checked: bool,
truck: bool,
work_approach: bool,
work_wait: u32,
works: u8,
phase: Phase, phase: Phase,
pts: Vec<DVec3>, pts: Vec<DVec3>,
next: usize, next: usize,
@@ -206,6 +251,10 @@ impl Route {
near: ((0, 0), f64::MAX), near: ((0, 0), f64::MAX),
expanded: 0, expanded: 0,
goal_checked: slack > 0.0, goal_checked: slack > 0.0,
truck: kind == SamKind::Tzm && slack > 0.0,
work_approach: false,
work_wait: 0,
works: 0,
phase: Phase::Search, phase: Phase::Search,
pts: Vec::new(), pts: Vec::new(),
next: 0, next: 0,
@@ -231,7 +280,12 @@ impl Route {
horizontal(self.centre(c) - self.dest).length() horizontal(self.centre(c) - self.dest).length()
} }
fn is_goal(&self, c: (i32, i32)) -> bool { fn is_goal(&self, c: (i32, i32)) -> bool {
if self.slack > 0.0 { self.to_goal(c) <= self.slack } else { c == self.cell_of(self.dest) } if self.slack == 0.0 {
return c == self.cell_of(self.dest);
}
let Some(info) = self.cells.get(&c) else { return false };
let p = self.centre(c);
DVec3::new(p.x, f64::from(info.h), p.z).distance(self.dest) <= self.slack
} }
/// Searches afresh from `pos`, keeping the cells found bad. /// Searches afresh from `pos`, keeping the cells found bad.
@@ -242,6 +296,7 @@ impl Route {
self.lo = (self.start.0.min(goal.0) - margin, self.start.1.min(goal.1) - margin); self.lo = (self.start.0.min(goal.0) - margin, self.start.1.min(goal.1) - margin);
self.hi = (self.start.0.max(goal.0) + margin, self.start.1.max(goal.1) + margin); self.hi = (self.start.0.max(goal.0) + margin, self.start.1.max(goal.1) + margin);
self.g.clear(); self.g.clear();
self.cells.clear();
self.came.clear(); self.came.clear();
self.open.clear(); self.open.clear();
self.parked.clear(); self.parked.clear();
@@ -252,7 +307,9 @@ impl Route {
self.expanded = 0; self.expanded = 0;
self.near = (self.start, f64::MAX); self.near = (self.start, f64::MAX);
self.partial = false; self.partial = false;
self.cells.insert(self.start, Info { h: pos.y as f32, ok: true }); self.work_approach = false;
self.work_wait = 0;
self.cells.insert(self.start, Info { h: pos.y as f32 });
self.g.insert(self.start, 0.0); self.g.insert(self.start, 0.0);
let h = self.heur(self.start); let h = self.heur(self.start);
self.open.push(Open(h, self.start)); self.open.push(Open(h, self.start));
@@ -262,71 +319,60 @@ impl Route {
(self.to_goal(c) * 1.1) as f32 (self.to_goal(c) * 1.1) as f32
} }
fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32)) -> Eval { fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32), near: f64, climb: f64) -> Eval {
if let Some(i) = self.cells.get(&c) { if let Some(i) = self.cells.get(&c) {
return if i.ok { Eval::Ok(i.h) } else { Eval::Bad }; return Eval::Ok(i.h);
} }
if self.bad.contains(&c) { if self.bad.contains(&c) {
return Eval::Bad; return Eval::Bad;
} }
let p = self.centre(c); let verdict = self.road_at(ground, self.centre(c).with_y(near), climb, climb.max(STEP_DOWN), now);
let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); if let Eval::Ok(h) = verdict {
let verdict = match ground.column(x, z, 1024) { self.cells.insert(c, Info { h });
None => return Eval::Pending,
Some(None) => Info { h: 0.0, ok: false },
Some(Some(h)) => {
// The height is the top of what blocks motion or holds a fluid: water has nothing solid under it.
let top = DVec3::new(f64::from(x) + 0.5, h, f64::from(z) + 0.5);
match ground.world.sweep(top + DVec3::Y * 0.5, top - DVec3::Y * 0.5, false, now) {
world::Sweep::Hit { .. } => Info { h: h as f32, ok: true },
world::Sweep::Clear => Info { h: h as f32, ok: false },
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Eval::Pending,
world::Sweep::Unknown { .. } => Info { h: h as f32, ok: false },
}
}
};
if verdict.ok {
match self.clearance_at(ground, DVec3::new(f64::from(x) + 0.5, f64::from(verdict.h), f64::from(z) + 0.5), now) {
Clearance::Clear => {}
Clearance::Blocked => {
let blocked = Info { h: verdict.h, ok: false };
self.cells.insert(c, blocked);
return Eval::Bad;
}
Clearance::Pending => return Eval::Pending,
}
} }
self.cells.insert(c, verdict); verdict
if verdict.ok { Eval::Ok(verdict.h) } else { Eval::Bad }
} }
/// Check a chassis-sized footprint against sampled support columns and voxel headroom. /// Check support and headroom for the complete folded chassis. Unknown or just changed voxels
/// Unknown columns or sections are pending so neither search nor motion assumes they are open. /// remain pending so neither search nor motion assumes they are open.
fn clearance_at(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance { fn road_at(&self, ground: &mut Ground, pos: DVec3, climb: f64, drop: f64, now: u64) -> Eval {
let base = pos.y; let (cx, cz) = (pos.x.floor() as i32, pos.z.floor() as i32);
let base = match support(ground, cx, cz, pos.y, climb, drop, now) {
Eval::Ok(h) => f64::from(h),
other => return other,
};
let up = if self.truck { 2.0 } else { STEP_UP };
let mut pending = false; let mut pending = false;
for (dx, dz) in self.chassis.samples() { for (x, z) in self.chassis.samples(pos) {
let x = pos.x.floor() as i32 + dx; let h = if x == cx && z == cz {
let z = pos.z.floor() as i32 + dz; base
let Some(column) = ground.column(x, z, 1024) else { pending = true; continue }; } else {
let Some(h) = column else { return Clearance::Blocked }; match support(ground, x, z, base, up, STEP_DOWN, now) {
let dh = h - base; Eval::Ok(h) => f64::from(h),
if dh > STEP_UP || dh < -STEP_DOWN { Eval::Pending => { pending = true; continue; }
return Clearance::Blocked; Eval::Bad => return Eval::Bad,
} }
let top = DVec3::new(f64::from(x) + 0.5, h + 0.05, f64::from(z) + 0.5); };
match ground.world.sweep(top, top + DVec3::Y * self.chassis.height, false, now) { let mut section = None;
world::Sweep::Clear => {} let top = h.max(base);
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => pending = true, for y in top as i32..(top + self.chassis.height).ceil() as i32 {
world::Sweep::Unknown { .. } | world::Sweep::Hit { .. } => return Clearance::Blocked, match ground.world.road_block(&mut section, x, y, z, now) {
Some(Some(false)) => {}
None => { pending = true; break; }
Some(_) => return Eval::Bad,
}
} }
} }
if pending { Clearance::Pending } else { Clearance::Clear } if pending { Eval::Pending } else { Eval::Ok(base as f32) }
} }
/// Recheck the envelope at the live position, since obstacles may change after planning. /// Recheck the envelope at the live position, since obstacles may change after planning.
pub(super) fn clearance(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance { pub(super) fn clearance(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance {
self.clearance_at(ground, pos, now) match self.road_at(ground, pos, STEP_UP, STEP_DOWN, now) {
Eval::Ok(h) => Clearance::Clear(f64::from(h)),
Eval::Bad => Clearance::Blocked,
Eval::Pending => Clearance::Pending,
}
} }
/// Relaxes the edge from the opened cell `c` to `nb`; parks it when the land between isn't known yet. /// Relaxes the edge from the opened cell `c` to `nb`; parks it when the land between isn't known yet.
@@ -337,8 +383,10 @@ impl Route {
let (di, dj) = (nb.0 - c.0, nb.1 - c.1); let (di, dj) = (nb.0 - c.0, nb.1 - c.1);
let len = if di != 0 && dj != 0 { std::f64::consts::SQRT_2 } else { 1.0 }; let len = if di != 0 && dj != 0 { std::f64::consts::SQRT_2 } else { 1.0 };
let dist = len * f64::from(self.cell); let dist = len * f64::from(self.cell);
let slope = self.slope;
let allow = |l: f64| (slope * l).max(STEP_UP);
let Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return }; let Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return };
let h1 = match self.eval(ground, now, nb) { let h1 = match self.eval(ground, now, nb, h0, allow(dist)) {
Eval::Ok(h) => f64::from(h), Eval::Ok(h) => f64::from(h),
Eval::Bad => return, Eval::Bad => return,
Eval::Pending => return self.park(c, nb), Eval::Pending => return self.park(c, nb),
@@ -346,7 +394,7 @@ impl Route {
// A diagonal doesn't cut a corner of something in the way. // A diagonal doesn't cut a corner of something in the way.
if di != 0 && dj != 0 { if di != 0 && dj != 0 {
for side in [(c.0 + di, c.1), (c.0, c.1 + dj)] { for side in [(c.0 + di, c.1), (c.0, c.1 + dj)] {
match self.eval(ground, now, side) { match self.eval(ground, now, side, h0, allow(f64::from(self.cell))) {
Eval::Ok(h) if (f64::from(h) - h0).abs() <= (self.slope * f64::from(self.cell)).max(STEP_UP) => {} Eval::Ok(h) if (f64::from(h) - h0).abs() <= (self.slope * f64::from(self.cell)).max(STEP_UP) => {}
Eval::Pending => return self.park(c, nb), Eval::Pending => return self.park(c, nb),
_ => return, _ => return,
@@ -356,13 +404,12 @@ impl Route {
// Between the centres: a wall one block thick or a ditch there is what the centres don't show. // Between the centres: a wall one block thick or a ditch there is what the centres don't show.
let (a, b) = (self.centre(c), self.centre(nb)); let (a, b) = (self.centre(c), self.centre(nb));
let mid = (a + b) * 0.5; let mid = (a + b) * 0.5;
let hm = match ground.column(mid.x.floor() as i32, mid.z.floor() as i32, 1024) {
None => return self.park(c, nb),
Some(None) => return,
Some(Some(h)) => h,
};
let half = dist * 0.5; let half = dist * 0.5;
let allow = |l: f64| (self.slope * l).max(STEP_UP); let hm = match self.road_at(ground, mid.with_y(h0), allow(half), STEP_DOWN, now) {
Eval::Pending => return self.park(c, nb),
Eval::Bad => return,
Eval::Ok(h) => f64::from(h),
};
if (hm - h0).abs() > allow(half) || (h1 - hm).abs() > allow(half) || hm - h0 < -STEP_DOWN * (half / 2.0).max(1.0) { if (hm - h0).abs() > allow(half) || (h1 - hm).abs() > allow(half) || hm - h0 < -STEP_DOWN * (half / 2.0).max(1.0) {
return; return;
} }
@@ -388,7 +435,15 @@ impl Route {
/// Works on the search: at most `budget` cells. /// Works on the search: at most `budget` cells.
fn search(&mut self, ground: &mut Ground, now: u64, mut budget: usize) { fn search(&mut self, ground: &mut Ground, now: u64, mut budget: usize) {
if !self.goal_checked { if !self.goal_checked {
match self.eval(ground, now, self.cell_of(self.dest)) { let x = self.dest.x.floor() as i32;
let z = self.dest.z.floor() as i32;
let goal = match ground.column(x, z, 1024) {
// Orders made while flying above an exposed road still mean the ground below.
Some(Some(top)) => self.road_at(ground, self.dest.with_y(self.dest.y.min(top)), STEP_UP, STEP_DOWN, now),
Some(None) => Eval::Bad,
None => Eval::Pending,
};
match goal {
Eval::Bad => { Eval::Bad => {
self.failed = Some(Why::Goal); self.failed = Some(Why::Goal);
return; return;
@@ -442,8 +497,7 @@ impl Route {
} }
if self.open.is_empty() { if self.open.is_empty() {
if self.parked.is_empty() { if self.parked.is_empty() {
let goal = self.cell_of(self.dest); self.failed = Some(Why::NoWay);
self.failed = Some(if self.slack == 0.0 && !self.cells.get(&goal).is_none_or(|i| i.ok) { Why::Goal } else { Why::NoWay });
} else { } else {
let since = *self.stuck_since.get_or_insert(now); let since = *self.stuck_since.get_or_insert(now);
if now.saturating_sub(since) > WAIT_MAP { if now.saturating_sub(since) > WAIT_MAP {
@@ -503,13 +557,11 @@ impl Route {
let c = self.cell_of(at); let c = self.cell_of(at);
if c != self.cell_of(pos) { if c != self.cell_of(pos) {
self.bad.insert(c); self.bad.insert(c);
self.cells.insert(c, Info { h: 0.0, ok: false });
} else { } else {
// In the cell itself: the stretch ahead, one cell on. // In the cell itself: the stretch ahead, one cell on.
let d = horizontal(at - pos).normalize_or(DVec3::X) * f64::from(self.cell); let d = horizontal(at - pos).normalize_or(DVec3::X) * f64::from(self.cell);
let c = self.cell_of(pos + d); let c = self.cell_of(pos + d);
self.bad.insert(c); self.bad.insert(c);
self.cells.insert(c, Info { h: 0.0, ok: false });
} }
self.replans += 1; self.replans += 1;
if self.replans > REPLANS { if self.replans > REPLANS {
@@ -542,13 +594,117 @@ impl Route {
if self.phase == Phase::Search { if self.phase == Phase::Search {
return Drive::Wait(Why::Map); return Drive::Wait(Why::Map);
} }
let reach = f64::from(self.cell) * 0.7; let reach = if self.truck { 0.65 } else { f64::from(self.cell) * 0.7 };
while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach { while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach {
self.next += 1; self.next += 1;
} }
Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len()) Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len())
} }
/// Let an automatic delivery approach the nearest reachable spot before trying local roadwork.
pub(super) fn approach_works(&mut self) -> bool {
if !self.truck || self.works >= 2 || self.near.0 == self.start
|| self.to_goal(self.start) - self.near.1 < f64::from(self.cell)
{
return false;
}
self.failed = None;
self.finish(self.near.0, true);
self.work_approach = true;
true
}
pub(super) fn work_approach(&self) -> bool {
self.work_approach
}
/// Make a short local crossing only after route search or motion finds a blockage.
/// Returns true while waiting for terrain data or after requesting the edits.
pub(super) fn try_works(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool {
if !self.truck || self.works >= 2 || self.work_wait >= 60 {
return false;
}
self.work_wait += 1;
let direction = horizontal(self.dest - pos);
let (dx, dz) = if direction.x.abs() >= direction.z.abs() {
(if direction.x >= 0.0 { 1 } else { -1 }, 0)
} else {
(0, if direction.z >= 0.0 { 1 } else { -1 })
};
let coord = |row: i32, side: i32| (
pos.x.floor() as i32 + dx * row + dz * side,
pos.z.floor() as i32 + dz * row + dx * side,
);
let width = self.chassis.radius.ceil() as i32;
let start = pos.y.round() as i32;
let (ex, ez) = coord(10, 0);
let Some(Some(end)) = ground.column(ex, ez, 1024) else {
ground.want_chunk((ex >> 4, ez >> 4));
return true;
};
let end = end.round() as i32;
if (end - start).abs() > 2 || !(-63..=320).contains(&start) || !(-63..=320).contains(&end) {
return false;
}
let mut commands = Vec::new();
for row in 1..=10 {
let level = start + ((end - start) as f64 * f64::from(row) / 10.0).round() as i32;
let mut deck = false;
for side in -width..=width {
let (x, z) = coord(row, side);
let Some(Some(top)) = ground.column(x, z, 1024) else {
ground.want_chunk((x >> 4, z >> 4));
return true;
};
let top = top.round() as i32;
if top > level + 2 {
return false;
}
let p = DVec3::new(f64::from(x) + 0.5, f64::from(level), f64::from(z) + 0.5);
match ground.world.sweep(p + DVec3::Y * 0.25, p - DVec3::Y * 0.25, false, now) {
world::Sweep::Hit { .. } if top >= level => {}
world::Sweep::Hit { .. } | world::Sweep::Clear => deck = true,
_ => return true,
}
if top > level {
// Only shallow natural cover is cleared. Vanilla fills preserve other materials.
for block in ["short_grass", "fern", "snow", "dirt", "grass_block", "sand", "gravel"] {
commands.push(format!("fill {x} {level} {z} {x} {} {z} minecraft:air replace minecraft:{block}", top - 1));
}
}
}
if deck {
let (ax, az) = coord(row, -width);
let (bx, bz) = coord(row, width);
let y = level - 1;
for block in ["air", "water"] {
commands.push(format!("fill {ax} {y} {az} {bx} {y} {bz} minecraft:cobblestone replace minecraft:{block}"));
}
}
}
if commands.is_empty() || out.commands.len() + commands.len() > 192 {
return false;
}
out.commands.extend(commands);
let centre = pos + DVec3::new(f64::from(dx * 5), 0.0, f64::from(dz * 5));
ground.forget(centre, 9);
let (cx, cz) = (centre.x.floor() as i32, centre.z.floor() as i32);
let mut chunks = Vec::new();
for x in (cx - 9).div_euclid(16)..=(cx + 9).div_euclid(16) {
for z in (cz - 9).div_euclid(16)..=(cz + 9).div_euclid(16) {
chunks.push((x, z));
}
}
ground.world.columns_changed(&chunks);
self.works += 1;
self.replans = 0;
self.failed = None;
self.bad.clear();
self.cells.clear();
self.restart(pos);
true
}
pub(super) fn searching(&self) -> bool { pub(super) fn searching(&self) -> bool {
self.phase == Phase::Search && self.failed.is_none() self.phase == Phase::Search && self.failed.is_none()
} }
@@ -563,6 +719,23 @@ pub(super) struct Routes {
} }
impl Routes { impl Routes {
/// What the routes and their searches hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes};
let cell = std::mem::size_of::<(i32, i32)>();
let mut n = map_bytes(self.map.len(), std::mem::size_of::<u32>() + std::mem::size_of::<Route>())
+ map_bytes(self.unreachable.len(), std::mem::size_of::<(u32, u32)>() + std::mem::size_of::<u64>());
for r in self.map.values() {
n += map_bytes(r.cells.len(), cell + std::mem::size_of::<Info>())
+ map_bytes(r.bad.len(), cell)
+ map_bytes(r.g.len(), cell + std::mem::size_of::<f32>())
+ map_bytes(r.came.len(), 2 * cell)
+ r.open.capacity() * std::mem::size_of::<Open>()
+ vec_bytes(&r.parked)
+ vec_bytes(&r.pts);
}
n
}
pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool { pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool {
self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now) self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now)
} }
@@ -593,7 +766,7 @@ mod tests {
#[test] #[test]
fn footprint_checks_voxels_grazed_between_their_centres() { fn footprint_checks_voxels_grazed_between_their_centres() {
let cells = Chassis { radius: 2.75, height: 3.0 }.samples(); let cells: Vec<_> = Chassis { radius: 2.75, height: 3.0 }.samples(DVec3::new(0.5, 64.0, 0.5)).collect();
assert!(cells.contains(&(3, 1)), "the body reaches the near corner of this voxel"); assert!(cells.contains(&(3, 1)), "the body reaches the near corner of this voxel");
assert!(cells.contains(&(-3, -1))); assert!(cells.contains(&(-3, -1)));
assert!(!cells.contains(&(3, 3))); assert!(!cells.contains(&(3, 3)));
@@ -617,7 +790,129 @@ mod tests {
ground.world.serve(src, sections, now); ground.world.serve(src, sections, now);
} }
/// Drives a Patriot from the origin to `to` over land of the given heights (water: a height over a lower floor). #[derive(Default)]
struct Overhang {
lowered: bool,
}
impl Overhang {
fn spans(x: i32, z: i32) -> bool {
(16..32).contains(&x) && (-120..120).contains(&z)
}
fn answer(&self, ground: &mut Ground, tick: u64) {
let columns = ground.take_wanted().into_iter().map(|(x, z)| {
(x, z, if Self::spans(x, z) { 73 } else { 64 })
}).collect();
ground.answer(columns, tick);
let sections = ground.world.take_wanted(tick);
ground.world.serve(self, sections, tick);
}
}
impl world::WorldSource for Overhang {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
Some(y < 64 || Self::spans(x, z) && (y == 72 || self.lowered && y == 65))
}
}
fn march_under_overhang(lower_after_planning: bool) -> (Sim, bool, bool) {
let mut src = Overhang::default();
let mut sim = Sim::new(3);
let mut ground = Ground::default();
let mut out = Out::default();
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.5, 64.0, 0.5), 0.0));
assert!(sim.order_move(0, DVec3::new(60.5, 64.0, 0.5)));
let mut crossed = false;
let mut replanned = false;
for _ in 0..4000 {
sim.tick += 1;
src.answer(&mut ground, sim.tick);
sim.step_moves(&mut ground, &mut out);
let unit = &sim.sams[0];
if lower_after_planning && !src.lowered && unit.pos.x > 5.0 {
assert!(sim.routes.map.get(&id).is_some_and(|route| route.phase == Phase::Follow));
src.lowered = true;
// A new block under the deck changes the navigable road without changing the heightmap.
let changed: Vec<_> = (-8..8).map(|z| (1, 4, z)).collect();
ground.world.changed(1, false, &changed);
}
if src.lowered {
replanned |= sim.routes.map.get(&id).is_some_and(|route| route.replans > 0);
assert!(unit.pos.x + Chassis::for_kind(unit.kind).radius <= 16.0, "entered the changed ceiling at {:?}", unit.pos);
}
if Overhang::spans(unit.pos.x.floor() as i32, unit.pos.z.floor() as i32) {
assert_eq!(unit.pos.y, 64.0);
crossed = true;
}
if !unit.moving() {
break;
}
}
(sim, crossed, replanned)
}
#[test]
fn a_vehicle_can_follow_the_lower_road_under_a_bridge_deck() {
let (sim, crossed, _) = march_under_overhang(false);
let unit = &sim.sams[0];
assert!(crossed && !unit.moving() && unit.pos.x > 59.0, "ended at {:?}", unit.pos);
}
#[test]
fn a_new_low_ceiling_on_a_planned_road_stops_the_vehicle_and_replans() {
let (sim, crossed, replanned) = march_under_overhang(true);
assert!(replanned && !crossed && !sim.sams[0].moving(), "ended at {:?}", sim.sams[0].pos);
}
#[test]
fn a_supply_truck_builds_a_bridge_then_crosses_it() {
struct Creek(HashSet<(i32, i32)>);
impl world::WorldSource for Creek {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
let floor = if (16..20).contains(&x) && !self.0.contains(&(x, z)) { 60 } else { 64 };
Some(y < floor)
}
}
let mut creek = Creek(HashSet::new());
let mut sim = Sim::new(5);
let from = DVec3::new(0.5, 64.0, 0.5);
let to = DVec3::new(80.5, 64.0, 0.5);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Tzm, from, 0.0));
sim.sams[0].job = Some(999);
assert!(sim.order_move_near(0, to, HANDOVER - 0.75));
let mut ground = Ground::default();
let mut out = Out::default();
for _ in 0..2000 {
sim.tick += 1;
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
ground.answer(columns, sim.tick);
let sections = ground.world.take_wanted(sim.tick);
ground.world.serve(&creek, sections, sim.tick);
sim.step_moves(&mut ground, &mut out);
for command in out.commands.drain(..) {
let words: Vec<&str> = command.split_whitespace().collect();
if words[7] == "minecraft:cobblestone" && words[9] == "minecraft:water" {
let [ax, ay, az, bx, by, bz] = std::array::from_fn(|i| words[i + 1].parse::<i32>().unwrap());
assert_eq!((ay, by), (63, 63));
for x in ax.min(bx)..=ax.max(bx) {
for z in az.min(bz)..=az.max(bz) {
if (16..20).contains(&x) { creek.0.insert((x, z)); }
}
}
}
}
if !sim.sams[0].moving() { break; }
}
assert!(!creek.0.is_empty(), "the truck built no bridge");
assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "{:?} {:?}", sim.sams[0].pos, out.messages);
assert!(out.messages.is_empty(), "{:?}", out.messages);
}
/// Drives a Patriot from the origin to `to` over land of the given heights.
fn march_kind<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(kind: SamKind, height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) { fn march_kind<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(kind: SamKind, height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) {
let src = Src { height, floor }; let src = Src { height, floor };
let mut sim = Sim::new(3); let mut sim = Sim::new(3);
@@ -695,6 +990,13 @@ mod tests {
assert!(!s.moving() && s.pos.distance(DVec3::new(100.0, 64.0, 30.5)) < 3.0, "pos={:?} state={:?} messages={:?} route={route:?}", s.pos, s.state, out.messages); assert!(!s.moving() && s.pos.distance(DVec3::new(100.0, 64.0, 30.5)) < 3.0, "pos={:?} state={:?} messages={:?} route={route:?}", s.pos, s.state, out.messages);
} }
#[test]
fn an_order_from_above_an_open_road_still_reaches_the_ground() {
let (sim, _, _) = march(|_, _| 64, |_, _| 64, DVec3::new(30.5, 110.0, 0.5), 1500);
let unit = &sim.sams[0];
assert!(!unit.moving() && unit.pos.distance(DVec3::new(30.5, 64.0, 0.5)) < 1.0, "ended at {:?}", unit.pos);
}
// A point-column route fits through this one-block slit, but the S-400 chassis does not. // A point-column route fits through this one-block slit, but the S-400 chassis does not.
#[test] #[test]
fn s400_rejects_a_one_block_corridor() { fn s400_rejects_a_one_block_corridor() {
+92 -3
View File
@@ -496,7 +496,7 @@ fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" { if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick)); stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
} }
stats.max_channels = stats.max_channels.max(sam.own_channels_used()); stats.max_channels = stats.max_channels.max(sam.own_channels_used(sim.tick));
} }
} }
(stats, sim, radars, ids) (stats, sim, radars, ids)
@@ -599,6 +599,41 @@ fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch"); assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
} }
#[test]
fn a_network_plot_cues_a_separate_fire_radar_but_not_the_embedded_one() {
// #145: a fire-quality radar is cued to look at a network contact, but the weapon's own
// embedded radar is not — cueing every relayed contact each tick flooded the embedded fire
// control with one-tick plots and degraded the intercepts. The embedded radar keeps its
// beam/revisit/lock acquisition; a separate engagement radar still takes the cue.
let mut sim = Sim::new(145);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let embedded = {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0));
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
let id = sim.drones[0].id;
let at = sim.drones[0].pos;
let away = DVec3::new(-600.0, 120.0, 0.0);
let mut ground = Ground::default();
for tick in 1..=8 {
sim.tick = tick;
// The search radar measures the contact; the embedded and engagement radars look away,
// so only a cue (not the beam, a revisit or a lock) could give them an own plot.
sim.sams[search].beam = bearing(sim.sams[search].pos, at);
sim.sams[embedded].beam = bearing(sim.sams[embedded].pos, away);
sim.sams[engagement].beam = bearing(sim.sams[engagement].pos, away);
sim.update_sight(&mut ground);
}
let emb = sim.sams[embedded].track(id).expect("the embedded radar holds the network track");
assert_eq!(emb.own_tick, 0, "the embedded radar cue-measured a relayed contact (#145)");
assert!(!emb.own_authorizes(sim.tick), "a relayed plot gave the embedded radar fire authority");
let eng = sim.sams[engagement].track(id).expect("the engagement radar holds the track");
assert!(eng.own_tick > 0, "a separate fire-quality radar was not cued by the network plot");
}
#[test] #[test]
fn the_air_picture_prefers_the_better_plot_at_one_tick() { fn the_air_picture_prefers_the_better_plot_at_one_tick() {
let mut sim = Sim::new(1345); let mut sim = Sim::new(1345);
@@ -633,11 +668,65 @@ fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect(); let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count(); let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}"); assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(), 2); assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}"); assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick))); assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
} }
// #140: a network heartbeat keeps an old contact's track fresh, but never holds the station's
// channel: two stale own fire plots free the channels for a new contact, and the survey tracks
// of the old ones stay on the picture — with the search radar left running.
#[test]
fn stale_own_plots_free_their_channels_while_the_network_keeps_the_tracks() {
let mut sim = Sim::new(140);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
let search = radar_with_role(&mut sim, RadarRole::Search, 1550.0);
for x in [100.0, 140.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let old: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
let mut ground = Ground::default();
let radars = [engagement, search];
for tick in 1..=40 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let frozen: Vec<u64> = old
.iter()
.map(|&id| {
let t = sim.sams[engagement].track(id).expect("the station took the contact");
assert_ne!(t.own_product, Measure::Search, "the station took no channel: {t:?}");
t.own_tick
})
.collect();
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
// The two contacts leave the station's reach for the search radar beside them; the new one
// arrives close to the station. Only the network keeps the old tracks alive now.
for (k, d) in sim.drones.iter_mut().enumerate() {
d.pos = DVec3::new(1600.0 + 20.0 * k as f64, 120.0, 0.0);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 120.0, 0.0), DVec3::Z, DVec3::new(180.0, 120.0, 0.0));
let fresh = sim.drones.last().unwrap().id;
for tick in 41..=750 {
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let now = sim.tick;
let station = &sim.sams[engagement];
assert_eq!(station.own_channels_used(now), 1, "the stale channels still hold: {:?}", station.tracks);
for (&id, &own_tick) in old.iter().zip(&frozen) {
let t = station.track(id).expect("the survey track was thrown away with its channel");
assert_eq!(t.own_tick, own_tick, "the network renewed the station's own plot");
assert!(t.tick > 500, "the network stopped relaying the old contact: {t:?}");
assert_eq!(t.product, Measure::Search, "the relayed survey plot is gone: {t:?}");
assert!(!t.holds_channel(now, station.track_ttl() as u64), "an old own plot still holds a channel: {t:?}");
assert!(!t.own_authorizes(now));
}
let new = station.track(fresh).expect("the new contact is not held");
assert_eq!(new.own_product, Measure::Fire, "the new contact never got a channel: {new:?}");
assert!(new.own_authorizes(now), "the new contact's own fire plot does not authorize: {new:?}");
}
#[test] #[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() { fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342); let mut sim = Sim::new(1342);
@@ -751,7 +840,7 @@ fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
stats.high_marked |= t.id == ids[1]; stats.high_marked |= t.id == ids[1];
} }
if profile.id == "radar_track" { if profile.id == "radar_track" {
stats.track_channels = stats.track_channels.max(sam.own_channels_used()); stats.track_channels = stats.track_channels.max(sam.own_channels_used(sim.tick));
} }
if profile.id == "radar_search" || profile.id == "radar_height" { if profile.id == "radar_search" || profile.id == "radar_height" {
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick)); stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
+111 -30
View File
@@ -22,6 +22,8 @@ use super::*;
/// Rays round a radar, and blocks between the land's samples along them. /// Rays round a radar, and blocks between the land's samples along them.
const RAYS: usize = 48; const RAYS: usize = 48;
const STEP: f64 = 16.0; const STEP: f64 = 16.0;
/// The longest profiles use wider intervals to retain the same height-cache footprint.
const MAX_RAY_STEPS: f64 = 160.0;
/// How far units share their tracks (the network's data links). /// How far units share their tracks (the network's data links).
pub(super) const LINK: f64 = 2250.0; pub(super) const LINK: f64 = 2250.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`. /// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
@@ -33,8 +35,8 @@ pub const FIRE_QUALITY: u8 = 50;
pub(super) const GUN_PICK_AGE: u64 = 40; pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast. /// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20; pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks. /// The game's radio horizon: `HORIZON * (√mast + √height)` blocks.
pub(super) const HORIZON: f64 = 35.0; pub(super) const HORIZON: f64 = 95.0;
/// Anything this near is seen (and heard), whatever hides it. /// Anything this near is seen (and heard), whatever hides it.
pub(super) const NEAR: f64 = 24.0; pub(super) const NEAR: f64 = 24.0;
@@ -43,11 +45,13 @@ pub(super) struct Horizon {
pub(super) rays: Vec<Vec<f32>>, pub(super) rays: Vec<Vec<f32>>,
antenna: DVec3, antenna: DVec3,
reach: f64, reach: f64,
step: f64,
} }
impl Horizon { impl Horizon {
fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self { fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self {
let steps = (reach / STEP).ceil() as usize + 1; let step = STEP.max(reach / MAX_RAY_STEPS);
let steps = (reach / step).ceil() as usize + 1;
let rays = (0..RAYS) let rays = (0..RAYS)
.map(|r| { .map(|r| {
let a = r as f64 / RAYS as f64 * TAU; let a = r as f64 / RAYS as f64 * TAU;
@@ -55,7 +59,7 @@ impl Horizon {
let mut top = f32::NEG_INFINITY; let mut top = f32::NEG_INFINITY;
(1..=steps) (1..=steps)
.map(|k| { .map(|k| {
let d = k as f64 * STEP; let d = k as f64 * step;
// Unknown land (not loaded, not answered yet) hides nothing. // Unknown land (not loaded, not answered yet) hides nothing.
if let Some(g) = ground.at(antenna + dir * d, now) { if let Some(g) = ground.at(antenna + dir * d, now) {
top = top.max(((g - antenna.y) / d) as f32); top = top.max(((g - antenna.y) / d) as f32);
@@ -65,7 +69,7 @@ impl Horizon {
.collect() .collect()
}) })
.collect(); .collect();
Self { rays, antenna, reach } Self { rays, antenna, reach, step }
} }
fn matches(&self, sam: &Sam) -> bool { fn matches(&self, sam: &Sam) -> bool {
@@ -75,7 +79,7 @@ impl Horizon {
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool { pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna; let rel = p - antenna;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt(); let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
let k = (flat / STEP) as usize; let k = (flat / self.step) as usize;
if k == 0 { if k == 0 {
return false; return false;
} }
@@ -322,6 +326,15 @@ impl Track {
pub fn own_authorizes(&self, now: u64) -> bool { pub fn own_authorizes(&self, now: u64) -> bool {
self.own_fire_within(now, MISSILE_AGE) self.own_fire_within(now, MISSILE_AGE)
} }
/// The station's own refine/fire channel on this contact is still live: the plot is its own,
/// finer than a search, and no older than the station keeps a contact without a fresh
/// measurement. A relayed plot never holds a channel: the network's heartbeat keeps the
/// track fresh, not the station's own tracking (#140).
pub fn holds_channel(&self, now: u64, ttl: u64) -> bool {
self.own_tick > 0
&& self.own_product != battery::Measure::Search
&& now.saturating_sub(self.own_tick) <= ttl
}
/// Who measured the latest plot, as an ID (`0`: no station). /// Who measured the latest plot, as an ID (`0`: no station).
pub fn measured_by(&self) -> Option<u32> { pub fn measured_by(&self) -> Option<u32> {
(self.source != 0).then_some(self.source) (self.source != 0).then_some(self.source)
@@ -363,12 +376,23 @@ impl Sam {
pub fn radar_up(&self) -> bool { pub fn radar_up(&self) -> bool {
self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0 self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
} }
/// Its jammer is really on the air: the switch, a live station and a deployed one. The same
/// state `step_ew` transmits in, so a look names jamming only while the transmitter works.
pub fn ew_up(&self) -> bool {
self.ew_on && !self.ew_lock && self.alive() && !self.moving()
}
pub fn track(&self, id: u32) -> Option<&Track> { pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id) self.tracks.iter().find(|t| t.id == id)
} }
/// Refined/fire channels this station is currently using. /// Ticks a contact stays this station's own without a fresh measurement: three missed turns, at least 60.
pub fn own_channels_used(&self) -> usize { pub(super) fn track_ttl(&self) -> u32 {
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count() ((self.scan_ticks() * 3.0) as u32).max(60)
}
/// Refined/fire channels this station is currently using: the same test the planner applies,
/// so the panel and the allocation never disagree about a stale channel.
pub fn own_channels_used(&self, now: u64) -> usize {
let ttl = self.track_ttl() as u64;
self.tracks.iter().filter(|t| t.holds_channel(now, ttl)).count()
} }
} }
@@ -394,7 +418,8 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
(mine.own_tick, mine.own_product, mine.own_quality, mine.locked) (mine.own_tick, mine.own_product, mine.own_quality, mine.locked)
}; };
let hits = mine.hits.max(t.hits); let hits = mine.hits.max(t.hits);
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t }; let class = if t.class == ClassEst::Unknown { mine.class } else { t.class };
*mine = Track { own_tick, own_product, own_quality, hits, locked, class, ..t };
} }
} }
None => { None => {
@@ -404,6 +429,26 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
} }
} }
/// One local measurement used as a baseline for classifying speed. Fusing
/// positions from different sensors a tick apart can turn noise into speed.
#[derive(Clone, Copy)]
pub(super) struct ClassPlot {
pos: DVec3,
tick: u64,
sigma: f64,
networked: bool,
}
impl ClassPlot {
fn classify(self, next: Self, previous: ClassEst) -> Option<ClassEst> {
let elapsed = (next.tick - self.tick) as f64;
// Let the contact move a measurable distance before using another plot.
// Even a radar locked every tick has too much noise over one tick.
let min_ticks = (2.5 * (self.sigma + next.sigma)).max(6.0);
(elapsed >= min_ticks).then(|| previous.step(3, self.pos.distance(next.pos) / elapsed))
}
}
/// A plot's quality (0..100). It uses only the measured geometry and the /// A plot's quality (0..100). It uses only the measured geometry and the
/// station's own fit, never the target's hidden state. /// station's own fit, never the target's hidden state.
fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 { fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 {
@@ -449,13 +494,23 @@ impl Sim {
let heights: Vec<Option<f64>> = let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect(); self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect(); let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
if now % 80 == 0 {
self.breakthroughs.active.retain(|id, _| drone_at.contains_key(id));
}
let seed = self.seed; let seed = self.seed;
let mut index: HashMap<u32, usize> = HashMap::new(); let mut index: HashMap<u32, usize> = HashMap::new();
for sam in &mut self.sams { for sam in &mut self.sams {
// A track of a drone that is gone is dropped (the kill is seen), so is one not renewed for its time. // A track of a drone that is gone is dropped (the kill is seen), so is one not renewed for its time.
sam.tracks.retain(|t| now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive())); sam.tracks.retain(|t| {
let keep = now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive());
if !keep {
sam.class_plots.remove(&t.id);
}
keep
});
if !sam.alive() || sam.moving() { if !sam.alive() || sam.moving() {
sam.tracks.clear(); sam.tracks.clear();
sam.class_plots.clear();
continue; continue;
} }
if !sam.radar_up() { if !sam.radar_up() {
@@ -468,13 +523,14 @@ impl Sim {
let scan = sam.scan_profile(); let scan = sam.scan_profile();
let period = sam.scan_ticks(); let period = sam.scan_ticks();
let w = TAU / period; let w = TAU / period;
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60)); let (b0, ttl) = (sam.beam, sam.track_ttl());
sam.beam = (b0 + w) % TAU; sam.beam = (b0 + w) % TAU;
let at = antenna(sam); let at = antenna(sam);
let horizon = self.horizons.get(&sam.id); let horizon = self.horizons.get(&sam.id);
let local = spec.sensor * profile.local; let local = spec.sensor * profile.local;
// Channels already refining or holding fire plots. Search plots do not use one. // Channels already refining or holding fire plots, by the same test the UI shows:
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count(); // a stale own plot (the network may keep the track) no longer occupies one.
let mut used = sam.own_channels_used(now);
let mut fresh: Vec<Track> = Vec::new(); let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) { for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() { if !d.alive() {
@@ -490,9 +546,12 @@ impl Sim {
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round). // The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w); let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64); let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
// A network plot cues a fire-quality radar to look, but is never itself a // A network plot cues a *separate* fire-quality radar to look, but is never itself
// measurement: reach, terrain, probability and noise still apply. // a measurement: reach, terrain, probability and noise still apply. The weapon's
let cue = profile.allows(battery::Measure::Fire) // own embedded radar is not cued: measuring every relayed contact each tick flooded
// its fire control with one-tick plots whose noisy velocity degraded the intercepts
// (#145); it keeps its beam/revisit/lock acquisition, as before the profiles (#134).
let cue = sam.kind == SamKind::Radar && profile.allows(battery::Measure::Fire)
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE); && held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
if !(in_beam || locked || revisit || cue) { if !(in_beam || locked || revisit || cue) {
continue; continue;
@@ -506,8 +565,7 @@ impl Sim {
// and a full station does not silently refine the whole sky. A station already // and a full station does not silently refine the whole sky. A station already
// refining a contact keeps its channel; a new refinement needs a free one, and // refining a contact keeps its channel; a new refinement needs a free one, and
// without one the station still publishes its ordinary coarse search plot. // without one the station still publishes its ordinary coarse search plot.
let own_held = held.is_some_and(|t| t.own_tick > 0); let holds_channel = held.is_some_and(|t| t.holds_channel(now, ttl as u64));
let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
let mut product = if profile.allows(battery::Measure::Fire) { let mut product = if profile.allows(battery::Measure::Fire) {
battery::Measure::Fire battery::Measure::Fire
} else if profile.allows(battery::Measure::Refine) && held.is_some() { } else if profile.allows(battery::Measure::Refine) && held.is_some() {
@@ -536,6 +594,9 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p { if dist > NEAR && dice(seed, now, key, 0) >= p {
continue; continue;
} }
if let Some(facts) = self.breakthroughs.active.get_mut(&d.id) {
facts.first.get_or_insert((now, sam.id));
}
let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread }; let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma; let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
let measured = d.pos + noise; let measured = d.pos + noise;
@@ -544,17 +605,26 @@ impl Sim {
used += 1; used += 1;
} }
let hits = held.map_or(1, |t| t.hits.saturating_add(1)); let hits = held.map_or(1, |t| t.hits.saturating_add(1));
// What this measurement says of the contact's class and speed, from the measured let vel = match held {
// places alone: the first blip gives neither; a later one, the change of place over
// the ticks since the last real measurement (not a forecast's), smoothed into what
// the track held so the class does not flap on one noisy pair (#133).
let (vel, class) = match held {
Some(p) if p.tick < now => { Some(p) if p.tick < now => {
let seen = (measured - p.pos) / (now - p.tick) as f64; let seen = (measured - p.pos) / (now - p.tick) as f64;
let vel = if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) }; if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) }
(vel, p.class.step(hits, vel.length()))
} }
_ => (DVec3::ZERO, ClassEst::Unknown), _ => DVec3::ZERO,
};
let plot = ClassPlot { pos: measured, tick: now, sigma, networked: false };
let previous_class = held.map_or(ClassEst::Unknown, |t| t.class);
let baseline = sam.class_plots.entry(d.id).or_insert(plot);
baseline.networked |= held.is_some_and(|p| p.source != sam.id);
let class = if !baseline.networked {
// A station measuring independently retains the velocity
// estimate from its own successive observations.
previous_class.step(hits, vel.length())
} else if let Some(estimate) = baseline.classify(plot, previous_class) {
*baseline = ClassPlot { networked: true, ..plot };
estimate
} else {
previous_class
}; };
fresh.push(Track { fresh.push(Track {
id: d.id, id: d.id,
@@ -579,12 +649,12 @@ impl Sim {
} }
// The network: every unit gets the tracks the radars within data-link range measured themselves, // The network: every unit gets the tracks the radars within data-link range measured themselves,
// with the time they were measured: a relayed track is never fresher than its measurement. // with the time they were measured: a relayed track is never fresher than its measurement.
// Fictional passive observation: hostile aircraft within 1600 blocks fix an emitting radar // Fictional passive observation: hostile aircraft within 1600 blocks report an emitter's area
// every 20 ticks. Silence leaves the previous report to age normally. // every 20 ticks. Silence leaves the previous report to age normally.
if now % 20 == 0 { if now % 20 == 0 {
for s in self.sams.iter().filter(|s| s.radar_up()) { for s in self.sams.iter().filter(|s| s.radar_up()) {
if self.drones.iter().any(|d| d.alive() && d.pos.distance(s.pos) <= 1600.0) { if recon::has_signal_witness(&self.drones, s.pos) {
self.intel.observe(s, now, ew::Seen::Emission); self.recon.signal(s, now, recon::Source::Emission);
} }
} }
} }
@@ -781,6 +851,17 @@ mod low_view_tests {
mod relay_tests { mod relay_tests {
use super::*; use super::*;
#[test]
fn class_samples_ignore_noise_between_nearby_ticks() {
let sample = |tick, error| ClassPlot { pos: DVec3::X * (tick as f64 * 0.6 + error), tick, sigma: 8.0, networked: true };
let baseline = sample(10, -8.0);
assert_eq!(baseline.classify(sample(11, 8.0), ClassEst::Unknown), None);
let next = sample(50, 8.0);
let probable = baseline.classify(next, ClassEst::Unknown).unwrap();
assert_eq!(probable, ClassEst::Probable(Class::Drone));
assert_eq!(next.classify(sample(90, -8.0), probable), Some(ClassEst::Firm(Class::Drone)));
}
/// A relayed measurement: its class and hits arrive as they were, the receiver's own age is /// A relayed measurement: its class and hits arrive as they were, the receiver's own age is
/// kept, and passing the same message again adds nothing (#133). /// kept, and passing the same message again adds nothing (#133).
#[test] #[test]
+5
View File
@@ -184,6 +184,11 @@ pub(super) enum Slot {
} }
impl Sites { impl Sites {
/// What the sites hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.list) + vec_bytes(&self.jobs) + vec_bytes(&self.holding) + vec_bytes(&self.flying)
}
pub fn get(&self, id: u32) -> Option<&LaunchSite> { pub fn get(&self, id: u32) -> Option<&LaunchSite> {
self.list.iter().find(|s| s.id == id) self.list.iter().find(|s| s.id == id)
} }
+314
View File
@@ -0,0 +1,314 @@
//! Smart v2 (#149): the merged public picture, one knowledge version per order, the bounded
//! refresh of the unreleased portion, and the bearing window — and the metamorphic guarantee
//! that a hidden permutation nothing observed changes no decision.
use super::*;
use super::sites::testland::{Land, serve};
fn grid() -> raid::Grid {
raid::Grid { min: DVec3::new(-800.0, 0.0, -800.0), cell: 16.0, size: 100 }
}
fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon::Mark {
recon::Mark {
id,
area: at,
radius: recon::COARSE_AREA,
category,
role: None,
source: recon::Source::Flyby,
observed,
reported: observed,
quality: recon::Quality::Coarse,
looks: 1,
launches: 0,
last_launch: None,
}
}
fn contact(id: u32, kind: SamKind, at: DVec3, tick: u64) -> ew::Contact {
ew::Contact { id, kind, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }
}
fn order() -> RaidOrder {
RaidOrder { kinds: vec![(DroneKind::Shahed, 4), (DroneKind::Kh22, 2)], approach: Approach::Sector, dist: 900.0, aim: Aim::Smart }
}
// #149: the metamorphic guarantee. Two worlds with the same seed and the same observed radar,
// whose hidden forces are a permutation of one another (kinds swapped between places), order
// the same recon flight, the same aims and intents, and the same prices — nothing unobserved
// leaks into a decision.
#[test]
fn a_hidden_permutation_changes_nothing_before_observation() {
let object = DVec3::new(0.0, 70.0, 0.0);
let build = |perm: bool| {
let mut sim = Sim::new(149);
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0), DVec3::new(-50.0, 70.0, -300.0)];
let kinds = if perm { [SamKind::Pantsir, SamKind::S400, SamKind::Tor] } else { [SamKind::S400, SamKind::Tor, SamKind::Pantsir] };
for (k, p) in kinds.into_iter().zip(spots) {
let id = sim.id();
sim.sams.push(Sam::new(id, k, p, 0.0));
}
sim.targets.push(object);
sim.target_health.push(100.0);
let mut out = Out::default();
sim.order_raid(&order(), &[object], &mut out);
let flight: Vec<_> = sim.recon.sorties.iter().map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::<Vec<_>>()).collect();
let aims = sim.planned_aims();
let intents = sim.planned_intents();
let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101);
(flight, aims, intents, prices)
};
assert_eq!(build(false), build(true), "a hidden permutation changed the flight, the plan or the prices");
}
// #149: the same guarantee after a look. Once a radar is observed, permuting only the units
// nothing saw changes neither the structured picture nor the prices.
#[test]
fn a_hidden_permutation_changes_nothing_after_observation() {
let build = |perm: bool| {
let mut sim = Sim::new(149);
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(150.0, 70.0, -80.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
let spots = [DVec3::new(-200.0, 70.0, 100.0), DVec3::new(300.0, 70.0, 200.0)];
let kinds = if perm { [SamKind::S400, SamKind::Pantsir] } else { [SamKind::Pantsir, SamKind::S400] };
for (k, p) in kinds.into_iter().zip(spots) {
let id = sim.id();
sim.sams.push(Sam::new(id, k, p, 0.0));
}
sim.tick = 100;
let (prices, _) = sim.price_grid(&grid(), DroneKind::Kh101);
(sim.enemy_picture(), prices)
};
assert_eq!(build(false), build(true), "a hidden permutation moved the picture or the prices after a look");
}
// #149: price_grid_known accounts for marks. A fresh probable mark raises the cells its public
// category covers; a doubtful one prices nothing; a mark matched to a contact is priced once,
// exactly as the contact alone. The legacy mode prices contacts only.
#[test]
fn a_fresh_mark_prices_the_map_and_a_doubtful_one_does_not() {
let mut sim = Sim::new(149);
let g = grid();
let m = mark(recon::ID_BASE + 1, DVec3::new(0.0, 70.0, 0.0), recon::Category::Launcher, 0);
let fresh = ew::KnowledgeSnapshot::new(100, Vec::new(), vec![m]);
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh);
assert!(prices.iter().any(|p| *p > 1.0), "a fresh launcher mark priced nothing");
let old = ew::KnowledgeSnapshot::new(4000, Vec::new(), vec![m]);
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &old);
assert!(prices.iter().all(|p| *p == 1.0), "a doubtful mark was priced");
// Merged into a contact of the same public category: one hint, priced once.
let c = contact(16, SamKind::S400, m.area, 100);
let merged = ew::KnowledgeSnapshot::new(100, vec![c], vec![m]);
let only = ew::KnowledgeSnapshot::new(100, vec![c], Vec::new());
assert_eq!(
sim.price_grid_known(&g, DroneKind::Kh101, None, &merged).0,
sim.price_grid_known(&g, DroneKind::Kh101, None, &only).0,
"a matched mark was priced twice"
);
// The legacy mode does not price marks at all.
sim.smart_legacy = true;
let (prices, _) = sim.price_grid_known(&g, DroneKind::Kh101, None, &fresh);
assert!(prices.iter().all(|p| *p == 1.0), "the legacy mode priced a mark");
}
// #146/#149: one order prices every kind over the snapshot its targets were chosen from. A
// contact disclosed while the plan is still being worked out changes neither mode's routes:
// the #146 versioning is preserved for the candidate and the legacy picker alike.
#[test]
fn one_order_prices_every_kind_over_its_own_snapshot() {
let object = DVec3::new(0.0, 70.0, 300.0);
let build = |legacy: bool, disclose: bool| {
let mut sim = Sim::new(149);
sim.smart_legacy = legacy;
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::new(600.0, 70.0, -600.0), 0.0);
sim.intel.observe(&radar, 0, ew::Seen::Emission);
sim.sams.push(radar);
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let order = RaidOrder { kinds: vec![(DroneKind::Kh101, 6), (DroneKind::Shahed, 8)], approach: Approach::Sector, dist: 600.0, aim: Aim::Smart };
sim.order_raid(&order, &[object], &mut out);
if disclose {
// A jamming station gives itself away at the objective while the plan waits for its
// land: every satellite-nav kind prices it, so the live picture bends the routes.
let id = sim.id();
let threat = Sam::new(id, SamKind::Ew, object, 0.0);
sim.intel.observe(&threat, sim.tick, ew::Seen::Jamming);
sim.sams.push(threat);
}
// Work the plan alone (no adaptive ticks): the queue's routes are the plan's own.
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
sim.queue.iter().map(|(_, d)| (d.id, d.route.clone())).collect::<Vec<_>>()
};
assert_eq!(build(false, false), build(false, true), "the candidate mixed two knowledge versions in one order");
assert_eq!(build(true, false), build(true, true), "the legacy mode lost the #146 one-version pricing");
}
// #149: a report arriving while the raid's drones still wait re-aims the plan's own picks once,
// on a fresh snapshot, within the switch cap — and then the refresh is spent.
#[test]
fn a_report_refreshes_the_unreleased_portion_once() {
let object = DVec3::new(0.0, 70.0, 0.0);
let mut sim = Sim::new(149);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0));
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
sim.order_raid(&order(), &[object], &mut out);
// Force the first sortie's look so a report is pending, then finish the plan: the refresh
// moment is armed only because a report is actually on its way.
let s = sim.recon.sorties.first().expect("no recon sortie").clone();
let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft");
d.pos = s.zones[s.next].center + DVec3::Y * 40.0;
sim.tick += 1;
sim.step_recon(&mut out);
let report_at = sim.recon.sorties.first().unwrap().report_at.expect("no pending report");
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
assert!(sim.refresh.is_some(), "a pending report did not arm the bounded refresh");
// The report arrives: the mark is in the picture.
sim.tick = report_at;
sim.step_recon(&mut out);
assert!(sim.recon.reports > 0);
let m = *sim.recon.marks.values().next().expect("the report left no mark");
// One drone is past the switch cap: it keeps its aim.
sim.queue[0].1.aim.switches = ew::SWITCH_CAP;
let capped = sim.queue[0].1.id;
sim.step_refresh(&mut out);
assert!(sim.refresh.is_none(), "the refresh was not spent");
assert!(sim.refresh_applied > 0, "the report re-aimed nobody");
assert!(sim.queue.iter().any(|(_, d)| d.intent == ew::Intent::Refresh && d.aim.unit == m.id), "no drone was refreshed onto the mark");
assert!(sim.queue.iter().find(|(_, d)| d.id == capped).unwrap().1.intent != ew::Intent::Refresh, "a drone past the cap was refreshed");
// Spent: a second call changes nothing.
let applied = sim.refresh_applied;
sim.step_refresh(&mut out);
assert_eq!(sim.refresh_applied, applied);
}
// #149: no report never pauses the raid. Past the deadline the refresh is dropped and the
// launches keep the times the plan gave them.
#[test]
fn no_report_never_pauses_the_raid() {
let object = DVec3::new(0.0, 70.0, 0.0);
let mut sim = Sim::new(149);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0), 0.0));
sim.targets.push(object);
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
sim.order_raid(&order(), &[object], &mut out);
let s = sim.recon.sorties.first().expect("no recon sortie").clone();
let d = sim.drones.iter_mut().find(|d| d.id == s.drone).unwrap();
d.pos = s.zones[s.next].center + DVec3::Y * 40.0;
sim.tick += 1;
sim.step_recon(&mut out);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.tick += 1;
sim.plan_step(Some(&mut ground), &mut out);
}
let deadline = sim.refresh.as_ref().expect("the refresh was not armed").deadline;
let times: Vec<u64> = sim.queue.iter().map(|(t, _)| *t).collect();
// The report never arrives (the aircraft is lost); the deadline passes.
sim.drones.retain(|d| !recon::is_drone_id(d.id));
sim.tick = deadline + 1;
sim.step_refresh(&mut out);
assert!(sim.refresh.is_none(), "the refresh outlived its deadline");
assert_eq!(sim.refresh_applied, 0);
assert_eq!(sim.queue.iter().map(|(t, _)| *t).collect::<Vec<_>>(), times, "a missing report delayed a launch");
}
// #149: the bearing window forgets, and names why it explores. Few observations, a stale
// result and changed public conditions are distinct typed reasons; the legacy mode keeps its
// fixed share.
#[test]
fn the_bearing_window_forgets_and_names_its_reason() {
let mut sim = Sim::new(149);
sim.tick = 100;
for _ in 0..8 {
sim.learn(3, false);
}
sim.best_bearing();
let r = sim.bearing_report();
assert_eq!(r.reason, ew::BearingReason::Exploiting);
assert_eq!(r.observations, 8);
sim.tick = 100 + ew::OUTCOME_STALE + 1;
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::StaleResults);
sim.tick = 100 + ew::OUTCOME_WINDOW + 1;
sim.best_bearing();
let r = sim.bearing_report();
assert_eq!(r.reason, ew::BearingReason::FewObservations);
assert_eq!(r.observations, 0, "the window did not forget the old outcomes");
let mut sim = Sim::new(149);
sim.tick = 100;
for _ in 0..8 {
sim.learn(3, false);
}
let id = sim.id();
let radar = Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0);
sim.intel.observe(&radar, 100, ew::Seen::Emission);
sim.sams.push(radar);
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::ConditionsChanged);
sim.smart_legacy = true;
sim.best_bearing();
assert_eq!(sim.bearing_report().reason, ew::BearingReason::FixedShare);
}
// #149: the bearing window and a refresh intent are durable: a save writes them, a load reads
// them back, and an older save without the window loads with an empty one.
#[test]
fn the_bearing_window_and_a_refresh_intent_survive_a_save() {
let mut sim = Sim::new(149);
sim.tick = 500;
sim.learn(2, true);
sim.learn(5, false);
let mut d = sim.make_drone(DroneKind::Shahed, DVec3::new(-500.0, 120.0, 0.0), DVec3::X, DVec3::ZERO);
d.smart = true;
d.intent = ew::Intent::Refresh;
d.aim = ew::Aim::unit(recon::ID_BASE + 1, 500, Confidence::Confirmed);
sim.queue.push((600, d));
let text = sim.air_text().expect("the window and the queue are durable");
assert!(text.contains("airlearn"), "the bearing window was not written");
assert!(text.contains("refresh"), "the refresh intent was not written");
let mut back = Sim::new(1);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert_eq!(back.intel.outcomes().len(), 2);
assert_eq!(back.queue[0].1.intent, ew::Intent::Refresh);
assert_eq!(back.queue[0].1.aim.unit, recon::ID_BASE + 1);
}
+71 -3
View File
@@ -20,6 +20,36 @@ const HANDOVER: f64 = 10.0;
const TRUCK_LOAD: u32 = 2; const TRUCK_LOAD: u32 = 2;
const STOCK_LIMIT: u32 = 1000000; const STOCK_LIMIT: u32 = 1000000;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum DroneKind {
Shahed,
Geran3,
Lancet,
Gerbera,
Kh101,
Kalibr,
Kh22,
Zircon,
Iskander,
Kinzhal,
Oreshnik,
OreshnikBlock,
OreshnikSub,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum MissileKind {
Pac3,
M57e6,
M48n6,
M77n6,
IrisT,
Amraam,
M9m317,
M9m338,
P1sun,
}
const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec { const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec {
name: "Шахед-136", name: "Шахед-136",
key: "shahed", key: "shahed",
@@ -30,6 +60,7 @@ const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec {
clearance: 18.0, clearance: 18.0,
dive: 32.0, dive: 32.0,
warhead: 3, warhead: 3,
accuracy: (1.2, 0.03),
scale: 1.3, scale: 1.3,
engine: Engine::Prop(1.34, 1.0), engine: Engine::Prop(1.34, 1.0),
decoy: false, decoy: false,
@@ -51,6 +82,7 @@ const DRONE_SPEC_GERAN3: DroneSpec = DroneSpec {
clearance: 18.0, clearance: 18.0,
dive: 50.0, dive: 50.0,
warhead: 2, warhead: 2,
accuracy: (1.0, 0.03),
scale: 1.15, scale: 1.15,
engine: Engine::Jet(0.34, 1.55, 1.0), engine: Engine::Jet(0.34, 1.55, 1.0),
decoy: false, decoy: false,
@@ -72,6 +104,7 @@ const DRONE_SPEC_LANCET: DroneSpec = DroneSpec {
clearance: 10.0, clearance: 10.0,
dive: 38.0, dive: 38.0,
warhead: 1, warhead: 1,
accuracy: (0.8, 0.02),
scale: 0.9, scale: 0.9,
engine: Engine::Prop(0.93, 0.55), engine: Engine::Prop(0.93, 0.55),
decoy: false, decoy: false,
@@ -93,6 +126,7 @@ const DRONE_SPEC_GERBERA: DroneSpec = DroneSpec {
clearance: 15.0, clearance: 15.0,
dive: 30.0, dive: 30.0,
warhead: 0, warhead: 0,
accuracy: (1.5, 0.04),
scale: 1.1, scale: 1.1,
engine: Engine::Prop(1.03, 0.9), engine: Engine::Prop(1.03, 0.9),
decoy: true, decoy: true,
@@ -114,6 +148,7 @@ const DRONE_SPEC_KH101: DroneSpec = DroneSpec {
clearance: 12.0, clearance: 12.0,
dive: 26.0, dive: 26.0,
warhead: 6, warhead: 6,
accuracy: (1.3, 0.05),
scale: 1.6, scale: 1.6,
engine: Engine::Jet(-0.27, 1.4, 0.6), engine: Engine::Jet(-0.27, 1.4, 0.6),
decoy: false, decoy: false,
@@ -135,6 +170,7 @@ const DRONE_SPEC_KALIBR: DroneSpec = DroneSpec {
clearance: 15.0, clearance: 15.0,
dive: 26.0, dive: 26.0,
warhead: 5, warhead: 5,
accuracy: (1.3, 0.05),
scale: 1.5, scale: 1.5,
engine: Engine::Jet(-0.2, 1.5, 0.6), engine: Engine::Jet(-0.2, 1.5, 0.6),
decoy: false, decoy: false,
@@ -156,6 +192,7 @@ const DRONE_SPEC_KH22: DroneSpec = DroneSpec {
clearance: 40.0, clearance: 40.0,
dive: 150.0, dive: 150.0,
warhead: 7, warhead: 7,
accuracy: (1.6, 0.06),
scale: 1.8, scale: 1.8,
engine: Engine::Rocket(1.5, 1.3), engine: Engine::Rocket(1.5, 1.3),
decoy: false, decoy: false,
@@ -177,6 +214,7 @@ const DRONE_SPEC_ZIRCON: DroneSpec = DroneSpec {
clearance: 30.0, clearance: 30.0,
dive: 110.0, dive: 110.0,
warhead: 6, warhead: 6,
accuracy: (1.5, 0.06),
scale: 1.4, scale: 1.4,
engine: Engine::Rocket(1.5, 1.1), engine: Engine::Rocket(1.5, 1.1),
decoy: false, decoy: false,
@@ -198,6 +236,7 @@ const DRONE_SPEC_ISKANDER: DroneSpec = DroneSpec {
clearance: 0.0, clearance: 0.0,
dive: 0.0, dive: 0.0,
warhead: 8, warhead: 8,
accuracy: (1.4, 0.06),
scale: 1.8, scale: 1.8,
engine: Engine::Rocket(1.5, 1.6), engine: Engine::Rocket(1.5, 1.6),
decoy: false, decoy: false,
@@ -219,6 +258,7 @@ const DRONE_SPEC_KINZHAL: DroneSpec = DroneSpec {
clearance: 0.0, clearance: 0.0,
dive: 0.0, dive: 0.0,
warhead: 8, warhead: 8,
accuracy: (1.5, 0.06),
scale: 1.7, scale: 1.7,
engine: Engine::Rocket(1.5, 1.5), engine: Engine::Rocket(1.5, 1.5),
decoy: false, decoy: false,
@@ -240,6 +280,7 @@ const DRONE_SPEC_ORESHNIK: DroneSpec = DroneSpec {
clearance: 0.0, clearance: 0.0,
dive: 0.0, dive: 0.0,
warhead: 0, warhead: 0,
accuracy: (1.6, 0.08),
scale: 2.6, scale: 2.6,
engine: Engine::Rocket(1.5, 2.4), engine: Engine::Rocket(1.5, 2.4),
decoy: false, decoy: false,
@@ -261,6 +302,7 @@ const DRONE_SPEC_ORESHNIKBLOCK: DroneSpec = DroneSpec {
clearance: 0.0, clearance: 0.0,
dive: 0.0, dive: 0.0,
warhead: 4, warhead: 4,
accuracy: (1.6, 0.08),
scale: 1.6, scale: 1.6,
engine: Engine::Rocket(1.0, 1.0), engine: Engine::Rocket(1.0, 1.0),
decoy: false, decoy: false,
@@ -282,6 +324,7 @@ const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec {
clearance: 0.0, clearance: 0.0,
dive: 0.0, dive: 0.0,
warhead: 3, warhead: 3,
accuracy: (1.6, 0.08),
scale: 1.1, scale: 1.1,
engine: Engine::Rocket(1.0, 1.0), engine: Engine::Rocket(1.0, 1.0),
decoy: false, decoy: false,
@@ -295,6 +338,7 @@ const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec {
const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec { const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
model: "airdef:pac3", model: "airdef:pac3",
launcher_blast: 0.8,
speed: 5.5, speed: 5.5,
accel: 0.35, accel: 0.35,
turn: 0.3, turn: 0.3,
@@ -304,7 +348,7 @@ const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
eject_drag: 0.0, eject_drag: 0.0,
pk: 0.9, pk: 0.9,
fuse: 4.0, fuse: 4.0,
life: 240, life: 360,
scale: 1.0, scale: 1.0,
flame: 1.0, flame: 1.0,
rear: 28.0, rear: 28.0,
@@ -315,6 +359,7 @@ const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec { const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec {
model: "airdef:m57e6", model: "airdef:m57e6",
launcher_blast: 0.45,
speed: 5.0, speed: 5.0,
accel: 0.5, accel: 0.5,
turn: 0.32, turn: 0.32,
@@ -335,6 +380,7 @@ const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec {
const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec { const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
model: "airdef:m48n6", model: "airdef:m48n6",
launcher_blast: 1.8,
speed: 7.0, speed: 7.0,
accel: 0.5, accel: 0.5,
turn: 0.22, turn: 0.22,
@@ -344,7 +390,7 @@ const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
eject_drag: 0.07, eject_drag: 0.07,
pk: 0.9, pk: 0.9,
fuse: 5.0, fuse: 5.0,
life: 300, life: 390,
scale: 1.5, scale: 1.5,
flame: 1.4, flame: 1.4,
rear: 30.0, rear: 30.0,
@@ -355,6 +401,7 @@ const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec { const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
model: "airdef:m77n6", model: "airdef:m77n6",
launcher_blast: 2.2,
speed: 9.0, speed: 9.0,
accel: 0.6, accel: 0.6,
turn: 0.22, turn: 0.22,
@@ -364,7 +411,7 @@ const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
eject_drag: 0.07, eject_drag: 0.07,
pk: 0.95, pk: 0.95,
fuse: 6.0, fuse: 6.0,
life: 320, life: 430,
scale: 1.7, scale: 1.7,
flame: 1.6, flame: 1.6,
rear: 32.0, rear: 32.0,
@@ -375,6 +422,7 @@ const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec { const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec {
model: "airdef:irist_missile", model: "airdef:irist_missile",
launcher_blast: 0.6,
speed: 7.0, speed: 7.0,
accel: 0.5, accel: 0.5,
turn: 0.35, turn: 0.35,
@@ -395,6 +443,7 @@ const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec {
const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec { const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec {
model: "airdef:amraam_missile", model: "airdef:amraam_missile",
launcher_blast: 0.5,
speed: 6.0, speed: 6.0,
accel: 0.45, accel: 0.45,
turn: 0.3, turn: 0.3,
@@ -415,6 +464,7 @@ const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec {
const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec { const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec {
model: "airdef:m48n6", model: "airdef:m48n6",
launcher_blast: 1.2,
speed: 6.5, speed: 6.5,
accel: 0.5, accel: 0.5,
turn: 0.25, turn: 0.25,
@@ -435,6 +485,7 @@ const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec {
const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec { const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec {
model: "airdef:m57e6", model: "airdef:m57e6",
launcher_blast: 0.4,
speed: 5.5, speed: 5.5,
accel: 0.6, accel: 0.6,
turn: 0.4, turn: 0.4,
@@ -455,6 +506,7 @@ const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec {
const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec { const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec {
model: "airdef:p1sun", model: "airdef:p1sun",
launcher_blast: 0.1,
speed: 2.8, speed: 2.8,
accel: 0.12, accel: 0.12,
turn: 0.3, turn: 0.3,
@@ -474,6 +526,22 @@ const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec {
}; };
impl DroneKind { impl DroneKind {
pub const ALL: [DroneKind; 13] = [
DroneKind::Shahed,
DroneKind::Geran3,
DroneKind::Lancet,
DroneKind::Gerbera,
DroneKind::Kh101,
DroneKind::Kalibr,
DroneKind::Kh22,
DroneKind::Zircon,
DroneKind::Iskander,
DroneKind::Kinzhal,
DroneKind::Oreshnik,
DroneKind::OreshnikBlock,
DroneKind::OreshnikSub,
];
/// Its row of numbers from `catalog/specs.json`. /// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static DroneSpec { pub fn spec(self) -> &'static DroneSpec {
match self { match self {
+37 -7
View File
@@ -349,6 +349,13 @@ pub struct Strikes {
} }
impl Strikes { impl Strikes {
/// What the counter-strikes hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::vec_bytes;
vec_bytes(&self.known) + vec_bytes(&self.flights) + vec_bytes(&self.pending) + vec_bytes(&self.flown)
+ vec_bytes(&self.wrecks) + vec_bytes(&self.cancelled)
+ self.news.iter().map(|s| s.capacity()).sum::<usize>()
}
pub fn new() -> Self { pub fn new() -> Self {
Strikes { stock: TUNE.stock, ..Default::default() } Strikes { stock: TUNE.stock, ..Default::default() }
} }
@@ -723,8 +730,11 @@ impl Sim {
&& s.alive() && !s.moving() && s.reloading == 0 && s.cooldown == 0 && s.alive() && !s.moving() && s.reloading == 0 && s.cooldown == 0
&& s.part(Part::Launcher) > 0.0 && s.ground_rounds > u32::from(s.ground_return) && s.preparing.is_none() && dist <= TUNE.range) && s.part(Part::Launcher) > 0.0 && s.ground_rounds > u32::from(s.ground_return) && s.preparing.is_none() && dist <= TUNE.range)
.then_some((i, dist)) .then_some((i, dist))
}).min_by(|(i,a), (j,b)| self.sams[*j].ground_rounds.cmp(&self.sams[*i].ground_rounds) }).min_by(|(i,a), (j,b)| {
.then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id))) let available = |s: &Sam| s.ground_rounds.saturating_sub(u32::from(s.ground_return));
available(&self.sams[*j]).cmp(&available(&self.sams[*i]))
.then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id))
})
.ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?; .ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?;
let sam = &mut self.sams[i]; let sam = &mut self.sams[i];
sam.sync_tube_cells(); sam.sync_tube_cells();
@@ -767,8 +777,9 @@ impl Sim {
sam.launched = 12; sam.launched = 12;
sam.fired += 1; sam.fired += 1;
let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length(); let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length();
// The launch betrays the carrier: the enemy saw it fire, no more than that. if recon::has_signal_witness(&self.drones, sam.pos) {
self.intel.observe(&self.sams[i], self.tick, ew::Seen::Launch); self.recon.signal(sam, self.tick, recon::Source::Launch);
}
self.strikes.fired += 1; self.strikes.fired += 1;
self.strikes.next += 1; self.strikes.next += 1;
// The counted flight includes the unlit ejection: the missile is honest about // The counted flight includes the unlit ejection: the missile is honest about
@@ -1182,7 +1193,8 @@ mod tests {
assert!(sim.queue.is_empty(), "the jobs are cancelled"); assert!(sim.queue.is_empty(), "the jobs are cancelled");
assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched); assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched);
assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages); assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages);
assert!(sim.strikes.wrecks.len() == 1 && sim.fires.list.len() == 1, "a wreck and a fire"); assert_eq!(sim.strikes.wrecks.len(), 1);
assert!(sim.fires.list.iter().any(|fire| horizontal(fire.at - site.pos).length() <= TUNE.hit_r), "a fire at the destroyed site");
assert!(!sim.blasts.is_empty() || sim.tick > 0); assert!(!sim.blasts.is_empty() || sim.tick > 0);
assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_))); assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_)));
assert!(sim.order_test_strike(id, player, &mut out).is_err(), "destroyed already"); assert!(sim.order_test_strike(id, player, &mut out).is_err(), "destroyed already");
@@ -1388,6 +1400,23 @@ mod tests {
assert!(sim.sams[0].ground_return); assert!(sim.sams[0].ground_return);
} }
#[test]
fn carrier_selection_ranks_unreserved_rounds_before_distance_and_id() {
let mut sim = Sim::new(11);
let site = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 500.0), 0);
for (id, z, reserved) in [(1, 400.0, true), (2, 200.0, false)] {
let mut sam = Sam::new(id, SamKind::S400, DVec3::new(0.0, 0.0, z), 0.0);
sam.missiles = 2; sam.ground_rounds = 2; sam.ground_return = reserved; sam.cooldown = 0;
sim.sams.push(sam);
}
let mut out = Out::default();
sim.order_strike(site, DVec3::ZERO, &mut out).unwrap();
assert_eq!(sim.strikes.pending[0].carrier, 2);
sim.tick += launch::OPEN_TICKS;
sim.prepare_ground_strikes(&mut out);
assert_eq!((sim.sams[0].ground_rounds, sim.sams[1].ground_rounds), (2, 1));
}
#[test] #[test]
fn ground_orders_reserve_the_carrier_and_target_until_ejection() { fn ground_orders_reserve_the_carrier_and_target_until_ejection() {
let mut sim = Sim::new(11); let mut sim = Sim::new(11);
@@ -1486,12 +1515,13 @@ mod tests {
k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO }); k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO });
sim.order_test_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap(); sim.order_test_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
out.messages.clear(); out.messages.clear();
let wrecks = sim.fires.list.len();
run(&mut sim, &mut ground, &mut out, 500); run(&mut sim, &mut ground, &mut out, 500);
assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages); assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages);
assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive); assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive);
// Nothing drawn: no wreck, no fire, no blast of its own. // Nothing drawn: no wreck, no fire, no blast of its own.
assert_eq!((sim.strikes.wrecks.len(), sim.fires.list.len()), (0, wrecks)); let site = sim.sites.get(id).unwrap();
assert!(sim.strikes.wrecks.is_empty());
assert!(sim.fires.list.iter().all(|fire| horizontal(fire.at - site.pos).length() > TUNE.hit_r));
} }
#[test] #[test]
+80 -15
View File
@@ -5,10 +5,32 @@ const NAMED_BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0,
const NAMED_BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3)); const NAMED_BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5); const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum SamKind {
Patriot,
Gepard,
Pantsir,
S400,
S500,
IrisT,
Nasams,
Buk,
Tor,
P1sun,
Radar,
Depot,
Tzm,
Ew,
Light,
Optical,
}
const UNIT_SPEC_PATRIOT: SamSpec = SamSpec { const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
name: "Patriot", name: "Patriot",
key: "patriot", key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }), village_cost: 5,
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 950.0, interval: 16 }),
ground_strike: None,
gun: None, gun: None,
reload: 220, reload: 220,
scale: 1.3, scale: 1.3,
@@ -26,15 +48,17 @@ const UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
mount: (0.69, 1.2), mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375), pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot, muzzle: Muzzle::Patriot,
sensor: 585.0, sensor: 1350.0,
mast: 5.0, mast: 5.0,
}; };
const UNIT_SPEC_GEPARD: SamSpec = SamSpec { const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
name: "Гепард", name: "Гепард",
key: "gepard", key: "gepard",
village_cost: 2,
missile: None, missile: None,
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }), ground_strike: None,
gun: Some(GunSpec { range: 180.0, track: 260.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160, reload: 160,
scale: 1.25, scale: 1.25,
rest_pitch: 0.0, rest_pitch: 0.0,
@@ -51,15 +75,17 @@ const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
mount: (1.55, 0.25), mount: (1.55, 0.25),
pivot: DVec3::ZERO, pivot: DVec3::ZERO,
muzzle: Muzzle::None, muzzle: Muzzle::None,
sensor: 255.0, sensor: 335.0,
mast: 3.0, mast: 3.0,
}; };
const UNIT_SPEC_PANTSIR: SamSpec = SamSpec { const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
name: "Панцирь-С1", name: "Панцирь-С1",
key: "pantsir", key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }), village_cost: 3,
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }), missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 330.0, interval: 14 }),
ground_strike: None,
gun: Some(GunSpec { range: 125.0, track: 185.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280, reload: 280,
scale: 1.3, scale: 1.3,
rest_pitch: 0.0, rest_pitch: 0.0,
@@ -76,19 +102,21 @@ const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
mount: (1.35, 0.69), mount: (1.35, 0.69),
pivot: DVec3::ZERO, pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir, muzzle: Muzzle::Pantsir,
sensor: 292.0, sensor: 450.0,
mast: 4.0, mast: 4.0,
}; };
const UNIT_SPEC_S400: SamSpec = SamSpec { const UNIT_SPEC_S400: SamSpec = SamSpec {
name: "С-400", name: "С-400",
key: "s400", key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }), village_cost: 5,
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 1300.0, interval: 20 }),
ground_strike: Some(catalog::GroundStrike::Rm48uGame),
gun: None, gun: None,
reload: 420, reload: 420,
scale: 1.5, scale: 1.5,
rest_pitch: HALF_PI - 0.02, rest_pitch: HALF_PI - 0.02,
roles: 30, roles: 28,
family: Family::Vertical, family: Family::Vertical,
parts: Parts { parts: Parts {
body: "airdef:s400_chassis", body: "airdef:s400_chassis",
@@ -101,14 +129,16 @@ const UNIT_SPEC_S400: SamSpec = SamSpec {
mount: (0.7, 1.45), mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT, pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0), muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 936.0, sensor: 1750.0,
mast: 5.0, mast: 5.0,
}; };
const UNIT_SPEC_S500: SamSpec = SamSpec { const UNIT_SPEC_S500: SamSpec = SamSpec {
name: "С-500", name: "С-500",
key: "s500", key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }), village_cost: 6,
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1850.0, interval: 20 }),
ground_strike: None,
gun: None, gun: None,
reload: 520, reload: 520,
scale: 1.6, scale: 1.6,
@@ -126,14 +156,16 @@ const UNIT_SPEC_S500: SamSpec = SamSpec {
mount: (0.7, 1.45), mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT, pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5), muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 1365.0, sensor: 2450.0,
mast: 5.0, mast: 5.0,
}; };
const UNIT_SPEC_IRIST: SamSpec = SamSpec { const UNIT_SPEC_IRIST: SamSpec = SamSpec {
name: "IRIS-T SLM", name: "IRIS-T SLM",
key: "irist", key: "irist",
village_cost: 4,
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }), missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
ground_strike: None,
gun: None, gun: None,
reload: 300, reload: 300,
scale: 1.4, scale: 1.4,
@@ -158,7 +190,9 @@ const UNIT_SPEC_IRIST: SamSpec = SamSpec {
const UNIT_SPEC_NASAMS: SamSpec = SamSpec { const UNIT_SPEC_NASAMS: SamSpec = SamSpec {
name: "NASAMS", name: "NASAMS",
key: "nasams", key: "nasams",
village_cost: 4,
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }), missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
ground_strike: None,
gun: None, gun: None,
reload: 260, reload: 260,
scale: 1.3, scale: 1.3,
@@ -183,7 +217,9 @@ const UNIT_SPEC_NASAMS: SamSpec = SamSpec {
const UNIT_SPEC_BUK: SamSpec = SamSpec { const UNIT_SPEC_BUK: SamSpec = SamSpec {
name: "Бук-М2", name: "Бук-М2",
key: "buk", key: "buk",
village_cost: 4,
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }), missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
ground_strike: None,
gun: None, gun: None,
reload: 400, reload: 400,
scale: 1.4, scale: 1.4,
@@ -208,7 +244,9 @@ const UNIT_SPEC_BUK: SamSpec = SamSpec {
const UNIT_SPEC_TOR: SamSpec = SamSpec { const UNIT_SPEC_TOR: SamSpec = SamSpec {
name: "Тор-М2", name: "Тор-М2",
key: "tor", key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }), village_cost: 3,
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 350.0, interval: 8 }),
ground_strike: None,
gun: None, gun: None,
reload: 300, reload: 300,
scale: 1.3, scale: 1.3,
@@ -226,14 +264,16 @@ const UNIT_SPEC_TOR: SamSpec = SamSpec {
mount: (1.5, 0.0), mount: (1.5, 0.0),
pivot: DVec3::ZERO, pivot: DVec3::ZERO,
muzzle: Muzzle::Cells, muzzle: Muzzle::Cells,
sensor: 315.0, sensor: 475.0,
mast: 3.5, mast: 3.5,
}; };
const UNIT_SPEC_P1SUN: SamSpec = SamSpec { const UNIT_SPEC_P1SUN: SamSpec = SamSpec {
name: "P1-SUN", name: "P1-SUN",
key: "p1sun", key: "p1sun",
village_cost: 3,
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }), missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
ground_strike: None,
gun: None, gun: None,
reload: 240, reload: 240,
scale: 1.1, scale: 1.1,
@@ -258,7 +298,9 @@ const UNIT_SPEC_P1SUN: SamSpec = SamSpec {
const UNIT_SPEC_RADAR: SamSpec = SamSpec { const UNIT_SPEC_RADAR: SamSpec = SamSpec {
name: "РЛС дальнего обнаружения", name: "РЛС дальнего обнаружения",
key: "radar", key: "radar",
village_cost: 2,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.5, scale: 1.5,
@@ -276,14 +318,16 @@ const UNIT_SPEC_RADAR: SamSpec = SamSpec {
mount: (0.0, 0.0), mount: (0.0, 0.0),
pivot: DVec3::ZERO, pivot: DVec3::ZERO,
muzzle: Muzzle::None, muzzle: Muzzle::None,
sensor: 2550.0, sensor: 3800.0,
mast: 16.0, mast: 16.0,
}; };
const UNIT_SPEC_DEPOT: SamSpec = SamSpec { const UNIT_SPEC_DEPOT: SamSpec = SamSpec {
name: "Склад боеприпасов", name: "Склад боеприпасов",
key: "depot", key: "depot",
village_cost: 2,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.5, scale: 1.5,
@@ -308,7 +352,9 @@ const UNIT_SPEC_DEPOT: SamSpec = SamSpec {
const UNIT_SPEC_TZM: SamSpec = SamSpec { const UNIT_SPEC_TZM: SamSpec = SamSpec {
name: "ТЗМ", name: "ТЗМ",
key: "tzm", key: "tzm",
village_cost: 2,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.3, scale: 1.3,
@@ -333,7 +379,9 @@ const UNIT_SPEC_TZM: SamSpec = SamSpec {
const UNIT_SPEC_EW: SamSpec = SamSpec { const UNIT_SPEC_EW: SamSpec = SamSpec {
name: "Станция РЭБ", name: "Станция РЭБ",
key: "ew", key: "ew",
village_cost: 2,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.3, scale: 1.3,
@@ -358,7 +406,9 @@ const UNIT_SPEC_EW: SamSpec = SamSpec {
const UNIT_SPEC_LIGHT: SamSpec = SamSpec { const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
name: "Прожектор", name: "Прожектор",
key: "light", key: "light",
village_cost: 1,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.2, scale: 1.2,
@@ -383,7 +433,9 @@ const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
const UNIT_SPEC_OPTICAL: SamSpec = SamSpec { const UNIT_SPEC_OPTICAL: SamSpec = SamSpec {
name: "Оптический пост", name: "Оптический пост",
key: "optical", key: "optical",
village_cost: 1,
missile: None, missile: None,
ground_strike: None,
gun: None, gun: None,
reload: 0, reload: 0,
scale: 1.0, scale: 1.0,
@@ -406,6 +458,19 @@ const UNIT_SPEC_OPTICAL: SamSpec = SamSpec {
}; };
impl SamKind { impl SamKind {
pub const ARMED: [SamKind; 10] = [
SamKind::Patriot,
SamKind::Gepard,
SamKind::Pantsir,
SamKind::S400,
SamKind::S500,
SamKind::IrisT,
SamKind::Nasams,
SamKind::Buk,
SamKind::Tor,
SamKind::P1sun,
];
/// Its row of numbers from `catalog/specs.json`. /// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static SamSpec { pub fn spec(self) -> &'static SamSpec {
match self { match self {
@@ -1,8 +1,8 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit. // Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const VARIANTS: &[UnitVariant] = &[ pub const VARIANTS: &[UnitVariant] = &[
UnitVariant { id: "s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая", description: "Пусковая С-400 без своей РЛС: работает по данным сети." }, UnitVariant { id: "s400_launcher", deploy_item: "airdef:deploy_s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая", description: "Пусковая С-400 без своей РЛС: работает по данным сети." },
UnitVariant { id: "s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая", description: "Пусковая С-500 без своей РЛС: работает по данным сети." }, UnitVariant { id: "s500_launcher", deploy_item: "airdef:deploy_s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая", description: "Пусковая С-500 без своей РЛС: работает по данным сети." },
UnitVariant { id: "radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора", description: "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт." }, UnitVariant { id: "radar_search", deploy_item: "airdef:deploy_radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора", description: "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт." },
UnitVariant { id: "radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения", description: "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск." }, UnitVariant { id: "radar_track", deploy_item: "airdef:deploy_radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения", description: "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск." },
UnitVariant { id: "radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." }, UnitVariant { id: "radar_height", deploy_item: "airdef:deploy_radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
]; ];
+6 -39
View File
@@ -5,32 +5,6 @@
//! wrecks, saving and move orders; only what they carry differs. //! wrecks, saving and move orders; only what they carry differs.
use super::*; use super::*;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum SamKind {
Patriot,
Gepard,
Pantsir,
S400,
S500,
IrisT,
Nasams,
Buk,
Tor,
P1sun,
/// A long-range search radar: no weapons, it feeds the network.
Radar,
/// An ammunition depot: the reload trucks fill up there.
Depot,
/// A transport-loader: drives missiles from a depot to the systems.
Tzm,
/// An electronic-warfare station: jams the drones' navigation while switched on.
Ew,
/// A searchlight: lights up targets at night for the guns.
Light,
/// A passive optical observation post: no radar, no weapon, one class observation at a time (#136).
Optical,
}
/// How a vehicle is put together: how its launcher or turret moves and is drawn. /// How a vehicle is put together: how its launcher or turret moves and is drawn.
#[derive(Clone, Copy, PartialEq, Eq, Debug)] #[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Family { pub enum Family {
@@ -112,7 +86,10 @@ pub(super) struct Drive {
pub struct SamSpec { pub struct SamSpec {
pub name: &'static str, pub name: &'static str,
pub key: &'static str, pub key: &'static str,
/// Points to deploy this unit in the village campaign.
pub village_cost: u32,
pub(super) missile: Option<MissileLoad>, pub(super) missile: Option<MissileLoad>,
pub(super) ground_strike: Option<catalog::GroundStrike>,
pub(super) gun: Option<GunSpec>, pub(super) gun: Option<GunSpec>,
pub(super) reload: u32, pub(super) reload: u32,
pub(super) scale: f64, pub(super) scale: f64,
@@ -150,19 +127,6 @@ include!("unit_specs_generated.rs");
impl SamKind { impl SamKind {
pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS; pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS;
/// The ones that shoot (the roles menu lists these).
pub const ARMED: [SamKind; 10] = [
SamKind::Patriot,
SamKind::Gepard,
SamKind::Pantsir,
SamKind::S400,
SamKind::S500,
SamKind::IrisT,
SamKind::Nasams,
SamKind::Buk,
SamKind::Tor,
SamKind::P1sun,
];
pub fn name(self) -> &'static str { pub fn name(self) -> &'static str {
self.spec().name self.spec().name
} }
@@ -185,6 +149,9 @@ impl SamKind {
pub fn missile_magazine(self) -> Option<u32> { pub fn missile_magazine(self) -> Option<u32> {
self.spec().missile.as_ref().map(|m| m.magazine) self.spec().missile.as_ref().map(|m| m.magazine)
} }
pub fn supports_rm48u(self) -> bool {
self.spec().ground_strike == Some(catalog::GroundStrike::Rm48uGame)
}
/// Whether it has a gun (its bursts are read by the status line). /// Whether it has a gun (its bursts are read by the status line).
pub fn has_gun(self) -> bool { pub fn has_gun(self) -> bool {
self.spec().gun.is_some() self.spec().gun.is_some()
+847 -27
View File
File diff suppressed because it is too large Load Diff
+49 -12
View File
@@ -36,6 +36,20 @@ pub enum Fill {
Mixed(Box<[u8; 512]>), Mixed(Box<[u8; 512]>),
} }
impl Fill {
fn block(&self, x: i32, y: i32, z: i32) -> Option<bool> {
match self {
Fill::Unknown => None,
Fill::Empty => Some(false),
Fill::Full => Some(true),
Fill::Mixed(bits) => {
let i = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize;
Some(bits[i >> 3] >> (i & 7) & 1 != 0)
}
}
}
}
/// An answer for a section, as the game gives it. /// An answer for a section, as the game gives it.
pub struct SectionAnswer { pub struct SectionAnswer {
pub sec: Sec, pub sec: Sec,
@@ -232,6 +246,25 @@ impl WorldCache {
.map(|e| 48 + if matches!(e.fill, Fill::Mixed(_)) { 512 } else { 0 }) .map(|e| 48 + if matches!(e.fill, Fill::Mixed(_)) { 512 } else { 0 })
.sum() .sum()
} }
/// What the cache holds, about: `(sections, other)` — the sections' table and mixed
/// bits, then the rays, queues, questions and blasts expected (see `sim::memory`).
pub fn memory(&self) -> (usize, usize) {
use super::memory::{map_bytes, vec_bytes};
let entry = std::mem::size_of::<Sec>() + std::mem::size_of::<Entry>();
let sections = map_bytes(self.secs.len(), entry)
+ self.secs.values().filter(|e| matches!(e.fill, Fill::Mixed(_))).count() * 512;
let ray_entry = std::mem::size_of::<(u32, [i32; 3])>() + std::mem::size_of::<RayEntry>();
let other = map_bytes(self.rays.entries.len(), ray_entry)
+ map_bytes(self.rays.by_id.len(), std::mem::size_of::<u32>() + std::mem::size_of::<(u32, [i32; 3])>())
+ vec_bytes(&self.rays.out)
+ vec_bytes(&self.urgent)
+ vec_bytes(&self.ahead)
+ map_bytes(self.queued.len(), std::mem::size_of::<Sec>())
+ map_bytes(self.asked.len(), std::mem::size_of::<Sec>() + std::mem::size_of::<u64>())
+ vec_bytes(&self.expected)
+ map_bytes(self.changed_cols.len(), std::mem::size_of::<(i32, i32)>());
(sections, other)
}
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.secs.len() self.secs.len()
} }
@@ -511,19 +544,23 @@ impl WorldCache {
self.unread_pending = true; self.unread_pending = true;
return None; return None;
}; };
match &entry.fill { if entry.fill == Fill::Unknown {
Fill::Unknown => { // Asked and answered unknown: no chunk there. Asked again (or not at all yet): waiting.
// Asked and answered unknown: no chunk there. Asked again (or not at all yet): waiting. self.unread_pending = entry.stale && entry.since == 0;
self.unread_pending = entry.stale && entry.since == 0;
None
}
Fill::Empty => Some(false),
Fill::Full => Some(true),
Fill::Mixed(bits) => {
let i = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize;
Some(bits[i >> 3] >> (i & 7) & 1 != 0)
}
} }
entry.fill.block(x, y, z)
}
/// Vehicle motion waits for a new mask after a notified block change. As with the height map,
/// `None` means pending and `Some(None)` means the host could not read this column.
pub(super) fn road_block(&mut self, last: &mut Option<Sec>, x: i32, y: i32, z: i32, now: u64) -> Option<Option<bool>> {
let s = sec_of(x, y, z);
if *last != Some(s) {
*last = Some(s);
self.touch(s, true, now);
}
let entry = self.secs.get(&s)?;
(!entry.stale).then(|| entry.fill.block(x, y, z))
} }
/// Whether the block is known to hold no solid block, with the sky above it /// Whether the block is known to hold no solid block, with the sky above it
+671
View File
@@ -0,0 +1,671 @@
//! Three rounds over one village layout. The existing simulation owns all units,
//! health, ammunition, and combat. The scenario only schedules the rounds and scores objectives.
use super::*;
const PAUSE: u64 = 20 * 30;
const WAVES: u8 = 3;
const WAVE_SEED: u64 = 0x5649_4c4c_4147_4501;
const OBJECTIVES: [(&str, u32); 3] = [("Штаб", 50), ("Лазарет", 30), ("Укрытие", 20)];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Level {
Easy,
Normal,
Hard,
}
impl Level {
fn parse(key: &str) -> Option<Self> {
match key {
"easy" => Some(Self::Easy),
"normal" => Some(Self::Normal),
"hard" => Some(Self::Hard),
_ => None,
}
}
fn key(self) -> &'static str {
match self {
Self::Easy => "easy",
Self::Normal => "normal",
Self::Hard => "hard",
}
}
fn budget(self) -> u32 {
match self {
Self::Easy => 30,
Self::Normal => 25,
Self::Hard => 22,
}
}
fn order(self, wave: u8) -> sim::RaidOrder {
use DroneKind::*;
let extra = match self {
Self::Easy => 0,
Self::Normal => 3,
Self::Hard => 6,
};
let (kinds, dist, approach) = match wave {
0 => (
vec![
(Gerbera, 4 + extra),
(Shahed, 8 + extra),
(Geran3, 2 + extra),
],
430.0,
sim::Approach::Sector,
),
1 => (
vec![
(Gerbera, 6 + extra),
(Shahed, 10 + extra),
(Geran3, 5 + extra),
(Kh101, 3 + extra),
],
600.0,
sim::Approach::TwoSectors,
),
_ => (
vec![
(Gerbera, 8 + extra),
(Shahed, 12 + extra),
(Geran3, 6 + extra),
(Kh101, 4 + extra),
(Iskander, 1 + extra / 3),
],
760.0,
sim::Approach::Waves,
),
};
sim::RaidOrder {
kinds,
dist,
approach,
aim: sim::Aim::Smart,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
Survey { origin: DVec3, until: u64 },
Setup,
Waiting { wave: u8, until: u64 },
Fighting(u8),
Finished([f64; 3]),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Village {
level: Level,
phase: Phase,
spent: u32,
}
pub(crate) fn cost(kind: SamKind) -> u32 {
kind.spec().village_cost
}
pub(crate) fn active(village: Option<Village>) -> bool {
village.is_some_and(|v| !matches!(v.phase, Phase::Finished(_)))
}
fn idle(sim: &Sim) -> bool {
!sim.planning() && sim.queue.is_empty() && sim.missiles.is_empty() && sim.drones.is_empty()
}
fn score(health: &[f64]) -> (f64, bool) {
let points = OBJECTIVES
.iter()
.zip(health)
.map(|((_, weight), hp)| f64::from(*weight) * hp.clamp(0.0, 100.0) / 100.0)
.sum::<f64>();
(
points,
points >= 65.0 && health.first().is_some_and(|hp| *hp > 0.0),
)
}
fn objective_status(health: &[f64]) -> String {
OBJECTIVES
.iter()
.zip(health)
.map(|((name, _), hp)| format!("{name} {:.0}%", hp))
.collect::<Vec<_>>()
.join(" · ")
}
impl Village {
fn used(self, layout_cost: u32) -> u32 {
if matches!(self.phase, Phase::Survey { .. } | Phase::Setup) {
layout_cost
} else {
self.spent
}
}
pub(crate) fn charge(&mut self, layout_cost: u32, cost: u32) -> Result<(), String> {
if matches!(self.phase, Phase::Finished(_)) {
return Ok(());
}
if !matches!(self.phase, Phase::Setup | Phase::Waiting { .. }) {
return Err("Расстановка доступна при подготовке и в паузе между волнами".into());
}
let remaining = self.level.budget().saturating_sub(self.used(layout_cost));
if cost > remaining {
return Err(format!(
"На эту технику нужно {cost} очк., доступно {remaining}"
));
}
if matches!(self.phase, Phase::Waiting { .. }) {
self.spent += cost;
}
Ok(())
}
pub(crate) fn ready(self) -> bool {
self.phase == Phase::Setup
}
pub(crate) fn fighting(self) -> bool {
matches!(self.phase, Phase::Fighting(_))
}
pub(crate) fn save(self, now: u64, air: bool) -> Option<String> {
let phase = match self.phase {
Phase::Survey { .. } => return None,
Phase::Setup => "setup 0 0".into(),
Phase::Waiting { wave, until } => format!("wait {wave} {}", until.saturating_sub(now)),
Phase::Fighting(wave) if air => format!("fight {wave} 0"),
Phase::Fighting(wave) => format!("wait {wave} 20"),
Phase::Finished([hq, clinic, shelter]) => format!("done 0 0 {hq} {clinic} {shelter}"),
};
Some(format!(
"village {} {} {phase}\n",
self.level.key(),
self.spent
))
}
pub(crate) fn read(text: &str, objectives: usize) -> Result<Option<Self>, String> {
let bad = || "Некорректное состояние сценария «Оборона деревни»".to_string();
let mut rows = text.lines().filter_map(|row| row.strip_prefix("village "));
let Some(row) = rows.next() else {
return Ok(None);
};
if rows.next().is_some() {
return Err(bad());
}
let words: Vec<_> = row.split_whitespace().collect();
let [level, spent, phase, wave, remaining, scores @ ..] = words.as_slice() else {
return Err(bad());
};
let level = Level::parse(level).ok_or_else(bad)?;
let spent = spent
.parse::<u32>()
.ok()
.filter(|&n| n <= level.budget())
.ok_or_else(bad)?;
let wave = wave
.parse::<u8>()
.ok()
.filter(|&n| n < WAVES)
.ok_or_else(bad)?;
let remaining = remaining
.parse::<u64>()
.ok()
.filter(|&n| n <= PAUSE)
.ok_or_else(bad)?;
let phase = match (*phase, wave, remaining, scores) {
("done", 0, 0, [hq, clinic, shelter]) => {
let parse = |s: &str| {
s.parse::<f64>()
.ok()
.filter(|hp| (0.0..=100.0).contains(hp))
.ok_or_else(bad)
};
Phase::Finished([parse(hq)?, parse(clinic)?, parse(shelter)?])
}
("setup", 0, 0, []) if objectives == OBJECTIVES.len() => Phase::Setup,
("wait", wave, remaining, []) if objectives == OBJECTIVES.len() => Phase::Waiting {
wave,
until: remaining,
},
("fight", wave, 0, []) if objectives == OBJECTIVES.len() => Phase::Fighting(wave),
_ => return Err(bad()),
};
Ok(Some(Self {
level,
phase,
spent,
}))
}
/// Move a saved countdown from its relative clock to the restored simulation clock.
pub(crate) fn resume(&mut self, now: u64) {
if let Phase::Waiting { until, .. } = &mut self.phase {
*until = until.saturating_add(now);
}
}
}
impl AirDef {
pub(crate) fn village_active(&self) -> bool {
active(self.village)
}
pub(crate) fn village_layout_cost(&self) -> u32 {
self.sim.sams.iter().map(|s| cost(s.kind)).sum()
}
fn request_village(&mut self, level: Level, origin: DVec3) -> Result<String, String> {
if self.village_active() || !idle(&self.sim) {
return Err("Завершите текущий налёт или остановите сценарий".into());
}
if self.village_layout_cost() > level.budget() {
return Err(format!(
"Текущая расстановка превышает бюджет в {} очк.",
level.budget()
));
}
let phase = if self.sim.targets.is_empty() {
Phase::Survey {
origin,
until: self.sim.tick + 160,
}
} else {
if self.sim.targets.len() != 3 || self.sim.target_health.as_slice() != [100.0; 3] {
return Err("Отметьте ровно три целых объекта или уберите все отметки для автоматической расстановки".into());
}
Phase::Setup
};
self.village = Some(Village {
phase,
level,
spent: 0,
});
self.dirty = true;
Ok(self.village_status())
}
pub(crate) fn village_status(&self) -> String {
let Some(v) = self.village else {
return "Оборона деревни · выберите сложность или /airdef scenario village normal"
.into();
};
let phase = match v.phase {
Phase::Survey { .. } => "ищу точки для объектов".into(),
Phase::Setup => "расставьте технику, затем начните оборону".into(),
Phase::Waiting { wave, until } => format!(
"волна {}/{WAVES} через {} с",
wave + 1,
until.saturating_sub(self.sim.tick).div_ceil(20)
),
Phase::Fighting(wave) => format!("идёт волна {}/{WAVES}", wave + 1),
Phase::Finished(health) => {
let (points, win) = score(&health);
format!(
"{} · {:.0}/100",
if win {
"Победа"
} else {
"Поражение"
},
points
)
}
};
let remaining = v
.level
.budget()
.saturating_sub(v.used(self.village_layout_cost()));
let health = match &v.phase {
Phase::Finished(health) => health.as_slice(),
_ => self.sim.target_health.as_slice(),
};
format!(
"Оборона деревни · {phase} · бюджет {remaining}/{}\n{}",
v.level.budget(),
objective_status(health)
)
}
pub(crate) fn village_command(&mut self, args: &[&str]) -> Result<String, String> {
match args {
[] | ["status"] => Ok(self.village_status()),
["prices"] => Ok(SamKind::ALL
.iter()
.map(|&k| format!("{} {}", k.name(), cost(k)))
.collect::<Vec<_>>()
.join(" · ")),
["stop"] => {
self.village = None;
self.dirty = true;
Ok("Сценарий остановлен. Расстановка и текущий налёт остаются в мире".into())
}
["start"] => {
let layout = self.village_layout_cost();
let v = self
.village
.as_mut()
.ok_or("Сначала выберите сложность сценария")?;
if v.phase != Phase::Setup || !idle(&self.sim) {
return Err(
"Оборона запускается после подготовки трёх объектов в спокойном небе"
.into(),
);
}
if layout == 0 || layout > v.level.budget() {
return Err(format!(
"Перед запуском разместите технику в пределах {} очк.",
v.level.budget()
));
}
v.spent = layout;
v.phase = Phase::Waiting {
wave: 0,
until: self.sim.tick + 20 * 5,
};
self.sim.reset_raid_intelligence();
self.sim.clear_breakthroughs();
self.dirty = true;
Ok(self.village_status())
}
[level] => {
let level = Level::parse(level).ok_or("Сложность: easy, normal или hard")?;
let p = player().ok_or("Нет игрока")?;
self.request_village(level, DVec3::new(p.x, p.y, p.z))
}
_ => Err("/airdef scenario village [easy|normal|hard|start|status|prices|stop]".into()),
}
}
pub(crate) fn tick_village(&mut self, out: &mut Out) {
let Some(mut v) = self.village else { return };
let now = self.sim.tick;
match v.phase {
Phase::Survey { origin, until } => {
let mut objects = [
origin,
origin + DVec3::new(48.0, 0.0, 12.0),
origin + DVec3::new(-35.0, 0.0, -32.0),
];
let mut ready = true;
for point in &mut objects {
if let Some(y) = self.ground.at(*point, now) {
point.y = y;
} else {
ready = false;
self.ground.want_chunk((
(point.x.floor() as i32) >> 4,
(point.z.floor() as i32) >> 4,
));
}
}
if ready {
self.sim.targets.extend(objects);
self.sim.target_health.extend([100.0; 3]);
v.phase = Phase::Setup;
out.messages.push(
"Штаб, лазарет и укрытие отмечены. Расставьте технику и начните оборону"
.into(),
);
} else if now >= until {
self.village = None;
self.dirty = true;
out.messages.push("Местность не загрузилась. Отметьте три объекта вручную или начните сценарий ближе к центру деревни".into());
return;
} else {
return;
}
}
Phase::Waiting { wave, until } if now >= until && idle(&self.sim) => {
let objects: Vec<_> = self
.sim
.targets
.iter()
.zip(&self.sim.target_health)
.filter(|(_, hp)| **hp > 0.0)
.map(|(&pos, _)| pos)
.collect();
if objects.is_empty() {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
self.sim.reseed(WAVE_SEED.wrapping_add(u64::from(wave)));
if self.sim.order_raid(&v.level.order(wave), &objects, out) == 0 {
return;
}
v.phase = Phase::Fighting(wave);
out.messages
.push(format!("Оборона деревни · волна {}/{WAVES}", wave + 1));
}
}
Phase::Fighting(wave) if now % 20 == 0 && idle(&self.sim) => {
if wave + 1 == WAVES || self.sim.target_health.iter().all(|&hp| hp <= 0.0) {
v.phase = Phase::Finished(
self.sim
.target_health
.as_slice()
.try_into()
.unwrap_or([0.0; 3]),
);
} else {
v.phase = Phase::Waiting {
wave: wave + 1,
until: now + PAUSE,
};
out.messages.push(format!(
"Волна {}/{} завершена. Следующая через {} с. {}",
wave + 1,
WAVES,
PAUSE / 20,
objective_status(&self.sim.target_health)
));
}
}
_ => return,
}
self.village = Some(v);
self.dirty = true;
if self.menu == Some(Page::Village) {
self.open_menu(Page::Village);
}
if matches!(v.phase, Phase::Finished(_)) {
out.messages.push(format!(
"{} · разбор: /airdef breaches",
self.village_status()
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::test_mod;
fn setup() -> AirDef {
let mut game = test_mod();
game.sim
.targets
.extend([DVec3::ZERO, DVec3::X * 50.0, DVec3::Z * 50.0]);
game.sim.target_health.extend([100.0; 3]);
game.request_village(Level::Normal, DVec3::ZERO).unwrap();
game
}
fn deploy(game: &mut AirDef, kind: SamKind) -> Result<u32, String> {
game.place(
kind,
sim::battery::SamMode::Integrated,
sim::battery::RadarRole::Multifunction,
DVec3::ZERO,
0.0,
)
}
#[test]
fn budget_guards_deployment_and_spent_points_stay_spent() {
let mut game = setup();
for _ in 0..4 {
deploy(&mut game, SamKind::S400).unwrap();
}
assert!(deploy(&mut game, SamKind::S500).is_err());
game.village_command(&["start"]).unwrap();
deploy(&mut game, SamKind::S400).unwrap();
game.sim.sams.remove(0);
assert!(deploy(&mut game, SamKind::Light).is_err());
assert!(game.command("airdef", "repair").is_err());
assert!(game.command("airdef", "targets clear").is_err());
assert!(game.command("airdef", "wave shahed 1").is_err());
assert_eq!(game.sim.targets.len(), 3);
}
#[test]
fn waiting_resumes_and_all_three_waves_keep_the_layout_state() {
let mut game = setup();
deploy(&mut game, SamKind::S400).unwrap();
game.village_command(&["start"]).unwrap();
game.sim.tick = 60;
game.sim.sams[0].missiles = 2;
game.sim.target_health[1] = 80.0;
let saved = game.state_text(false, false);
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
game = restored;
let mut out = Out::default();
for wave in 0..WAVES {
let v = game.village.unwrap();
let Phase::Waiting { wave: index, until } = v.phase else {
panic!("{:?}", v.phase)
};
assert_eq!(index, wave);
assert_eq!(until - game.sim.tick, if wave == 0 { 40 } else { PAUSE });
game.sim.tick = until - 1;
game.tick_village(&mut out);
assert!(!game.sim.planning());
game.sim.tick = until;
game.tick_village(&mut out);
assert!(game.sim.planning());
assert_eq!(game.village.unwrap().phase, Phase::Fighting(wave));
assert!(deploy(&mut game, SamKind::Gepard).is_err());
// Complete the combat externally here to test the scenario transitions in isolation.
game.sim.clear();
game.sim.tick = game.sim.tick.div_ceil(20) * 20;
game.tick_village(&mut out);
assert_eq!(game.sim.sams[0].missiles, 2);
assert_eq!(game.sim.target_health, [100.0, 80.0, 100.0]);
}
assert_eq!(
game.village.unwrap().phase,
Phase::Finished([100.0, 80.0, 100.0])
);
assert!(game.village_status().contains("Победа · 94/100"));
game.sim.targets.clear();
game.sim.target_health.clear();
let mut restored = test_mod();
restored
.apply_state(&game.state_text(false, false))
.unwrap();
assert!(restored.village_status().contains("Победа · 94/100"));
assert!(
out.messages
.iter()
.any(|line| line.contains("/airdef breaches"))
);
}
#[test]
fn three_playable_rounds_finish_and_the_report_lists_real_impacts() {
struct Flat;
impl sim::world::WorldSource for Flat {
fn solid(&self, _: i32, y: i32, _: i32) -> Option<bool> {
Some(y < 64)
}
}
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::new(0.0, 64.0, 0.0))
.unwrap();
// Lay one battery and hold its fire so the mission reaches the report path.
game.sim.damage = false;
game.sim.hold = true;
let mut out = Out::default();
let mut wave_count = 0;
for _ in 0..9000 {
let now = game.sim.tick;
let columns = game
.ground
.take_wanted()
.into_iter()
.map(|(x, z)| (x, z, 64))
.collect();
game.ground.answer(columns, now);
let sections = game.ground.world.take_wanted(now);
game.ground.world.serve(&Flat, sections, now);
let rays = game.ground.world.take_rays(now);
game.ground.world.serve_rays(&Flat, rays);
game.ground.take_chunks();
game.sim.step(&mut game.ground, None, &mut out);
game.tick_village(&mut out);
let phase = game.village.unwrap().phase;
if phase == Phase::Setup {
deploy(&mut game, SamKind::Gepard).unwrap();
game.village_command(&["start"]).unwrap();
}
wave_count += out
.messages
.iter()
.filter(|m| m.starts_with("Оборона деревни · волна "))
.count();
if matches!(phase, Phase::Finished(_)) {
break;
}
out = Out::default();
}
assert_eq!(wave_count, 3);
assert!(matches!(game.village.unwrap().phase, Phase::Finished(_)));
assert!(game.sim.breakthrough_pages() > 0);
assert!(
game.sim
.breakthrough_page(0)
.contains("Снимок перед ударом")
);
}
#[test]
fn survey_uses_world_heights_and_score_weights_each_object() {
let mut game = test_mod();
game.request_village(Level::Easy, DVec3::ZERO).unwrap();
let mut out = Out::default();
game.tick_village(&mut out);
assert!(game.sim.targets.is_empty());
let wanted = game.ground.take_wanted();
assert_eq!(wanted.len(), 3);
game.ground.answer(
wanted
.into_iter()
.enumerate()
.map(|(i, (x, z))| (x, z, 64 + i as i32))
.collect(),
game.sim.tick,
);
game.tick_village(&mut out);
assert_eq!(
game.sim.targets.iter().map(|p| p.y).collect::<Vec<_>>(),
[64.0, 65.0, 66.0]
);
assert_eq!(score(&[0.0, 100.0, 100.0]), (50.0, false));
assert_eq!(score(&[90.0, 60.0, 10.0]), (65.0, true));
}
}
+14 -3
View File
@@ -172,7 +172,7 @@ impl WaveConfig {
#[cfg(test)] #[cfg(test)]
mod catalog_tests { mod catalog_tests {
use super::*; use super::*;
use crate::sim::catalog::{AIRCRAFT, UNITS}; use crate::sim::catalog::{AIRCRAFT, UNITS, VARIANTS};
fn assets() -> std::path::PathBuf { fn assets() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets/airdef") std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets/airdef")
@@ -215,15 +215,26 @@ mod catalog_tests {
for model in [p.launcher, p.pack, p.dish.map(|v| v.0), p.spinner.map(|v| v.0)].into_iter().flatten() { model_exists(model); } for model in [p.launcher, p.pack, p.dish.map(|v| v.0), p.spinner.map(|v| v.0)].into_iter().flatten() { model_exists(model); }
for (model, _, _) in p.fixed { model_exists(model); } for (model, _, _) in p.fixed { model_exists(model); }
} }
for variant in VARIANTS {
item_exists(variant.deploy_item);
}
} }
#[test] #[test]
fn inventory_entries_match_catalog_and_scenario_order_round_trips() { fn inventory_entries_match_catalog_and_scenario_order_round_trips() {
for item in AIRCRAFT.iter().filter_map(|a| a.launch_item).chain(UNITS.iter().map(|u| u.deploy_item)) { let catalogued = |item: &str| {
AIRCRAFT.iter().any(|a| a.launch_item == Some(item))
|| UNITS.iter().any(|u| u.deploy_item == item)
|| VARIANTS.iter().any(|v| v.deploy_item == item)
};
for item in AIRCRAFT.iter().filter_map(|a| a.launch_item)
.chain(UNITS.iter().map(|u| u.deploy_item))
.chain(VARIANTS.iter().map(|v| v.deploy_item))
{
assert_eq!(crate::ITEMS.iter().filter(|i| **i == item).count(), 1, "{item}"); assert_eq!(crate::ITEMS.iter().filter(|i| **i == item).count(), 1, "{item}");
} }
for item in crate::ITEMS.iter().filter(|i| i.starts_with("airdef:launch_") || i.starts_with("airdef:deploy_")) { for item in crate::ITEMS.iter().filter(|i| i.starts_with("airdef:launch_") || i.starts_with("airdef:deploy_")) {
assert!(AIRCRAFT.iter().any(|a| a.launch_item == Some(*item)) || UNITS.iter().any(|u| u.deploy_item == *item), "uncatalogued item {item}"); assert!(catalogued(item), "uncatalogued item {item}");
} }
let mut wave = WaveConfig::default(); let mut wave = WaveConfig::default();
for (i, count) in wave.counts.iter_mut().enumerate() { *count = i as u32; } for (i, count) in wave.counts.iter_mut().enumerate() { *count = i as u32; }
+452
View File
@@ -0,0 +1,452 @@
//! Local bridge for the optional web panel. The engine's control endpoint stays local.
//! Snapshot and receipt I/O runs on explicit commands, never inside a tick or frame hook.
use crate::{AirDef, Out, battery_view, player, post, sim, wave, why_view};
use glam::DVec3;
use horizon_mod_sdk::storage;
use serde_json::{Value, json};
use std::collections::{HashSet, VecDeque};
const SNAPSHOT: &str = "panel-snapshot-v1.json";
const RECEIPT: &str = "panel-receipt-v1.json";
// Leave space under Horizon's 1 MiB per-call storage budget for both debug views
// and incremental logs from the active recording and the three retained replays.
const ENTITY_LIMIT: usize = 256;
const LOG_BATCH: usize = 128;
const RECEIPT_LIMIT: usize = 64;
#[derive(Default)]
pub(super) struct Link {
session: String,
receipts: VecDeque<(String, Value)>,
}
fn token(s: &str) -> bool {
(16..=32).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_hexdigit())
}
fn position(id: impl Into<Value>, label: impl Into<Value>, p: DVec3) -> Value {
json!({ "id": id.into(), "label": label.into(), "x": p.x, "y": p.y, "z": p.z })
}
fn merge(row: &mut Value, fields: Value) {
row.as_object_mut()
.unwrap()
.extend(fields.as_object().unwrap().clone());
}
fn configs() -> Value {
let presets: Vec<_> = wave::PRESETS
.iter()
.enumerate()
.map(|(i, preset)| {
let mut w = wave::WaveConfig::default();
w.apply(i);
json!({
"name": preset.name, "counts": w.counts.to_vec(), "distance": w.dist,
"approach": sim::Approach::ALL.iter().position(|a| *a == w.approach).unwrap(),
"aim": sim::Aim::ALL.iter().position(|a| *a == w.aim).unwrap()
})
})
.collect();
json!({
"kinds": wave::KINDS.iter().map(|k| k.spec().name).collect::<Vec<_>>(),
"approaches": sim::Approach::ALL.map(sim::Approach::name),
"aims": sim::Aim::ALL.map(sim::Aim::name),
"distance": [wave::DIST_MIN, wave::DIST_MAX],
"presets": presets,
})
}
fn class_symbol(class: sim::Class) -> &'static str {
match class {
sim::Class::Drone => "drone",
sim::Class::Jet => "jet",
sim::Class::Cruise => "cruise",
sim::Class::Supersonic => "supersonic",
sim::Class::Ballistic => "ballistic",
}
}
fn contact_symbol(estimate: sim::ClassEst) -> &'static str {
match estimate {
sim::ClassEst::Firm(class) => class_symbol(class),
_ => "unknown",
}
}
fn public_live(sim: &sim::Sim) -> Value {
let now = sim.tick;
let picture = sim.air_picture();
// The local HUD has an unaided truth fallback. The web network view deliberately has none.
let mut known = HashSet::new();
let contacts: Vec<_> = picture.tracks.iter().take(ENTITY_LIMIT).filter(|_| !picture.unaided).map(|t| {
known.insert(t.id);
let mut row = position(t.id, t.class.name(), t.est(now));
merge(&mut row, json!({
"status": if t.forecast(now) { "Оценка положения" } else { "Измерено" },
"source": (t.source != 0).then_some(t.source), "age": t.age(now),
"quality": t.quality, "confidence": t.ident().name(), "radius": t.uncertainty(now),
"symbol": contact_symbol(t.class),
"vx": t.vel.x * 20.0, "vz": t.vel.z * 20.0,
}));
row
}).collect();
let units: Vec<_> = sim
.sams
.iter()
.take(ENTITY_LIMIT)
.enumerate()
.map(|(i, s)| {
let mut row = position(s.id, format!("№{} {}", i + 1, s.kind.name()), s.pos);
let emitting = s.radar_up();
let radar_range = emitting.then(|| s.kind.spec().sensor * s.radar_profile().reach);
merge(
&mut row,
json!({
"status": post::state(s), "details": battery_view::sam_status(s, now),
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
"symbol": if s.kind == sim::SamKind::Radar { "radar" } else { "unit" },
"radarRange": radar_range,
"target": s.target.or(s.gun_target).filter(|id| known.contains(id)),
}),
);
row
})
.collect();
let objects: Vec<_> = sim.targets.iter().take(ENTITY_LIMIT).enumerate().map(|(i, &p)| {
let mut row = position(i + 1, format!("Объект №{}", i + 1), p);
let health = sim.target_health.get(i).copied();
merge(&mut row, json!({ "health": health, "status": if health == Some(0.0) { "Уничтожен" } else { "Под защитой" } }));
row
}).collect();
let interceptors: Vec<_> = sim.missiles.iter().take(ENTITY_LIMIT).map(|m| {
let mut row = position(m.id, format!("Перехватчик №{}", m.id), m.pos);
merge(&mut row, json!({ "target": known.contains(&m.target()).then_some(m.target()), "status": "В полёте" }));
row
}).collect();
json!({
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors,
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold },
"limited": sim.sams.len() > ENTITY_LIMIT || (!picture.unaided && picture.tracks.len() > ENTITY_LIMIT)
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT
})
}
fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
if !debug {
return (Value::Null, Value::Null);
}
let report = sim.enemy_picture();
let observed: Vec<_> = report.observations.iter().take(ENTITY_LIMIT).map(|o| {
let mut row = position(o.id, o.kind.unwrap_or(o.category), o.at);
merge(&mut row, json!({
"status": format!("Донесение · {}", o.category), "confidence": format!("{:?}", o.confidence),
"radius": o.radius, "age": o.age, "source": o.channel, "quality": o.quality, "rank": o.rank,
}));
row
}).collect();
let reports: Vec<_> = report
.aims
.iter()
.filter(|a| a.unit != 0 && report.observations.iter().any(|o| o.id == a.unit))
.take(256)
.map(|a| json!({"contact": a.unit, "reason": a.intent, "at": a.since}))
.collect();
let sorties: Vec<_> = report
.recon_sorties
.iter()
.take(64)
.map(|r| json!({"phase": r.phase, "zones": r.zones_left, "reportIn": r.report_in}))
.collect();
let truth: Vec<_> = sim
.drones
.iter()
.filter(|d| d.alive())
.take(ENTITY_LIMIT)
.map(|d| {
let mut row = position(d.id, d.kind.spec().name, d.pos);
merge(
&mut row,
json!({"status": "Истина", "symbol": class_symbol(d.kind.spec().class), "vx": d.vel.x * 20.0, "vz": d.vel.z * 20.0}),
);
row
})
.collect();
(
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "reports": reports, "sorties": sorties,
"limited": report.observations.len() > ENTITY_LIMIT}),
json!(truth),
)
}
fn record_data(rec: &sim::record::Recording, cursor: (u64, usize, usize), active: bool) -> Value {
let first = rec.decisions.first_index();
let (dec, ev, sc) = cursor;
let decisions: Vec<_> = rec.decisions.entries().enumerate().skip(dec.saturating_sub(first) as usize).take(LOG_BATCH)
.map(|(i, &entry)| {
let choice = post::RecordedChoice { raid: rec.number, entry };
json!({ "seq": first + i as u64, "at": entry.at, "unit": entry.unit, "target": entry.target,
"label": post::decision_label(entry.outcome), "lines": post::decision_lines(choice, Some(rec)) })
}).collect();
let next_dec = decisions
.last()
.and_then(|d| d["seq"].as_u64())
.map_or(dec.max(first), |seq| seq + 1);
let mut next_ev = ev.min(rec.events.len());
let mut events = Vec::new();
for (i, event) in rec.events.iter().enumerate().skip(next_ev).take(LOG_BATCH) {
use sim::record::EventKind;
next_ev = i + 1;
let (label, unit, target, object) = match event.kind {
EventKind::Kill { sam, drone, .. } => ("Цель сбита", Some(sam), Some(drone), None),
EventKind::Hit {
drone,
object: Some(object),
..
} => ("Попадание по объекту", None, Some(drone), Some(object + 1)),
EventKind::Hit {
drone,
sam: Some((_, i)),
..
} => (
"Попадание по комплексу",
rec.sams.get(i).map(|s| s.0),
Some(drone),
None,
),
EventKind::SamLost { sam, .. } => ("Комплекс уничтожен", Some(sam), None, None),
_ => continue,
};
events.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "object": object, "label": label, "lines": [] }));
}
let mut observations = Vec::new();
let mut next_sc = sc;
if let Some(scene) = &rec.scene {
use sim::record::SceneKind::*;
next_sc = next_sc.min(scene.events().len());
for (i, event) in scene.events().iter().enumerate().skip(next_sc) {
next_sc = i + 1;
let (label, unit, target) = match event.kind {
TrackAcquired { sam, target, .. } => ("Отметка получена", sam, target),
TrackSource { sam, target, .. } => ("Изменился источник отметки", sam, target),
TrackLock {
sam,
target,
locked,
} => (
if locked {
"Контакт взят на сопровождение"
} else {
"Сопровождение прервано"
},
sam,
target,
),
TrackLost { sam, target } => ("Отметка потеряна", sam, target),
_ => continue,
};
observations.push(json!({ "seq": i, "at": event.at, "unit": unit, "target": target, "label": label, "lines": [] }));
if observations.len() == LOG_BATCH {
break;
}
}
}
json!({ "id": rec.number, "start": rec.started_at, "length": rec.len, "active": active,
"first": first, "gap": dec < first,
"limited": rec.decisions.truncated() || rec.scene.as_ref().is_some_and(|s| s.truncated || s.track_limit_reached()),
"next": [next_dec, next_ev as u64, next_sc as u64], "decisions": decisions, "events": events, "observations": observations })
}
fn cursors(raw: &str, session: &str, raid: u32) -> (u64, usize, usize) {
let Some((epoch, list)) = raw.split_once(':') else {
return (0, 0, 0);
};
if epoch != session {
return (0, 0, 0);
}
list.split(',')
.take(4)
.find_map(|s| {
let mut fields = s.split('.');
let number = fields.next()?.parse::<u32>().ok()?;
(number == raid).then_some((
fields.next()?.parse().ok()?,
fields.next()?.parse().ok()?,
fields.next().and_then(|n| n.parse().ok()).unwrap_or(0),
))
})
.unwrap_or_default()
}
fn parse_wave(raw: &str) -> Result<wave::WaveConfig, String> {
let chunks: Vec<_> = raw.split(':').collect();
let [a, d, aim, counts] = chunks.as_slice() else {
return Err("Неверный формат сценария".into());
};
let approach = a
.parse::<usize>()
.ok()
.and_then(|i| sim::Approach::ALL.get(i))
.ok_or("Неизвестный подход")?;
let aim = aim
.parse::<usize>()
.ok()
.and_then(|i| sim::Aim::ALL.get(i))
.ok_or("Неизвестная цель сценария")?;
let dist = d
.parse::<f64>()
.ok()
.filter(|x| (wave::DIST_MIN..=wave::DIST_MAX).contains(x))
.ok_or("Дальность вне диапазона")?;
let counts: Vec<u32> = counts
.split(',')
.map(str::parse)
.collect::<Result<_, _>>()
.map_err(|_| "Неверное количество")?;
if counts.len() != wave::KINDS.len()
|| counts.iter().any(|&n| n > 80)
|| counts.iter().all(|&n| n == 0)
{
return Err("Укажите допустимое количество аппаратов по каждому типу".into());
}
Ok(wave::WaveConfig {
counts: counts.try_into().unwrap(),
approach: *approach,
dist,
aim: *aim,
preset: 0,
})
}
impl AirDef {
pub(super) fn panel_command(&mut self, args: &[&str]) -> Result<Option<String>, String> {
match args {
["snapshot", nonce, privacy, raw]
if token(nonce) && matches!(*privacy, "public" | "debug") =>
{
let player = player().filter(|_| self.world.is_some()).ok_or("Откройте игровой мир")?;
if self.web.session.is_empty() {
self.web.session = nonce.to_string();
}
let session = &self.web.session;
let (enemy, truth) = perspectives(&self.sim, *privacy == "debug");
let raids: Vec<_> = self
.sim
.replays
.iter()
.map(|r| (r, false))
.chain(self.sim.recording().map(|r| (r, true)))
.map(|(r, active)| record_data(r, cursors(raw, session, r.number), active))
.collect();
let selected = self.monitor_index().and_then(|i| {
self.sim.battle_reason(i).map(|reason| {
json!({"unit": self.sim.sams[i].id, "reason": why_view::unit_headline(reason)})
})
});
let content = json!({
"version": 1, "nonce": nonce, "session": session, "world": self.state_key(), "terrainWorld": self.world, "tick": self.sim.tick,
"terrainDimension": player.dimension, "mapCenter": [player.x, player.z],
"live": public_live(&self.sim), "enemy": enemy, "truth": truth, "raids": raids, "catalog": configs(),
"selected": selected, "canLaunch": !self.sim.planning() && !self.village_active() && self.presentation.is_live(),
});
let bytes = serde_json::to_vec(&content).map_err(|e| e.to_string())?;
storage::set(SNAPSHOT, &bytes)?;
Ok(None)
}
["launch", id, session, wave] if token(id) => {
let receipt = if let Some((_, previous)) =
self.web.receipts.iter().find(|(key, _)| key == id)
{
previous.clone()
} else {
let result = self.panel_launch(session, wave);
let receipt = match result {
Ok(n) => {
json!({"id": id, "accepted": true, "message": format!("Игра приняла сценарий на {n} аппаратов")})
}
Err(error) => json!({"id": id, "accepted": false, "message": error}),
};
if self.web.receipts.len() == RECEIPT_LIMIT {
self.web.receipts.pop_front();
}
self.web
.receipts
.push_back((id.to_string(), receipt.clone()));
receipt
};
storage::set(
RECEIPT,
&serde_json::to_vec(&receipt).map_err(|e| e.to_string())?,
)?;
Ok(receipt["message"].as_str().map(str::to_owned))
}
_ => Err("Неизвестный запрос веб-пульта".into()),
}
}
fn panel_launch(&mut self, session: &str, raw: &str) -> Result<u32, String> {
if self.web.session.is_empty() || self.web.session != session {
return Err("Игровая сессия сменилась. Обновите карту".into());
}
if self.sim.planning() || self.village_active() || !self.presentation.is_live() {
return Err("В этом режиме нельзя запускать сценарий".into());
}
let p = player().ok_or("Игровой мир закрыт")?;
let wave = parse_wave(raw)?;
let objects = self.objects(DVec3::new(p.x, p.y, p.z));
let mut out = Out::default();
let n = self.sim.order_raid(&wave.order(), &objects, &mut out);
self.emit(out);
(n > 0)
.then_some(n)
.ok_or_else(|| "Игра не приняла сценарий".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_network_snapshot_has_no_truth_without_sensors() {
let mut sim = sim::Sim::new(1);
sim.launch(
sim::DroneKind::Shahed,
DVec3::X,
DVec3::Z,
DVec3::ZERO,
&mut Out::default(),
);
assert!(public_live(&sim)["contacts"].as_array().unwrap().is_empty());
let (_, truth) = perspectives(&sim, true);
assert_eq!(truth.as_array().unwrap().len(), 1);
assert!(perspectives(&sim, false).1.is_null());
}
#[test]
fn contact_symbol_requires_a_confirmed_class() {
use sim::{Class, ClassEst};
assert_eq!(contact_symbol(ClassEst::Unknown), "unknown");
assert_eq!(contact_symbol(ClassEst::Probable(Class::Cruise)), "unknown");
assert_eq!(contact_symbol(ClassEst::Firm(Class::Drone)), "drone");
assert_eq!(contact_symbol(ClassEst::Firm(Class::Cruise)), "cruise");
assert_eq!(contact_symbol(ClassEst::Firm(Class::Ballistic)), "ballistic");
}
#[test]
fn validates_wave_as_data_and_resets_cursors_between_game_sessions() {
let mut counts = vec!["0"; wave::KINDS.len()];
counts[0] = "2";
assert_eq!(
parse_wave(&format!("0:300:0:{}", counts.join(",")))
.unwrap()
.total(),
2
);
assert!(parse_wave("0:NaN:0:2").is_err());
assert!(parse_wave("0:300:0:1;clear").is_err());
assert_eq!(cursors("new:1.101.200.5,2.0.50.4", "new", 1), (101, 200, 5));
assert_eq!(cursors("old:1.101.200.5", "new", 1), (0, 0, 0));
}
}
+117 -1
View File
@@ -1,5 +1,5 @@
//! Text for diagnostics produced by the simulation. //! Text for diagnostics produced by the simulation.
use crate::sim::why::{CheckReason, PartEffect}; use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect};
use crate::sim::{Comps, Part, SamKind}; use crate::sim::{Comps, Part, SamKind};
fn part_value(part: Part, value: f64) -> String { fn part_value(part: Part, value: f64) -> String {
@@ -25,9 +25,91 @@ pub fn worst(comps: &Comps, kind: SamKind) -> String {
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default() .map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
} }
/// The mark's age and where it came from, in the battery's own picture: a relayed plot names
/// its station, never the target's true place or kind.
pub fn mark_text(mark: &BattleMark) -> String {
let age = if mark.age == 0 { "сейчас".to_string() } else { format!("{:.1} с назад", mark.age as f64 / 20.0) };
let source = if mark.own {
"своя РЛС".to_string()
} else {
mark.source.map_or_else(|| "сеть".to_string(), |i| format!("сеть, РЛС №{}", i + 1))
};
let mut own = String::new();
if let Some(product) = mark.own_product {
if !mark.own {
own = format!(", своё измерение: {}", product.name());
}
}
let forecast = if mark.forecast { ", прогноз" } else { "" };
format!(
"отметка {age}, источник {source}, {} кач.{} {}{}{forecast}",
mark.product.name(),
mark.quality,
mark.class.name(),
own
)
}
fn with_mark(text: String, mark: Option<BattleMark>) -> String {
match mark {
Some(mark) => format!("{text}: {}", mark_text(&mark)),
None => text,
}
}
/// The one headline reason a battery fires or not, as the player reads it.
pub fn battle_text(reason: &BattleReason) -> String {
match reason.kind {
BattleKind::Ready => with_mark("готов к пуску".into(), reason.mark),
BattleKind::ObserveOnly => with_mark("есть только обзор, пуск не разрешён — нужно своё подтверждённое измерение".into(), reason.mark),
BattleKind::AwaitingTrack => with_mark("ждёт сопровождения — своё измерение ещё не разрешает пуск".into(), reason.mark),
BattleKind::ChannelsBusy => {
let channels = reason.channels.map_or_else(|| "каналы заняты".to_string(), |(used, total)| format!("каналы заняты: {used}/{total}"));
with_mark(channels, reason.mark)
}
BattleKind::NoAmmo => {
let mut text = format!("нет боезапаса: ракет {}, очередей {}", reason.rounds, reason.bursts);
if reason.reloading > 0 {
text += &format!(", перезарядка ещё {:.1} с", reason.reloading as f64 / 20.0);
}
with_mark(text, reason.mark)
}
BattleKind::Blocked => {
let text = match reason.block {
Some(BattleBlock::Destroyed) => "уничтожен".to_string(),
Some(BattleBlock::Moving) => "на марше, не стреляет".to_string(),
Some(BattleBlock::Hold) => "огонь запрещён или роли не заданы".to_string(),
Some(BattleBlock::NoWeapon) => "нет оружия (РЛС, склад, РЭБ, прожектор)".to_string(),
Some(BattleBlock::NoTarget) => "нет целей в небе".to_string(),
Some(BattleBlock::NoTrack) => "цель не обнаружена своей РЛС или сетью".to_string(),
Some(BattleBlock::ClassPending) => "ждёт подтверждения класса цели".to_string(),
Some(BattleBlock::OutOfRoles) => "цель вне ролей комплекса".to_string(),
Some(BattleBlock::OutOfReach) => "цель вне дальности".to_string(),
Some(BattleBlock::Claimed) => "цель уже занята перехватчиками".to_string(),
Some(BattleBlock::Doctrine) => "запрещено доктриной (сектор, охрана или резерв)".to_string(),
Some(BattleBlock::Aiming) => "ещё доворачивается на цель".to_string(),
Some(BattleBlock::Preparing) => "открывает ТПК".to_string(),
Some(BattleBlock::LauncherDown) => "пусковая отказала".to_string(),
Some(BattleBlock::Other) | None => "стрелять сейчас не может".to_string(),
};
with_mark(text, reason.mark)
}
}
}
/// A card can be opened in normal play, where an unobserved contact is absent from the UI.
pub fn unit_headline(mut reason: BattleReason) -> String {
if reason.mark.is_none() && (reason.target.is_some() || reason.block == Some(BattleBlock::NoTarget)) {
return "нет отметки у комплекса".into();
}
reason.mark = None;
battle_text(&reason)
}
pub fn reason(reason: &CheckReason) -> String { pub fn reason(reason: &CheckReason) -> String {
match reason { match reason {
CheckReason::Text(text) => text.clone(), CheckReason::Text(text) => text.clone(),
CheckReason::Battle(battle) => battle_text(battle),
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")), CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
CheckReason::PartEffect(effect) => match effect { CheckReason::PartEffect(effect) => match effect {
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(), PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
@@ -79,6 +161,40 @@ mod tests {
assert!(summary < sensor && sensor < tracks, "{lines:?}"); assert!(summary < sensor && sensor < tracks, "{lines:?}");
} }
#[test]
fn the_headline_reason_shows_the_marks_age_and_source_without_the_true_kind() {
use crate::sim::battery::Measure;
use crate::sim::ClassEst;
let mark = BattleMark {
age: 46,
own_age: None,
source: Some(2),
own: false,
product: Measure::Search,
quality: 40,
own_product: None,
forecast: false,
class: ClassEst::Unknown,
};
let reason = BattleReason {
kind: BattleKind::ObserveOnly,
block: None,
sam: 0,
target: Some(7),
mark: Some(mark),
rounds: 4,
bursts: 0,
reloading: 0,
channels: None,
};
let text = battle_text(&reason);
assert!(text.starts_with("есть только обзор"), "{text}");
assert!(text.contains("2.3 с назад"), "{text}");
assert!(text.contains("источник сеть, РЛС №3"), "{text}");
assert!(text.contains("тип не определён"), "{text}");
assert!(!text.contains("Шахед"), "the true kind leaked into the HUD: {text}");
}
#[test] #[test]
fn renders_damage_diagnostics() { fn renders_damage_diagnostics() {
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ"); assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
+10 -3
View File
@@ -1016,7 +1016,9 @@ frames = 10
[[step]] [[step]]
command = "airdef stats" command = "airdef stats"
expect.feedback = "В воздухе: 184, ракет: 10, ПВО: 64, сбито: 777, поражений: 1499, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 5353 секций (250 КБ), запросов 14405, неизвестно 0, лучей 327428 (ударов 6746, неизв. 213), клеток 2282312; взрывы в блоках: 1586 (подтверждено 0, без перемен 175, нет чанка 1330), чужих ответов 0" # Finite-ammunition checkpoint after extending the game ranges. With no depot,
# the two waves exhaust the initial stock. The previous baseline used free reloads.
expect.feedback = "В воздухе: 184, ракет: 0, ПВО: 64, сбито: 132, поражений: 2199, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4785 секций (224 КБ), запросов 12079, неизвестно 0, лучей 307306 (ударов 822, неизв. 152), клеток 1960898; взрывы в блоках: 2214 (подтверждено 0, без перемен 83, нет чанка 1989), чужих ответов 0"
# The Windows #122 path: a Smart order through the UI launch function (`airdef raid` # The Windows #122 path: a Smart order through the UI launch function (`airdef raid`
# is the wave screen's ПУСК button handler) with a fat intel log and EW up — twice. # is the wave screen's ПУСК button handler) with a fat intel log and EW up — twice.
@@ -1041,7 +1043,9 @@ expect.feedback = "Готовый: Массированный удар"
[[step]] [[step]]
command = "airdef raid" command = "airdef raid"
expect.chat = [] # A Smart order sends a recon flight ahead of the strike (#135): the wave screen's ПУСК handler
# reports it. The empty-chat expectation predates #135 and stopped the scenario here (#145).
expect.chat = ["Разведка противника: впереди налёта высланы разведчики"]
[[step]] [[step]]
ticks = 400 ticks = 400
@@ -1061,4 +1065,7 @@ frames = 100
[[step]] [[step]]
command = "airdef stats" command = "airdef stats"
expect.feedback = "В воздухе: 11, ракет: 3, ПВО: 68, сбито: 936, поражений: 1853, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 6643 секций (311 КБ), запросов 17355, неизвестно 0, лучей 393828 (ударов 9283, неизв. 978), клеток 2953257; взрывы в блоках: 1961 (подтверждено 0, без перемен 234, нет чанка 1727), чужих ответов 0" # The two late Smart raids also run with finite stock. At this point the
# launchers still have no supply depot.
# The late Smart orders use the coarse observation picture from #135.
expect.feedback = "В воздухе: 25, ракет: 0, ПВО: 68, сбито: 133, поражений: 2730, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7309 секций (342 КБ), запросов 16741, неизвестно 0, лучей 406150 (ударов 2235, неизв. 1073), клеток 3915183; взрывы в блоках: 2829 (подтверждено 0, без перемен 165, нет чанка 2664), чужих ответов 0"
+248
View File
@@ -0,0 +1,248 @@
//! The fullscreen-map OOM replica (the `Ground::answer` rehash crash): a large raid watched
//! from all sides through a long session, with the wide ground-query pattern the command map
//! adds on top of the simulation's own. 64 integrated complexes stand where `/airdef deploy`
//! puts them; `airdef wave oreshnik 12 2600` orders come from all sides every 1500 ticks (six
//! raids, so recordings close and the kept replays pile up), and a smart raid maps its whole
//! grid. The render answers are produced exactly as the WASM test host produces them
//! (`horizon_mods::world_query::trace`, flat land at y=64). While the fight runs, a map pass
//! every other tick (the map's redraw pace) sweeps ground queries over a wide view — the
//! fullscreen map asks for the land under its whole grid, not just the flights' columns.
//!
//! The test measures what each consumer holds (`Sim::memory`) through the session, asserts the
//! peak fits the 64 MiB WASM linear memory with headroom for a hashbrown rehash transient, and
//! that the fight still resolves: intercepts happen, the sky clears, and the same seed replays
//! the same ordered combat trace.
//!
//! Run: `cargo test --test ground_oom -- --nocapture`.
use airdef::sim::world::{Fill, RayReply, SectionAnswer};
use airdef::sim::{Aim, Approach, DroneKind, Ground, MemoryReport, Out, RaidOrder, Sam, SamKind, Sim};
use glam::DVec3;
use horizon_mods::world_query::{self, BlockProbe, Cell, Trace};
/// The seed the mod derives on the first tick of a fresh world (`open_world`, game_time 1).
const SEED: u64 = 1u64.wrapping_mul(2654435761) ^ 0x9e37;
const PLAYER: DVec3 = DVec3::new(0.5, 64.0, 0.5);
const DEPLOY_AT: DVec3 = DVec3::new(0.5, 64.0, 8.5);
const GROUND_Y: i32 = 64;
const KINDS: [SamKind; 7] = [SamKind::S400, SamKind::Patriot, SamKind::Pantsir, SamKind::Gepard, SamKind::Nasams, SamKind::IrisT, SamKind::Tor];
/// The engine's cap on a mod's linear memory (`horizon-mods` runtime `MEMORY`).
const WASM_MEMORY: usize = 512 << 20;
/// The peak the mod's own bounds keep it under (well inside the cap): headroom for the allocator,
/// the transient query/answer vectors and save serialization on top of the measured steady state.
const PEAK_BUDGET: usize = 48 << 20;
/// Six raids fought out, recordings closed and replays kept; long enough for the caches to fill.
const TICKS: u64 = 10_000;
struct Flat;
impl BlockProbe for Flat {
fn cell(&mut self, _x: i32, y: i32, _z: i32) -> Cell<'_> {
if y < GROUND_Y { Cell::Solid(None) } else { Cell::Empty }
}
}
fn section_fill(sec: (i32, i32, i32)) -> SectionAnswer {
let base = i64::from(sec.1) * 16;
let solid = (i64::from(GROUND_Y) - base).clamp(0, 16) as usize;
let fill = match solid {
0 => Fill::Empty,
16 => Fill::Full,
_ => {
let mut bits = [0u8; 512];
bits[..solid * 32].fill(255);
Fill::Mixed(Box::new(bits))
}
};
SectionAnswer { sec, fill }
}
fn ray_reply(id: u32, a: DVec3, b: DVec3) -> RayReply {
match world_query::trace(&mut Flat, [a.x, a.y, a.z], [b.x, b.y, b.z]) {
Trace::Clear => RayReply { id, clear: true, hit: false, fraction: 1.0, normal: [0; 3], block: [0; 3] },
Trace::Hit { fraction, normal, block } => RayReply { id, clear: false, hit: true, fraction, normal, block },
Trace::Unknown { .. } => RayReply { id, clear: false, hit: false, fraction: 0.0, normal: [0; 3], block: [0; 3] },
}
}
fn wave(sim: &mut Sim, out: &mut Out, count: u32, aim: Aim) -> u32 {
let o = RaidOrder { kinds: vec![(DroneKind::Oreshnik, count)], approach: Approach::AllSides, dist: 2600.0, aim };
sim.order_raid(&o, &[PLAYER], out)
}
fn deploy(sim: &mut Sim) {
for _ in 0..9 {
for kind in KINDS {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
}
}
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
assert_eq!(sim.sams.len(), 64);
}
/// One run of the heavy session: the combat trace (ordered, for the determinism check), the
/// peak memory report and the counters at the end.
struct Run {
trace: Vec<(u64, u32, u32, usize)>,
peak: MemoryReport,
peak_total: usize,
peak_known: usize,
peak_airborne: usize,
sim: Sim,
}
fn run() -> Run {
// Six raids 1500 ticks apart: the sky clears between them, so recordings close and the
// kept replays pile up (the journal's and the poses' budgets are per recording).
run_with(&[(3, 12, Aim::Objects), (1503, 12, Aim::Objects), (3003, 12, Aim::Objects), (4503, 12, Aim::Objects), (6003, 12, Aim::Objects), (7503, 12, Aim::Objects), (1203, 10, Aim::Smart)], TICKS, false)
}
/// The extreme continuous load: waves overlap, the sky never clears, one recording runs long
/// and the flight tracks reach their points budget (the thinning), with over a thousand objects
/// airborne at once — well past the crash's >200.
fn run_extreme() -> Run {
run_with(&[(3, 40, Aim::Objects), (103, 40, Aim::Objects), (203, 40, Aim::Objects), (1003, 40, Aim::Objects), (2003, 40, Aim::Objects), (3003, 40, Aim::Objects), (4003, 40, Aim::Objects), (5003, 40, Aim::Objects)], 8000, true)
}
fn run_with(waves: &[(u64, u32, Aim)], ticks: u64, sustained_supply: bool) -> Run {
let mut sim = Sim::new(SEED);
let mut ground = Ground::default();
let mut out = Out::default();
let mut columns: Vec<(i32, i32, i32)> = Vec::new();
let mut sections: Vec<SectionAnswer> = Vec::new();
let mut rays: Vec<RayReply> = Vec::new();
let mut changes_epoch = 0u32;
let mut run = Run { trace: Vec::new(), peak: MemoryReport::default(), peak_total: 0, peak_known: 0, peak_airborne: 0, sim: Sim::new(SEED) };
for now in 1..=ticks {
if now == 3 {
deploy(&mut sim);
if sustained_supply {
// Sustained fire needs physical stock under finite ammunition rules.
for _ in 0..3 {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Depot, DEPLOY_AT, 0.0));
}
}
}
for &(at, count, aim) in waves {
if now == at {
assert!(wave(&mut sim, &mut out, count, aim) > 0, "wave at tick {now} was refused");
}
}
if now == 1103 {
sim.shader = true;
}
let now0 = sim.tick;
ground.world.changed_rev(changes_epoch, 0, false, &[]);
ground.answer(std::mem::take(&mut columns), now0);
ground.world.answer(std::mem::take(&mut sections), now0);
ground.world.answer_rays(&std::mem::take(&mut rays));
sim.day_time = Some(now);
sim.night = (13000..23000).contains(&(now % 24000));
out = Out::default();
sim.step(&mut ground, Some(PLAYER), &mut out);
// The fullscreen map redraws every other tick and asks for the land under its grid:
// a wide walk over the view (32 fresh columns a redraw), as panning and placing do.
if now % 2 == 0 {
let t = now as f64;
let x0 = (t * 13.37).rem_euclid(8000.0) - 4000.0;
let z0 = (t * 7.91).rem_euclid(8000.0) - 4000.0;
for k in 0..32 {
let _ = ground.at(DVec3::new(x0 + k as f64 * 8.0, 0.0, z0 + k as f64 * 3.0), sim.tick);
}
}
columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, GROUND_Y)).collect();
let _chunks = ground.take_chunks();
let rq = ground.world.take_rays(now);
let sq = ground.world.take_wanted(now);
if !rq.is_empty() || !sq.is_empty() {
changes_epoch = 1;
}
rays = rq.into_iter().map(|(id, a, b)| ray_reply(id, a, b)).collect();
sections = sq.into_iter().map(section_fill).collect();
let airborne = sim.drones.iter().filter(|d| d.alive()).count();
run.peak_airborne = run.peak_airborne.max(airborne);
run.peak_known = run.peak_known.max(ground.known_len());
if now % 100 == 0 {
let m = sim.memory(&ground);
let total = m.total();
if total > run.peak_total {
run.peak_total = total;
run.peak = m;
}
run.trace.push((now, sim.kills, sim.hits, airborne));
}
}
run.sim = sim;
run
}
#[test]
fn the_heavy_map_session_fits_the_memory_budget_and_the_fight_resolves() {
let run = run();
let m = run.peak;
eprintln!("peak airborne {}, peak known columns {}", run.peak_airborne, run.peak_known);
eprintln!("peak memory at the worst sample:\n{}", m.text());
if let Some(rec) = run.sim.recording() {
let (tracks, journal, poses, misc) = rec.memory_parts();
eprintln!("live recording: tracks {:.2} MiB, journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
}
for (i, rec) in run.sim.replays.iter().enumerate() {
let (tracks, journal, poses, misc) = rec.memory_parts();
eprintln!("replay {}: len {} ticks, tracks {:.2} MiB, journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", i + 1, rec.len, tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
}
eprintln!(
"end: tick {}, kills {}, hits {}, crashes {}, airborne {}, replays {}",
run.sim.tick,
run.sim.kills,
run.sim.hits,
run.sim.crashes,
run.sim.drones.iter().filter(|d| d.alive()).count(),
run.sim.replays.len()
);
// The load is the crash's load: a large raid, more than 200 objects in the sky at once.
assert!(run.peak_airborne > 200, "the replica never reached the crash's load: {}", run.peak_airborne);
// The fight resolves: intercepts happen and the sky clears by the end of the session.
assert!(run.sim.kills > 100, "the defence stopped intercepting: {}", run.sim.kills);
assert_eq!(run.sim.drones.iter().filter(|d| d.alive()).count(), 0, "the raid never fought out");
// The memory budget: the steady peak plus the worst rehash transient (the old and the new
// table of the biggest map held at once) stays under the headroom target, far under the cap.
let peak = run.peak_total + m.rehash_headroom();
assert!(peak < PEAK_BUDGET, "peak {} MiB (steady {} + rehash {}) over the {} MiB budget:\n{}", peak >> 20, run.peak_total >> 20, m.rehash_headroom() >> 20, PEAK_BUDGET >> 20, m.text());
assert!(peak < WASM_MEMORY, "peak {} MiB over the engine's {} MiB cap", peak >> 20, WASM_MEMORY >> 20);
}
#[test]
fn the_same_seed_replays_the_same_ordered_combat_trace() {
let a = run();
let b = run();
assert_eq!(a.trace, b.trace, "the combat trace diverged between identical runs");
assert_eq!(a.sim.kills, b.sim.kills);
assert_eq!(a.sim.hits, b.sim.hits);
assert_eq!(a.sim.tally.text(), b.sim.tally.text());
assert_eq!(a.peak_known, b.peak_known);
}
#[test]
fn the_continuous_extreme_load_stays_bounded_and_thins_its_tracks() {
let run = run_extreme();
let m = run.peak;
eprintln!("extreme: peak airborne {}, peak known columns {}", run.peak_airborne, run.peak_known);
eprintln!("extreme peak memory:\n{}", m.text());
eprintln!("extreme end: kills {}, hits {}, airborne {}", run.sim.kills, run.sim.hits, run.sim.drones.iter().filter(|d| d.alive()).count());
// Well past the crash's load: the radar picture itself scales with the sky, and the
// recording's tracks must thin under their points budget rather than grow without bound.
assert!(run.peak_airborne > 1000, "the extreme load never materialised: {}", run.peak_airborne);
assert!(run.sim.kills > 100, "the defence stopped intercepting: {}", run.sim.kills);
let rec = run.sim.recording().or_else(|| run.sim.replays.last()).expect("the raid was recorded");
let (tracks, journal, poses, misc) = rec.memory_parts();
let points: usize = rec.tracks.iter().map(|t| t.points_len()).sum();
let max_step = rec.tracks.iter().map(|t| t.step()).max().unwrap_or(0);
eprintln!("extreme recording: len {} ticks, tracks {:.2} MiB ({points} points, max step {max_step}), journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", rec.len, tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
assert!(max_step > airdef::sim::record::STEP, "the points budget never thinned the tracks");
let peak = run.peak_total + m.rehash_headroom();
assert!(peak < PEAK_BUDGET, "extreme peak {} MiB over the {} MiB budget:\n{}", peak >> 20, PEAK_BUDGET >> 20, m.text());
}
+170
View File
@@ -0,0 +1,170 @@
//! The saturation regression (#145): a deterministic native replica of the WASM budget
//! scenario's checkpoint (`tests/budgets/wasm_flat_budget.toml`, tick 2102). 64 integrated
//! complexes stand where `/airdef deploy` puts them (8 blocks south of the player at the world
//! origin), two `airdef wave oreshnik 40 2600` orders 100 ticks apart, flat land at y=64, the
//! engine's own seed for the first morning. The render answers are produced exactly as the WASM
//! test host produces them (`horizon_mods::world_query::trace`, the same section fill), so the
//! replica replays the same fight the heavy run measures. It exists to explain and guard the
//! intercept count under saturation: the counters and `Sim::launch_audit` say why the systems
//! hold their fire, which the fuel-bound WASM run cannot afford to diagnose per tick.
//!
//! Run: `cargo test --test saturation -- --nocapture`.
use airdef::sim::world::{Fill, RayReply, SectionAnswer};
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sam, SamKind, Sim};
use glam::DVec3;
use horizon_mods::world_query::{self, BlockProbe, Cell, Trace};
/// The seed the mod derives on the first tick of a fresh world (`open_world`, game_time 1).
const SEED: u64 = 1u64.wrapping_mul(2654435761) ^ 0x9e37;
/// Where the test player stands, and where every deploy lands (`deploy_configured`: 8 blocks ahead).
const PLAYER: DVec3 = DVec3::new(0.5, 64.0, 0.5);
const DEPLOY_AT: DVec3 = DVec3::new(0.5, 64.0, 8.5);
const GROUND_Y: i32 = 64;
/// The fixture's deploy order: nine rounds of seven kinds, then one more S-400 (64 complexes).
const KINDS: [SamKind; 7] = [SamKind::S400, SamKind::Patriot, SamKind::Pantsir, SamKind::Gepard, SamKind::Nasams, SamKind::IrisT, SamKind::Tor];
/// The checkpoint the WASM fixture asserts at step 271.
const CHECKPOINT: u64 = 2102;
/// The flat world the test host answers from: solid below `GROUND_Y`, air above.
struct Flat;
impl BlockProbe for Flat {
fn cell(&mut self, _x: i32, y: i32, _z: i32) -> Cell<'_> {
if y < GROUND_Y { Cell::Solid(None) } else { Cell::Empty }
}
}
/// A section's fill, exactly as `answer_flat_world` computes it.
fn section_fill(sec: (i32, i32, i32)) -> SectionAnswer {
let base = i64::from(sec.1) * 16;
let solid = (i64::from(GROUND_Y) - base).clamp(0, 16) as usize;
let fill = match solid {
0 => Fill::Empty,
16 => Fill::Full,
_ => {
let mut bits = [0u8; 512];
bits[..solid * 32].fill(255);
Fill::Mixed(Box::new(bits))
}
};
SectionAnswer { sec, fill }
}
/// A ray's reply, exactly as `answer_flat_world` traces it.
fn ray_reply(id: u32, a: DVec3, b: DVec3) -> RayReply {
match world_query::trace(&mut Flat, [a.x, a.y, a.z], [b.x, b.y, b.z]) {
Trace::Clear => RayReply { id, clear: true, hit: false, fraction: 1.0, normal: [0; 3], block: [0; 3] },
Trace::Hit { fraction, normal, block } => RayReply { id, clear: false, hit: true, fraction, normal, block },
Trace::Unknown { .. } => RayReply { id, clear: false, hit: false, fraction: 0.0, normal: [0; 3], block: [0; 3] },
}
}
fn order(sim: &mut Sim, out: &mut Out) -> u32 {
let o = RaidOrder { kinds: vec![(DroneKind::Oreshnik, 40)], approach: Approach::Sector, dist: 2600.0, aim: Aim::Objects };
sim.order_raid(&o, &[PLAYER], out)
}
fn deploy(sim: &mut Sim) {
for _ in 0..9 {
for kind in KINDS {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
}
}
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
assert_eq!(sim.sams.len(), 64);
}
/// Steps the replica to `ticks`, ordering the two waves and the HD effects where the fixture does,
/// and answering render queries one tick later exactly as the WASM host does.
fn run_to(ticks: u64) -> Sim {
let mut sim = Sim::new(SEED);
let mut ground = Ground::default();
let mut out = Out::default();
let mut columns: Vec<(i32, i32, i32)> = Vec::new();
let mut sections: Vec<SectionAnswer> = Vec::new();
let mut rays: Vec<RayReply> = Vec::new();
let mut changes_epoch = 0u32;
for now in 1..=ticks {
// Commands run between ticks: deploys and the first wave after tick 2, the second after
// tick 102, `airdef shader hd` after tick 1102 (effects only, but kept exact).
if now == 3 {
deploy(&mut sim);
assert!(order(&mut sim, &mut out) > 0, "the first wave was refused");
}
if now == 103 {
assert!(order(&mut sim, &mut out) > 0, "the second wave was refused (the first still planning)");
}
if now == 1103 {
sim.shader = true;
}
// The mod's tick reads the previous tick's answers at the clock it had then (sim.tick).
let now0 = sim.tick;
ground.world.changed_rev(changes_epoch, 0, false, &[]);
ground.answer(std::mem::take(&mut columns), now0);
ground.world.answer(std::mem::take(&mut sections), now0);
ground.world.answer_rays(&std::mem::take(&mut rays));
sim.day_time = Some(now);
sim.night = (13000..23000).contains(&(now % 24000));
out = Out::default();
sim.step(&mut ground, Some(PLAYER), &mut out);
// The queries this tick asks; the host answers them before the next tick.
columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, GROUND_Y)).collect();
let _chunks = ground.take_chunks();
let rq = ground.world.take_rays(now);
let sq = ground.world.take_wanted(now);
if !rq.is_empty() || !sq.is_empty() {
changes_epoch = 1;
}
rays = rq.into_iter().map(|(id, a, b)| ray_reply(id, a, b)).collect();
sections = sq.into_iter().map(section_fill).collect();
}
sim
}
/// No depot is deployed in this fixture. Both waves spend the initial ammunition;
/// the checkpoint records the outcome with finite magazines and the heavy batteries'
/// confirmed-class engagement rules.
const REPLICA_KILLS: u32 = 129;
const REPLICA_HITS: u32 = 2202;
const REPLICA_AIRBORNE: usize = 184;
const REPLICA_FIRED: u32 = 344;
#[test]
fn checkpoint_replica_matches_the_finite_ammunition_baseline() {
let sim = run_to(CHECKPOINT);
let airborne = sim.drones.iter().filter(|d| d.alive()).count();
let fired: u32 = sim.sams.iter().map(|s| s.fired).sum();
eprintln!(
"checkpoint tick {}: airborne {airborne}, missiles {}, kills {}, hits {}, fired {}",
sim.tick,
sim.missiles.len(),
sim.kills,
sim.hits,
fired
);
eprintln!("tally: {}", sim.tally.text());
eprintln!("audit: {}", sim.launch_audit().text());
assert_eq!(airborne, REPLICA_AIRBORNE, "the sky at the checkpoint");
assert_eq!(sim.kills, REPLICA_KILLS, "intercepts at the checkpoint (deterministic replica baseline)");
assert_eq!(sim.hits, REPLICA_HITS, "hits at the checkpoint");
assert_eq!(fired, REPLICA_FIRED, "launches at the checkpoint");
assert!(sim.sams.iter().all(|s| s.fired <= s.kind.missile_magazine().unwrap_or(0)),
"a battery fired more than its initial load with no depot");
}
#[test]
fn the_saturation_loadout_has_no_separate_radar_channels_to_hold() {
// #140 (stale own fire channels held by network relays) is a separate-radar bug: it binds only
// where a profile has channels. This loadout deploys integrated complexes alone — every radar
// is the weapon's embedded one, whose profile has no channel limit — so #140 cannot affect it.
// Fact, not assumption: the A/B that relaxed the channel limit changed nothing (243 -> 243).
let sim = run_to(CHECKPOINT);
assert_eq!(sim.sams.len(), 64);
for s in &sim.sams {
assert_ne!(s.kind, SamKind::Radar, "the fixture deploys no separate radar");
assert_eq!(s.radar_profile().channels, 0, "an embedded radar has no channel limit");
}
}
+62
View File
@@ -0,0 +1,62 @@
# The scenario through the real mod command and world-query boundary.
[[step]]
ticks = 2
expect.commands = ["airdef"]
[[step]]
player = { x = 0.5, y = 64.0, z = 0.5 }
command = "airdef target here"
[[step]]
player = { x = 48.5, y = 64.0, z = 12.5 }
command = "airdef target here"
[[step]]
player = { x = -34.5, y = 64.0, z = -31.5 }
command = "airdef target here"
[[step]]
command = "airdef scenario village normal"
[[step]]
command = "airdef scenario village status"
expect.feedback = "Оборона деревни · расставьте технику, затем начните оборону · бюджет 25/25\nШтаб 100% · Лазарет 100% · Укрытие 100%"
[[step]]
command = "airdef deploy s400"
[[step]]
command = "airdef deploy s400"
[[step]]
command = "airdef deploy s400"
[[step]]
command = "airdef deploy s400"
[[step]]
command = "airdef deploy s500"
expect.error = "На эту технику нужно 6 очк., доступно 5"
[[step]]
command = "airdef scenario village start"
[[step]]
ticks = 101
[[step]]
command = "airdef scenario village status"
expect.feedback = "Оборона деревни · идёт волна 1/3 · бюджет 5/25\nШтаб 100% · Лазарет 100% · Укрытие 100%"
[[step]]
command = "airdef repair"
expect.error = "Это действие доступно после завершения или остановки «Обороны деревни»"
[[step]]
command = "airdef breaches"
expect.feedback = "Прорывов в истории нет"
[[step]]
command = "airdef scenario village stop"
expect.feedback = "Сценарий остановлен. Расстановка и текущий налёт остаются в мире"
+4 -2
View File
@@ -50,13 +50,15 @@ expect.feedback = "№2 С-400: режим launcher"
[[step]] [[step]]
command = "airdef deploy radar_track" command = "airdef deploy radar_track"
# The profile is chosen at deployment (#134): the old role switch is refused,
# and says where the profile comes from instead of retuning the station.
[[step]] [[step]]
command = "airdef radar 4 search" command = "airdef radar 4 search"
expect.feedback = "№4 РЛС: роль search" expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
[[step]] [[step]]
command = "airdef radar 4 engagement" command = "airdef radar 4 engagement"
expect.feedback = "№4 РЛС: роль engagement" expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
[[step]] [[step]]
command = "airdef radar 4 off" command = "airdef radar 4 off"
+10 -332
View File
@@ -1,137 +1,4 @@
{ {
"aircraft": [
{
"kind": "Gerbera",
"item": null,
"raid": true
},
{
"kind": "Shahed",
"item": "launch_shahed",
"raid": true
},
{
"kind": "Geran3",
"item": "launch_geran3",
"raid": true
},
{
"kind": "Lancet",
"item": "launch_lancet",
"raid": true
},
{
"kind": "Kh101",
"item": "launch_kh101",
"raid": true
},
{
"kind": "Kalibr",
"item": "launch_kalibr",
"raid": true
},
{
"kind": "Kh22",
"item": "launch_kh22",
"raid": true
},
{
"kind": "Zircon",
"item": "launch_zircon",
"raid": true
},
{
"kind": "Iskander",
"item": "launch_iskander",
"raid": true
},
{
"kind": "Kinzhal",
"item": "launch_kinzhal",
"raid": true
},
{
"kind": "Oreshnik",
"item": "launch_oreshnik",
"raid": true
},
{
"kind": "OreshnikBlock",
"item": null,
"raid": false
},
{
"kind": "OreshnikSub",
"item": null,
"raid": false
}
],
"units": [
{
"kind": "Patriot",
"item": "deploy_patriot"
},
{
"kind": "Gepard",
"item": "deploy_gepard"
},
{
"kind": "Pantsir",
"item": "deploy_pantsir"
},
{
"kind": "S400",
"item": "deploy_s400"
},
{
"kind": "S500",
"item": "deploy_s500"
},
{
"kind": "IrisT",
"item": "deploy_irist"
},
{
"kind": "Nasams",
"item": "deploy_nasams"
},
{
"kind": "Buk",
"item": "deploy_buk"
},
{
"kind": "Tor",
"item": "deploy_tor"
},
{
"kind": "P1sun",
"item": "deploy_p1sun"
},
{
"kind": "Radar",
"item": "deploy_radar"
},
{
"kind": "Depot",
"item": "deploy_depot"
},
{
"kind": "Tzm",
"item": "deploy_tzm"
},
{
"kind": "Ew",
"item": "deploy_ew"
},
{
"kind": "Light",
"item": "deploy_light"
},
{
"kind": "Optical",
"item": "deploy_optical"
}
],
"variants": [ "variants": [
{ {
"id": "s400_launcher", "id": "s400_launcher",
@@ -185,53 +52,8 @@
] ]
}, },
{ {
"id": "launch_shahed", "id": "deploy_s400_launcher",
"title": "Пуск: Шахед-136", "title": "Развернуть С-400 (пусковая)",
"color": [
90,
92,
96
]
},
{
"id": "launch_geran3",
"title": "Пуск: Герань-3",
"color": [
30,
30,
34
]
},
{
"id": "deploy_patriot",
"title": "Развернуть Patriot",
"color": [
76,
86,
58
]
},
{
"id": "deploy_gepard",
"title": "Развернуть Гепард",
"color": [
104,
84,
54
]
},
{
"id": "deploy_pantsir",
"title": "Развернуть Панцирь-С1",
"color": [
82,
96,
60
]
},
{
"id": "deploy_s400",
"title": "Развернуть С-400",
"color": [ "color": [
60, 60,
80, 80,
@@ -239,8 +61,8 @@
] ]
}, },
{ {
"id": "deploy_s500", "id": "deploy_s500_launcher",
"title": "Развернуть С-500", "title": "Развернуть С-500 (пусковая)",
"color": [ "color": [
108, 108,
110, 110,
@@ -248,53 +70,8 @@
] ]
}, },
{ {
"id": "launch_lancet", "id": "deploy_radar_search",
"title": "Пуск: Ланцет-3", "title": "Развернуть РЛС обзора",
"color": [
70,
78,
66
]
},
{
"id": "launch_kh101",
"title": "Пуск: Х-101",
"color": [
84,
88,
92
]
},
{
"id": "launch_kalibr",
"title": "Пуск: Калибр",
"color": [
150,
154,
156
]
},
{
"id": "launch_kh22",
"title": "Пуск: Х-22",
"color": [
226,
228,
222
]
},
{
"id": "launch_zircon",
"title": "Пуск: Циркон",
"color": [
52,
54,
52
]
},
{
"id": "launch_iskander",
"title": "Пуск: Искандер-М",
"color": [ "color": [
108, 108,
110, 110,
@@ -302,53 +79,8 @@
] ]
}, },
{ {
"id": "launch_kinzhal", "id": "deploy_radar_track",
"title": "Пуск: Кинжал", "title": "Развернуть РЛС сопровождения",
"color": [
60,
62,
60
]
},
{
"id": "launch_oreshnik",
"title": "Пуск: Орешник",
"color": [
230,
120,
40
]
},
{
"id": "deploy_irist",
"title": "Развернуть IRIS-T SLM",
"color": [
76,
86,
58
]
},
{
"id": "deploy_nasams",
"title": "Развернуть NASAMS",
"color": [
76,
86,
58
]
},
{
"id": "deploy_buk",
"title": "Развернуть Бук-М2",
"color": [
82,
96,
60
]
},
{
"id": "deploy_tor",
"title": "Развернуть Тор-М2",
"color": [ "color": [
108, 108,
110, 110,
@@ -356,68 +88,14 @@
] ]
}, },
{ {
"id": "deploy_p1sun", "id": "deploy_radar_height",
"title": "Развернуть P1-SUN", "title": "Развернуть мачтовую РЛС",
"color": [
52,
54,
52
]
},
{
"id": "deploy_radar",
"title": "Развернуть РЛС дальнего обнаружения",
"color": [ "color": [
108, 108,
110, 110,
80 80
] ]
}, },
{
"id": "deploy_depot",
"title": "Развернуть склад боеприпасов",
"color": [
92,
78,
48
]
},
{
"id": "deploy_tzm",
"title": "Развернуть ТЗМ",
"color": [
82,
96,
60
]
},
{
"id": "deploy_ew",
"title": "Развернуть станцию РЭБ",
"color": [
108,
110,
80
]
},
{
"id": "deploy_light",
"title": "Развернуть прожектор",
"color": [
52,
54,
52
]
},
{
"id": "deploy_optical",
"title": "Развернуть оптический пост",
"color": [
70,
110,
90
]
},
{ {
"id": "mover", "id": "mover",
"title": "Пульт перемещения", "title": "Пульт перемещения",
+99 -18
View File
@@ -21,6 +21,9 @@
"drones": [ "drones": [
{ {
"kind": "Shahed", "kind": "Shahed",
"accuracy": [1.2, 0.03],
"item": {"id": "launch_shahed", "title": "Пуск: Шахед-136", "color": [90, 92, 96]},
"raid_slot": 1,
"key": "shahed", "key": "shahed",
"name": "Шахед-136", "name": "Шахед-136",
"model": "airdef:shahed", "model": "airdef:shahed",
@@ -42,6 +45,9 @@
}, },
{ {
"kind": "Geran3", "kind": "Geran3",
"accuracy": [1.0, 0.03],
"item": {"id": "launch_geran3", "title": "Пуск: Герань-3", "color": [30, 30, 34]},
"raid_slot": 2,
"key": "geran3", "key": "geran3",
"name": "Герань-3", "name": "Герань-3",
"model": "airdef:geran3", "model": "airdef:geran3",
@@ -63,6 +69,9 @@
}, },
{ {
"kind": "Lancet", "kind": "Lancet",
"accuracy": [0.8, 0.02],
"item": {"id": "launch_lancet", "title": "Пуск: Ланцет-3", "color": [70, 78, 66]},
"raid_slot": 3,
"key": "lancet", "key": "lancet",
"name": "Ланцет-3", "name": "Ланцет-3",
"model": "airdef:lancet", "model": "airdef:lancet",
@@ -84,6 +93,9 @@
}, },
{ {
"kind": "Gerbera", "kind": "Gerbera",
"accuracy": [1.5, 0.04],
"item": null,
"raid_slot": 0,
"key": "gerbera", "key": "gerbera",
"name": "Гербера", "name": "Гербера",
"model": "airdef:gerbera", "model": "airdef:gerbera",
@@ -105,6 +117,9 @@
}, },
{ {
"kind": "Kh101", "kind": "Kh101",
"accuracy": [1.3, 0.05],
"item": {"id": "launch_kh101", "title": "Пуск: Х-101", "color": [84, 88, 92]},
"raid_slot": 4,
"key": "kh101", "key": "kh101",
"name": "Х-101", "name": "Х-101",
"model": "airdef:kh101", "model": "airdef:kh101",
@@ -126,6 +141,9 @@
}, },
{ {
"kind": "Kalibr", "kind": "Kalibr",
"accuracy": [1.3, 0.05],
"item": {"id": "launch_kalibr", "title": "Пуск: Калибр", "color": [150, 154, 156]},
"raid_slot": 5,
"key": "kalibr", "key": "kalibr",
"name": "Калибр", "name": "Калибр",
"model": "airdef:kalibr", "model": "airdef:kalibr",
@@ -147,6 +165,9 @@
}, },
{ {
"kind": "Kh22", "kind": "Kh22",
"accuracy": [1.6, 0.06],
"item": {"id": "launch_kh22", "title": "Пуск: Х-22", "color": [226, 228, 222]},
"raid_slot": 6,
"key": "kh22", "key": "kh22",
"name": "Х-22", "name": "Х-22",
"model": "airdef:kh22", "model": "airdef:kh22",
@@ -168,6 +189,9 @@
}, },
{ {
"kind": "Zircon", "kind": "Zircon",
"accuracy": [1.5, 0.06],
"item": {"id": "launch_zircon", "title": "Пуск: Циркон", "color": [52, 54, 52]},
"raid_slot": 7,
"key": "zircon", "key": "zircon",
"name": "Циркон", "name": "Циркон",
"model": "airdef:zircon", "model": "airdef:zircon",
@@ -189,6 +213,9 @@
}, },
{ {
"kind": "Iskander", "kind": "Iskander",
"accuracy": [1.4, 0.06],
"item": {"id": "launch_iskander", "title": "Пуск: Искандер-М", "color": [108, 110, 80]},
"raid_slot": 8,
"key": "iskander", "key": "iskander",
"name": "Искандер-М", "name": "Искандер-М",
"model": "airdef:iskander", "model": "airdef:iskander",
@@ -210,6 +237,9 @@
}, },
{ {
"kind": "Kinzhal", "kind": "Kinzhal",
"accuracy": [1.5, 0.06],
"item": {"id": "launch_kinzhal", "title": "Пуск: Кинжал", "color": [60, 62, 60]},
"raid_slot": 9,
"key": "kinzhal", "key": "kinzhal",
"name": "Кинжал", "name": "Кинжал",
"model": "airdef:kinzhal", "model": "airdef:kinzhal",
@@ -231,6 +261,9 @@
}, },
{ {
"kind": "Oreshnik", "kind": "Oreshnik",
"accuracy": [1.6, 0.08],
"item": {"id": "launch_oreshnik", "title": "Пуск: Орешник", "color": [230, 120, 40]},
"raid_slot": 10,
"key": "oreshnik", "key": "oreshnik",
"name": "Орешник", "name": "Орешник",
"model": "airdef:iskander", "model": "airdef:iskander",
@@ -252,6 +285,9 @@
}, },
{ {
"kind": "OreshnikBlock", "kind": "OreshnikBlock",
"accuracy": [1.6, 0.08],
"item": null,
"raid_slot": null,
"key": "oreshnik_block", "key": "oreshnik_block",
"name": "Орешник: блок", "name": "Орешник: блок",
"model": "airdef:reentry", "model": "airdef:reentry",
@@ -273,6 +309,9 @@
}, },
{ {
"kind": "OreshnikSub", "kind": "OreshnikSub",
"accuracy": [1.6, 0.08],
"item": null,
"raid_slot": null,
"key": "oreshnik_sub", "key": "oreshnik_sub",
"name": "Орешник: суббоеприпас", "name": "Орешник: суббоеприпас",
"model": "airdef:reentry", "model": "airdef:reentry",
@@ -296,9 +335,11 @@
"units": [ "units": [
{ {
"kind": "Patriot", "kind": "Patriot",
"village_cost": 5,
"item": {"id": "deploy_patriot", "title": "Развернуть Patriot", "color": [76, 86, 58]},
"key": "patriot", "key": "patriot",
"name": "Patriot", "name": "Patriot",
"missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 450.0, "interval": 16}, "missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 950.0, "interval": 16},
"gun": null, "gun": null,
"reload": 220, "reload": 220,
"scale": 1.3, "scale": 1.3,
@@ -316,15 +357,17 @@
"mount": [0.69, 1.2], "mount": [0.69, 1.2],
"pivot": [0.0, -0.5, 1.375], "pivot": [0.0, -0.5, 1.375],
"muzzle": {"type": "patriot"}, "muzzle": {"type": "patriot"},
"sensor": 585.0, "sensor": 1350.0,
"mast": 5.0 "mast": 5.0
}, },
{ {
"kind": "Gepard", "kind": "Gepard",
"village_cost": 2,
"item": {"id": "deploy_gepard", "title": "Развернуть Гепард", "color": [104, 84, 54]},
"key": "gepard", "key": "gepard",
"name": "Гепард", "name": "Гепард",
"missile": null, "missile": null,
"gun": {"range": 135.0, "track": 195.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]}, "gun": {"range": 180.0, "track": 260.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]},
"reload": 160, "reload": 160,
"scale": 1.25, "scale": 1.25,
"rest_pitch": 0.0, "rest_pitch": 0.0,
@@ -341,15 +384,17 @@
"mount": [1.55, 0.25], "mount": [1.55, 0.25],
"pivot": [0.0, 0.0, 0.0], "pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"}, "muzzle": {"type": "none"},
"sensor": 255.0, "sensor": 335.0,
"mast": 3.0 "mast": 3.0
}, },
{ {
"kind": "Pantsir", "kind": "Pantsir",
"village_cost": 3,
"item": {"id": "deploy_pantsir", "title": "Развернуть Панцирь-С1", "color": [82, 96, 60]},
"key": "pantsir", "key": "pantsir",
"name": "Панцирь-С1", "name": "Панцирь-С1",
"missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 225.0, "interval": 14}, "missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 330.0, "interval": 14},
"gun": {"range": 90.0, "track": 135.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]}, "gun": {"range": 125.0, "track": 185.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]},
"reload": 280, "reload": 280,
"scale": 1.3, "scale": 1.3,
"rest_pitch": 0.0, "rest_pitch": 0.0,
@@ -366,19 +411,22 @@
"mount": [1.35, 0.69], "mount": [1.35, 0.69],
"pivot": [0.0, 0.0, 0.0], "pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "pantsir"}, "muzzle": {"type": "pantsir"},
"sensor": 292.0, "sensor": 450.0,
"mast": 4.0 "mast": 4.0
}, },
{ {
"kind": "S400", "kind": "S400",
"village_cost": 5,
"item": {"id": "deploy_s400", "title": "Развернуть С-400", "color": [60, 80, 50]},
"ground_strike": "rm48u_game",
"key": "s400", "key": "s400",
"name": "С-400", "name": "С-400",
"missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 720.0, "interval": 20}, "missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 1300.0, "interval": 20},
"gun": null, "gun": null,
"reload": 420, "reload": 420,
"scale": 1.5, "scale": 1.5,
"rest_pitch": {"half_pi": -0.02}, "rest_pitch": {"half_pi": -0.02},
"roles": 30, "roles": 28,
"family": "vertical", "family": "vertical",
"parts": { "parts": {
"body": "airdef:s400_chassis", "body": "airdef:s400_chassis",
@@ -391,14 +439,16 @@
"mount": [0.7, 1.45], "mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"}, "pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 2, "size": 7.0}, "muzzle": {"type": "grid", "cols": 2, "rows": 2, "size": 7.0},
"sensor": 936.0, "sensor": 1750.0,
"mast": 5.0 "mast": 5.0
}, },
{ {
"kind": "S500", "kind": "S500",
"village_cost": 6,
"item": {"id": "deploy_s500", "title": "Развернуть С-500", "color": [108, 110, 80]},
"key": "s500", "key": "s500",
"name": "С-500", "name": "С-500",
"missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1050.0, "interval": 20}, "missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1850.0, "interval": 20},
"gun": null, "gun": null,
"reload": 520, "reload": 520,
"scale": 1.6, "scale": 1.6,
@@ -416,11 +466,13 @@
"mount": [0.7, 1.45], "mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"}, "pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 1, "size": 9.5}, "muzzle": {"type": "grid", "cols": 2, "rows": 1, "size": 9.5},
"sensor": 1365.0, "sensor": 2450.0,
"mast": 5.0 "mast": 5.0
}, },
{ {
"kind": "IrisT", "kind": "IrisT",
"village_cost": 4,
"item": {"id": "deploy_irist", "title": "Развернуть IRIS-T SLM", "color": [76, 86, 58]},
"key": "irist", "key": "irist",
"name": "IRIS-T SLM", "name": "IRIS-T SLM",
"missile": {"kind": "IrisT", "magazine": 8, "min": 15.0, "max": 600.0, "interval": 10}, "missile": {"kind": "IrisT", "magazine": 8, "min": 15.0, "max": 600.0, "interval": 10},
@@ -446,6 +498,8 @@
}, },
{ {
"kind": "Nasams", "kind": "Nasams",
"village_cost": 4,
"item": {"id": "deploy_nasams", "title": "Развернуть NASAMS", "color": [76, 86, 58]},
"key": "nasams", "key": "nasams",
"name": "NASAMS", "name": "NASAMS",
"missile": {"kind": "Amraam", "magazine": 6, "min": 10.0, "max": 450.0, "interval": 14}, "missile": {"kind": "Amraam", "magazine": 6, "min": 10.0, "max": 450.0, "interval": 14},
@@ -471,6 +525,8 @@
}, },
{ {
"kind": "Buk", "kind": "Buk",
"village_cost": 4,
"item": {"id": "deploy_buk", "title": "Развернуть Бук-М2", "color": [82, 96, 60]},
"key": "buk", "key": "buk",
"name": "Бук-М2", "name": "Бук-М2",
"missile": {"kind": "M9m317", "magazine": 4, "min": 20.0, "max": 675.0, "interval": 18}, "missile": {"kind": "M9m317", "magazine": 4, "min": 20.0, "max": 675.0, "interval": 18},
@@ -496,9 +552,11 @@
}, },
{ {
"kind": "Tor", "kind": "Tor",
"village_cost": 3,
"item": {"id": "deploy_tor", "title": "Развернуть Тор-М2", "color": [108, 110, 80]},
"key": "tor", "key": "tor",
"name": "Тор-М2", "name": "Тор-М2",
"missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 240.0, "interval": 8}, "missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 350.0, "interval": 8},
"gun": null, "gun": null,
"reload": 300, "reload": 300,
"scale": 1.3, "scale": 1.3,
@@ -516,11 +574,13 @@
"mount": [1.5, 0.0], "mount": [1.5, 0.0],
"pivot": [0.0, 0.0, 0.0], "pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "cells"}, "muzzle": {"type": "cells"},
"sensor": 315.0, "sensor": 475.0,
"mast": 3.5 "mast": 3.5
}, },
{ {
"kind": "P1sun", "kind": "P1sun",
"village_cost": 3,
"item": {"id": "deploy_p1sun", "title": "Развернуть P1-SUN", "color": [52, 54, 52]},
"key": "p1sun", "key": "p1sun",
"name": "P1-SUN", "name": "P1-SUN",
"missile": {"kind": "P1sun", "magazine": 8, "min": 5.0, "max": 675.0, "interval": 12}, "missile": {"kind": "P1sun", "magazine": 8, "min": 5.0, "max": 675.0, "interval": 12},
@@ -546,6 +606,8 @@
}, },
{ {
"kind": "Radar", "kind": "Radar",
"village_cost": 2,
"item": {"id": "deploy_radar", "title": "Развернуть РЛС дальнего обнаружения", "color": [108, 110, 80]},
"key": "radar", "key": "radar",
"name": "РЛС дальнего обнаружения", "name": "РЛС дальнего обнаружения",
"missile": null, "missile": null,
@@ -566,11 +628,13 @@
"mount": [0.0, 0.0], "mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0], "pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"}, "muzzle": {"type": "none"},
"sensor": 2550.0, "sensor": 3800.0,
"mast": 16.0 "mast": 16.0
}, },
{ {
"kind": "Depot", "kind": "Depot",
"village_cost": 2,
"item": {"id": "deploy_depot", "title": "Развернуть склад боеприпасов", "color": [92, 78, 48]},
"key": "depot", "key": "depot",
"name": "Склад боеприпасов", "name": "Склад боеприпасов",
"missile": null, "missile": null,
@@ -596,6 +660,8 @@
}, },
{ {
"kind": "Tzm", "kind": "Tzm",
"village_cost": 2,
"item": {"id": "deploy_tzm", "title": "Развернуть ТЗМ", "color": [82, 96, 60]},
"key": "tzm", "key": "tzm",
"name": "ТЗМ", "name": "ТЗМ",
"missile": null, "missile": null,
@@ -621,6 +687,8 @@
}, },
{ {
"kind": "Ew", "kind": "Ew",
"village_cost": 2,
"item": {"id": "deploy_ew", "title": "Развернуть станцию РЭБ", "color": [108, 110, 80]},
"key": "ew", "key": "ew",
"name": "Станция РЭБ", "name": "Станция РЭБ",
"missile": null, "missile": null,
@@ -646,6 +714,8 @@
}, },
{ {
"kind": "Light", "kind": "Light",
"village_cost": 1,
"item": {"id": "deploy_light", "title": "Развернуть прожектор", "color": [52, 54, 52]},
"key": "light", "key": "light",
"name": "Прожектор", "name": "Прожектор",
"missile": null, "missile": null,
@@ -671,6 +741,8 @@
}, },
{ {
"kind": "Optical", "kind": "Optical",
"village_cost": 1,
"item": {"id": "deploy_optical", "title": "Развернуть оптический пост", "color": [70, 110, 90]},
"key": "optical", "key": "optical",
"name": "Оптический пост", "name": "Оптический пост",
"missile": null, "missile": null,
@@ -698,6 +770,7 @@
"missiles": [ "missiles": [
{ {
"kind": "Pac3", "kind": "Pac3",
"launcher_blast": 0.8,
"model": "airdef:pac3", "model": "airdef:pac3",
"speed": 5.5, "speed": 5.5,
"accel": 0.35, "accel": 0.35,
@@ -708,7 +781,7 @@
"eject_drag": 0.0, "eject_drag": 0.0,
"pk": 0.9, "pk": 0.9,
"fuse": 4.0, "fuse": 4.0,
"life": 240, "life": 360,
"scale": 1.0, "scale": 1.0,
"flame": 1.0, "flame": 1.0,
"rear": 28.0, "rear": 28.0,
@@ -718,6 +791,7 @@
}, },
{ {
"kind": "M57e6", "kind": "M57e6",
"launcher_blast": 0.45,
"model": "airdef:m57e6", "model": "airdef:m57e6",
"speed": 5.0, "speed": 5.0,
"accel": 0.5, "accel": 0.5,
@@ -738,6 +812,7 @@
}, },
{ {
"kind": "M48n6", "kind": "M48n6",
"launcher_blast": 1.8,
"model": "airdef:m48n6", "model": "airdef:m48n6",
"speed": 7.0, "speed": 7.0,
"accel": 0.5, "accel": 0.5,
@@ -748,7 +823,7 @@
"eject_drag": 0.07, "eject_drag": 0.07,
"pk": 0.9, "pk": 0.9,
"fuse": 5.0, "fuse": 5.0,
"life": 300, "life": 390,
"scale": 1.5, "scale": 1.5,
"flame": 1.4, "flame": 1.4,
"rear": 30.0, "rear": 30.0,
@@ -758,6 +833,7 @@
}, },
{ {
"kind": "M77n6", "kind": "M77n6",
"launcher_blast": 2.2,
"model": "airdef:m77n6", "model": "airdef:m77n6",
"speed": 9.0, "speed": 9.0,
"accel": 0.6, "accel": 0.6,
@@ -768,7 +844,7 @@
"eject_drag": 0.07, "eject_drag": 0.07,
"pk": 0.95, "pk": 0.95,
"fuse": 6.0, "fuse": 6.0,
"life": 320, "life": 430,
"scale": 1.7, "scale": 1.7,
"flame": 1.6, "flame": 1.6,
"rear": 32.0, "rear": 32.0,
@@ -778,6 +854,7 @@
}, },
{ {
"kind": "IrisT", "kind": "IrisT",
"launcher_blast": 0.6,
"model": "airdef:irist_missile", "model": "airdef:irist_missile",
"speed": 7.0, "speed": 7.0,
"accel": 0.5, "accel": 0.5,
@@ -798,6 +875,7 @@
}, },
{ {
"kind": "Amraam", "kind": "Amraam",
"launcher_blast": 0.5,
"model": "airdef:amraam_missile", "model": "airdef:amraam_missile",
"speed": 6.0, "speed": 6.0,
"accel": 0.45, "accel": 0.45,
@@ -818,6 +896,7 @@
}, },
{ {
"kind": "M9m317", "kind": "M9m317",
"launcher_blast": 1.2,
"model": "airdef:m48n6", "model": "airdef:m48n6",
"speed": 6.5, "speed": 6.5,
"accel": 0.5, "accel": 0.5,
@@ -838,6 +917,7 @@
}, },
{ {
"kind": "M9m338", "kind": "M9m338",
"launcher_blast": 0.4,
"model": "airdef:m57e6", "model": "airdef:m57e6",
"speed": 5.5, "speed": 5.5,
"accel": 0.6, "accel": 0.6,
@@ -858,6 +938,7 @@
}, },
{ {
"kind": "P1sun", "kind": "P1sun",
"launcher_blast": 0.1,
"model": "airdef:p1sun", "model": "airdef:p1sun",
"speed": 2.8, "speed": 2.8,
"accel": 0.12, "accel": 0.12,
+3 -2
View File
@@ -3,8 +3,9 @@ rem Run AirDef with DLSS SR and GPU pass timing. Same game home and mod as play.
chcp 65001 >nul chcp 65001 >nul
setlocal setlocal
set "HORIZON_DLSS=1" set "HORIZON_DLSS=1"
rem Empty means the DLSS default of 2/3 render resolution. rem Explicit 2/3 render resolution (DLSS Quality upscaling). The Resolution Scale slider's
set "HORIZON_HD_SCALE=" rem 100% is DLAA (1:1); this env override pins the upscaling ratio for the A/B test.
set "HORIZON_HD_SCALE=0.67"
set "HORIZON_HD_DEBUG_MOTION=" set "HORIZON_HD_DEBUG_MOTION="
set "HORIZON_SHADER_PACK_TIMING=1" set "HORIZON_SHADER_PACK_TIMING=1"
call "%~dp0play.bat" %* call "%~dp0play.bat" %*
+4 -2
View File
@@ -30,7 +30,7 @@
## Как собрать ## Как собрать
Через N → «Разместить элементы батареи…» можно расставить элементы в разных местах. Элементы расставляются отдельными пультами: `/airdef give` выдаёт пульты всех вариантов (`deploy_radar_search`, `deploy_radar_track`, `deploy_radar_height`, `deploy_s400_launcher`, `deploy_s500_launcher`), которые ставятся на блок как обычные пульты.
Командные эквиваленты: Командные эквиваленты:
```text ```text
@@ -65,7 +65,9 @@
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута, контакту, а число каналов ограничено на каждом тике. Канал удерживает только собственное измерение
станции: когда оно устаревает (станция больше не измеряет контакт), канал освобождается для новой
цели, а сетевой обзорный трек остаётся на месте. Если РЛС сопровождения уничтожена, свёрнута,
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
продолжают штатную игровую логику связи/памяти/самонаведения. продолжают штатную игровую логику связи/памяти/самонаведения.
+122 -3
View File
@@ -1,8 +1,88 @@
# Передача разработки AirDef # Передача разработки AirDef
Это журнал фактически сделанных изменений и ограничений проверки, а не список обещанных функций. Рабочая ветка публикации — `kimi-work`. Движок хранится в `chexit/horizon-airdef`,
Рабочая ветка `kimi-work`; issues не закрывать, публиковать комментарии с коммитом и проверками. точный коммит задаёт сабмодуль `horizon/`. Разделы ниже отражают состояние на указанные даты.
Движок — отдельный `chexit/horizon-airdef`, ветка `airdef`, подключён точным gitlink `horizon/`.
## Актуальная передача · 2 декабря 2026
База предыдущей опубликованной серии — `7612d15`. В ней уже были командный пункт,
карточки комплексов, журнал решений, дельты карты, маркеры шкалы боя и исправления
#91, #114, #118, #135. Кампания «Оборона деревни» и отчёты о прорывах вошли в
`7e6d9d8`. Рельеф, радар и Tailscale добавлены в `20fdb23`. Изменения баланса
вошли в `f6303fe`. Профилирование
рендера и эксперименты с DLSS/RT отложены по просьбе пользователя.
**Сборка.** Проверьте `git status --short`, HEAD и gitlink. На этой машине работа
велась в `/Users/chexit/Documents/zcode/airdef/gameplay/village-defense`. Соседний
worktree `/Users/chexit/Documents/zcode/airdef/airdef` содержит независимые
локальные изменения. В `kimi-work` используется Horizon
`2656f35af71be3472a88d3c7dcf505deb92cbd8d`. Обычное обновление на Windows
из каталога AirDef:
```powershell
git switch kimi-work
git pull --ff-only
py -3 tools/airdef.py all
py -3 tools/airdef.py play
```
**Баланс.** Штатный С-400 работает по крылатым, сверхзвуковым и баллистическим
ракетам. У С-500 роли сверхзвуковые и баллистические. С-400 и С-500 без
роли `drone` ждут подтверждения класса. При выборе цели у них выше приоритет
баллистической, затем сверхзвуковой, затем крылатой ракеты. Этот порядок
может прервать удержание менее приоритетной отметки. Классификация опирается
на независимые замеры, а права пуска по собственной отметке либо от
РЛС наведения по-прежнему проверяются отдельно. См. `sim/sight.rs`,
`sim/why.rs`, `sim/mod.rs` и `catalog/specs.json`.
Last Chance для С-400 и С-500 проверяет подтверждённый контакт вне штатных
ролей, направленный к игровой цели с расчётным временем до неё менее
80 тиков (4 с при 20 TPS). Назначенный перехватчик, готовое ближнее прикрытие
или достижение резерва закрывают исключение. Резерв для исключения — округлённая
вверх половина доступных зенитных ячеек либо более высокий заданный резерв.
Основные цели всё ещё могут расходовать эту часть боезапаса по обычной доктрине.
Пользовательские роли в сейвах сохраняются. Чтобы вернуть актуальные штатные
роли в старом мире, используйте `/airdef roles s400 default` и
`/airdef roles s500 default`. Для проверки отдельной батареи есть
`/airdef why <номер>`, для отключения исключения — `/airdef lastchance off`.
**Веб-пульт.** [Пошаговое подключение](WEB-PANEL.md#tailscale-serve-на-windows).
`web --tailscale https://имя.сеть.ts.net --allow-launch` поднимает локальный
пульт и запускает Horizon. Serve завершает HTTPS, backend слушает loopback,
оператор подтверждает доступ одноразовым кодом. В карте и радаре используется
единая картина игрока. Радар центрируется по выбранной активной РЛС и показывает
номинальную дальность. Силуэты контактов появляются после подтверждения класса.
Снимки запрашиваются через 0,5 с, открытый браузер опрашивает сервер через
0,65 с, архив снимается примерно раз в секунду.
Рельеф берётся из цветов чанков Horizon через локальную команду
`terrain-tile x z step`, обработчик в `horizon/crates/horizon-client/src/game/mod_canvas.rs`.
Фоновые запросы, PNG-кэш и HTTP находятся в `tools/web_remote/`, визуализация
и иконки в `tools/web_remote/static/`. PNG запрашивается с ключом текущего мира
и измерения. Прогрессивное заполнение при первом открытии карты ожидаемо.
В архиве отметки сохраняются в SQLite. Рельеф в повторе доступен из кэша
вкладки, если эти фрагменты уже загружались в той же сессии.
**Проверки.** Собран Horizon Metal на Mac. В живом мире в Chromium и WebKit
проверены сопряжение, рельеф, переключение подложки и выбор РЛС.
Малый сценарий с пульта подтвердил поступление неопознанной отметки и
иконки классифицированной крылатой ракеты. Пройдены 11 HTTP-тестов,
347 тестов ядра и 8 интеграционных сценариев, 128 тестов адаптера и его
11 интеграционных проверок, оба WASM-контракта. Нагрузочный WASM-сценарий
прошёл все 283 шага. Пик тика на одинаковом хосте изменился с 138 878 236 до
138 356 469 из 300 000 000, превышений нет. В том же сценарии число перехватов
изменилось с 142 до 133, число поражений с 2692 до 2730. Изменение проверяет
расход и распределение боезапаса. Суммарная эффективность этой расстановки
снизилась, и результаты смешанного налёта игрока ещё предстоит измерить.
**Приёмка на ПК игрока.** В Windows ещё нужно открыть пульт с физического
планшета через Serve и прогнать реальное сохранение. Матч для повторения:
обычная равнинная деревня, отметки объектов, 70+ комплексов, смешанный
волновой налёт с умным противником, HD и акустика. Сверьте расход ракет каждого
С-400/С-500, приоритеты, отказы и попадания по журналу. Для сравнения
производительности фиксируйте одинаковые мир, состав волн, настройки и
положение камеры. Нагрузочный WASM-тест проверяет симуляцию в заданном сценарии,
а клиентские кадры и реальный матч проверяются отдельно.
## #91: типизированные варианты комплексов — первый slice (20 ноября 2026) ## #91: типизированные варианты комплексов — первый slice (20 ноября 2026)
@@ -642,6 +722,45 @@ kills 59→58, 59→58, 56→63; hits 7→7, 7→9, 8→3; потери ЗРК 3
появляется). Adapter: `the_air_section_of_a_save_is_written_and_read_by_the_adapter` (запись/чтение появляется). Adapter: `the_air_section_of_a_save_is_written_and_read_by_the_adapter` (запись/чтение
секции, замена не слияние, старый save без секции, сценарий без воздуха). секции, замена не слияние, старый save без секции, сценарий без воздуха).
### #149: Smart v2 поверх #146 — единая разведкартина, цены отметок, ограниченный refresh, окно bearing
Продолжение #127/#135 **поверх уже интегрированного #146** (`KnowledgeSnapshot { tick, contacts, marks }`,
`knowledge_now()`, `Plan.knowledge`, `RouteJob.known`, версионные `price_grid_known`/restore). Инфраструктура
#146 не дублируется и не меняется: один снимок на приказ, цены по `known.tick`, версионный restore — как есть.
Новое наслоение:
- **Один публичный тип наблюдения** `sim::observe::Observation` (область/радиус, канал `recon::Source`,
возраст, уверенность, категория/роль/тип, качество, флаг `matched`). `observe::merge` сводит `Contact` и
`Mark` в один список **только по публичным признакам** (перекрытие области + точное совпадение категории);
coarse `Unknown` и противоречащая категория остаются отдельными подсказками, контакт не переписывает
тип/место, отметка добавляет лишь свежесть и refined-роль; `recon.truth` и реальные id не участвуют.
`KnowledgeSnapshot::observations()` (аддитивно) отдаёт этот список; одна шкала `Observation::rank`
заменила две разные в `radar_strikes`, `choose_target` и адаптивном выборе (сигнатуры kimi-work сохранены).
- **Цены отметок** в существующем `price_grid_known`: свежая (Probable/Confirmed) отметка launcher/gun/jammer
ценит клетки по published-огибающей категории (`observe::category_envelope`), взвешенной уверенностью
(Confirmed ×1, Probable ×0.5); radar-отметка кормит сетевую веру ПУ рядом (`observe::radar_envelope`);
совпавшая с контактом ценится один раз через контакт; doubtful не ценится.
- **Ограниченный refresh не выпущенной части**: пока разведчики в воздухе, при завершении плана взводится
`ew::Refresh { deadline, reports }` с абсолютным дедлайном `REFRESH_WINDOW=600`. `step_refresh` один раз,
при приходе донесения, перенацеливает queued-дроны с intent Plan/Sead на свежий снимок (typed
`Intent::Refresh`, приоритет SEAD) в пределах `SWITCH_CAP` и бюджетов. Нет донесения — пуски не задерживаются.
- **Окно bearing**: `Intel.outcomes` — bounded `VecDeque<Learned>` (48 записей, окно 12000 тиков);
`best_bearing` кандидата скорит окно и адаптирует долю исследования по typed `BearingReason`
(few/stale/conditions-changed/exploiting); «условия» — fingerprint публичной картины, не скрытое состояние.
Legacy сохраняет пожизненные kills/hits и фиксированные 0.3 (`FixedShare`). Диагностика —
`Sim::bearing_report()`, поля `bearing/refresh_waiting/refresh_applied/observations` в `EnemyPictureReport`.
- **Сравнительный runner** `cargo run --release --example smart_bench`: simple / current (legacy) / candidate
на seed 1/7/42, сценарии open/hills/config-change/recon-lost; JSON и строки (полезные решения, разнообразие,
jitter ≥2 переключений, reasons/intents, bearing reason, refresh, CPU p95/max, worst jobs).
`Sim::smart_legacy` воспроизводит текущий Smart kimi-work (включая #146) для честного сравнения;
`harness::run_with_hook` меняет оборону между волнами и сбивает разведчика до донесения. Лёгкий режим и
bounded jobs не тронуты; policy не читает здоровье/заряды/скрытые переключатели/позиции мира.
- **Тесты** `sim::smart_tests` + `sim::observe::tests`: метаморфный hidden-layout до/после наблюдения, дедуп
по публичным признакам, отметки в ценах, одна версия на приказ (обе моды чтят #146), bounded refresh
(срабатывает один раз / не паузит), окно bearing и причины, durable окна (`airlearn`) и `Intent::Refresh`.
Регрессия relief-версий сохранена; стена в её фикстуре расширена по z, чтобы пересекать любой восток-запад
маршрут после смены порядка назначений кандидатом.
## Что следующему агенту проверить в первую очередь ## Что следующему агенту проверить в первую очередь
1. На Windows: обновление сабмодуля через `all`, сохранение/перезаход, рабочий цикл игры. 1. На Windows: обновление сабмодуля через `all`, сохранение/перезаход, рабочий цикл игры.
+118 -6
View File
@@ -2,6 +2,93 @@
Это тестовая, а не релизная сборка #124. Она включает native DLSS Super Resolution через Vulkan и сохраняет обычный TAAU как fallback. Frame generation здесь нет; RTX 3060 его и не поддерживает. Это тестовая, а не релизная сборка #124. Она включает native DLSS Super Resolution через Vulkan и сохраняет обычный TAAU как fallback. Frame generation здесь нет; RTX 3060 его и не поддерживает.
## Temporal stability: дрожь с DLSS и мерцание native TAAU (ветка agent/dlss-temporal-stability)
### Что исправлено
**DLSS (сильная дрожь всего изображения).** Буфер motion в G-buffer — это current→previous в *джиттеренных* пикселях рендера (оба кадра со своим джиттером). Флаги создания DLSS-контекста не включали `MVJittered`, поэтому NGX использовал векторы как есть **и** применял переданный `jitter_offset` — джиттер камеры учитывался дважды, отсюда «дрожит адски». Исправление: флаг `DlssFeatureFlags::JitteredMotionVectors` (`horizon/crates/horizon-client/src/gfx/hd/dlss.rs`, коммит f536fa958). С ним NGX сам вычитает разницу джиттеров из векторов по per-frame `jitter_offset`.
Контракт сверен по первоисточникам (не по догадкам):
- **NVIDIA DLSS Programming Guide** (редакция 31 марта 2026, SDK 310.x — тот же, что оборачивает `dlss_wgpu` 6.0.0), `doc/DLSS_Programming_Guide_Release.pdf` из [NVIDIA/DLSS](https://github.com/NVIDIA/DLSS):
- §3.6/3.6.1: векторы — current→previous, **в пикселях render-разрешения**, начало координат сверху слева, y вниз; формат RG16F/RG32F. Наш буфер (`Rg16Float`, `terrain.wgsl`/`entity.wgsl` `motion_pixels`) ровно такой.
- §3.6.2: `MVJittered=1` — «DLSS then internally subtracts jitter from the motion vectors using the jitter offset values provided during the Evaluate call»; `MVLowRes=1` — векторы в render-разрешении (NGX сам их dilate'ит). Оба флага теперь стоят.
- §3.6.3: `InMVScaleX/Y = 1.0`, если масштабирование не нужно. Пиксельные векторы не масштабируются — `motion_vector_scale: [1,1]` оставлен. **Важно:** совет `{1/renderWidth, 1/renderHeight}` из гайда Streamline относится к константе `sl::Constants::mvecScale` самого Streamline: его плагин (`source/plugins/sl.dlss/dlssEntry.cpp`) умножает её обратно на renderWidth и передаёт в NGX `MV.Scale = 1.0` для pixel-space (`mvecPixelSpace ? 1.0f : mvecScale.x * renderWidth`). `dlss_wgpu` зовёт NGX напрямую, без Streamline, поэтому у нас 1.0.
- §3.7.3: `jitter_offset` — джиттер текущего кадра **в пикселях render-таргета**, в той же системе координат, что векторы (y вниз), в пределах ±0.5. `scene.jitter_px` именно такой.
- §3.8.1: `DepthInverted=1` для reversed-Z — уже стоял.
- Заголовок NGX `include/nvsdk_ngx_defs.h` (NVIDIA/DLSS): флаг `NVSDK_NGX_DLSS_Feature_Flags_MVJittered = 1 << 2`.
- Исходник Streamline `dlssEntry.cpp`: `motionVectorsJittered == eTrue → MVJittered`, jitter передаётся как есть.
**Native TAAU (слабое мерцание, особенно на воде).** Две причины найдены и исправлены (коммиты 26ee82398, acfb379aa):
1. **Вода анимируется без геометрического движения**: волны наклоняют нормали, преломление/SSR-отражение/блики меняются каждый кадр, а motion-буфер на пикселях воды несёт движение только дна. История TAA конфликтовала с кадром — мерцание. Теперь TAA-проход читает собственную глубину воды (binding 7) и снижает вес истории там, где вода анимируется быстрее всего — вблизи камеры (до 0.8 для `fs_taa`, до 0.7 для `fs_taau`, спад до 96 блоков; дальняя вода с медленными волнами сохраняет полный вес). Это reactive mask; качество не снижается, TAA не выключается.
2. **Листва и растения качаются на ветру**, но motion-буфер знал только камеру (`prev_clip` строился из текущей wind-позиции). Теперь предыдущая позиция вершины вычисляется с ветром *прошлого* кадра (`Globals.hd_motion.zw` = прошлые секунды/сила ветра, `terrain.wgsl` `wind_offset_at`) — листва несёт собственное движение, мерцание кроны и дальней лесополосы уходит.
Тени: каскады уже привязаны к текселям в мировых координатах (`hd::cascades`, f64 snap) — crawl отсутствует; дальняя каскада перерисовывается через кадр (`HORIZON_HD_SHADOW_FAST`), её матрица между перерисовками сдвигается за камерой — это корректно. Точность motion на дальних дистанциях достаточная: f16 хранит субпиксельные значения точно, f32-разница clip-координат на 500 блоках даёт ошибку ~1e-4 px.
### Что проверить на RTX (порядок)
1. Собрать с DLSS: `py tools\airdef.py all` (ветка `agent/dlss-temporal-stability`), запустить `test-dlss.bat --world "Имя мира"`. В `%APPDATA%\horizon\logs\latest.log` должна быть строка `DLSS Super Resolution: [1706, 960] -> [2560, 1440]` (для 1440p при масштабе 2/3) и не должно быть `using native TAAU` / `DLSS evaluation failed`.
2. **Статичная сцена — главный тест.** Встать неподвижно, смотреть на дальние статичные объекты (горы, строения) 10–15 секунд. Изображение не должно дрожать/вибрировать. Затем медленно повернуть камеру — не должно быть smear/ghosting на статичном мире. Для увеличения используй встроенный Windows Screen Magnifier (Win+«+», отключить «Smooth edges of images and text») — гайд §8.4.1.
3. **Движение**: `/airdef move 2` или `/airdef wave shahed 8 300` — движущиеся модели не должны двоиться/размазываться; дым и вспышки смотреть отдельно.
4. **Вода и листва, DLSS off** (`dlss off` через меню мода или контрольный сокет, без перезапуска): постоять у воды с ветром — мерцание/«вибрация» воды и кроны должны заметно уменьшиться против старой сборки. Блики на воде остаются живыми (это анимация, не артефакт).
5. **Motion-визуализация** (отдельный прогон, не для замера качества): `HORIZON_HD_DEBUG_MOTION=1` — на статичной сцене векторы должны быть почти нулевыми (субпиксельная разница джиттеров), без крупных пятен. Это проверяет буфер, который видит NGX.
6. Скриншоты одного ракурса: DLSS on / DLSS off, статика и движение; лог обоих прогонов.
Опционально (для глубокой отладки джиттера): dev-версия `nvngx_dlss.dll` (фича `debug_overlay` у `dlss_wgpu` + `DLSS_SDK` с dev-профилем) даёт оверлей §8.2 и jitter-отладку §8.4: offsets всегда внутри ±0.5, хоткеи CTRL+ALT+F9/F10 меняют знак/оси джиттера на лету.
### Если дрожь осталась: варианты по порядку (быстрая итерация)
Все правки — в `horizon/crates/horizon-client/src/gfx/hd/dlss.rs` (движок, ветка `agent/dlss-temporal-stability`), пересборка только игры.
- **Вариант A (проверка знака/осей джиттера).** В `render()` передавать `jitter_offset: [jitter[0], -jitter[1]]` (или `[-jitter[0], jitter[1]]`, или поменять оси местами). По документации наша система координат совпадает с NGX, так что это маловероятно, но гайд §8.4.1 советует именно это при остаточной дрожи. Признак: дрожь уменьшается при одном из знаков/осей.
- **Вариант B (нормализация Streamline).** `motion_vector_scale: Some([1.0 / self.world[0] as f32, 1.0 / self.world[1] as f32])`. Противоречит §3.6.3 для сырого NGX (и исходнику Streamline), но дёшево проверяется. Признак: если дрожь была от масштаба, картинка сразу стабилизируется; если станет хуже/размазаннее — вернуть `[1,1]`.
- **Вариант C (неджиттеренный буфер вместо флага).** Убрать `JitteredMotionVectors` из `FEATURE_FLAGS` и добавить конверсионный проход перед NGX: новый `Rg16Float`-таргет world-размера, fullscreen-шейдер пишет `motion.xy + frame.taa_params.zw - frame.prev_jitter.xy` (в точности коррекция `fs_taau`, taa.wgsl:234), в `DlssSuperResolutionRenderParameters.motion_vectors` подать его. Это зеркальный путь: NGX получает векторы без джиттера и использует их напрямую (§3.6.2, флаг=0). Признак: если флаг MVJittered в драйверной версии NGX работает иначе, чем описано, этот путь стабилизирует картинку.
Если дрожь ушла, но **только вода/анимированные материалы** двоится под DLSS — это отдельная задача: у NGX есть входы transparency/responsivity mask, `dlss_wgpu` передаёт их пустыми; native-путь теперь имеет reactive mask для воды.
### Что проверено на Mac, а что ждёт RTX
Проверено (macOS, Metal, без DLSS-устройства): вся сюита `cargo test -p horizon-client --lib` — 1242 passed / 0 failed; GPU A/B smoke `taau_gpu_smoke_still_surface_ab` (Apple M5): исправленный decode даёт ошибку 0.0048 на уровне собственного пространственного фильтра (0.00478) и разброс по фазам 0.0029 против 0.0156 у старого decode; shader-валидация naga + трансляция HLSL для всех HD-шейдеров и terrain/entity; раскладка `HdFrame`/`Globals`; детерминизм джиттера и репроекции (численные тесты на всех фазах Halton); сборка бинарника без фичи `dlss`. Сам `dlss.rs` на Mac не компилируется (cfg windows/linux + feature) — флаг и тест `the_feature_flags_match_the_motion_contract` проверятся на Windows-сборке.
Ждёт RTX: собственно NGX-оценка (стабильность статики, движение, вода), тест флага в `cargo test -p horizon-client --features dlss --lib gfx::hd::dlss`, визуальное сравнение воды/листвы с reactive mask и wind-motion.
## Переключатель DLSS
В сборках с фичей `dlss` DLSS теперь включён по умолчанию, а не только через `HORIZON_DLSS=1`:
- Меню мода: **N → Огонь, ремонт, эффекты… → DLSS (NVIDIA)**. Строка показывает состояние; на устройстве без DLSS переключение — мягкий no-op («недоступен»), запрос сохраняется и применяется при следующем запуске, если устройство его поддерживает.
- Команда контрольного сокета: `dlss on|off|status` (`available` — открыт ли DLSS-девайс, `dlss` — запрос игрока).
- Настройка `dlss:true|false` в `horizon-graphics.txt`; `HORIZON_DLSS=1|0` по-прежнему переопределяет её при старте.
Выключение переходит на native TAAU со следующего кадра: разделённые истории #137 делают переход чистым в обе стороны (NGX сбрасывается при возобновлении, первый native кадр не читает устаревшую историю). Включение после старта с выключенным DLSS применяется при следующем запуске — девайс открывается под DLSS только при старте. Разрешение рендера — выбор игрока в настройках Horizon (слайдер Resolution Scale, см. ниже).
Для A/B ниже `test-dlss.bat`/`test-native.bat` работают как раньше; если старт был с DLSS, оба режима можно снять и одним прогоном через `dlss off`/`dlss on` без перезапуска.
## Масштаб разрешения (Resolution Scale) и DLSS
**Баг (исправлен, ветка `agent/resolution-scale`).** Слайдер Resolution Scale (50–200%, `horizon-graphics.txt` `resolutionScale`) писал `world_post.scale`, но при включённом HD решение о масштабе мира принимал `hd::scale_override()`: с DLSS (включён + девайс открыт) он **всегда** возвращал `Some(2/3)`, и `world_post.prepare()` брал `hd_scale.unwrap_or(scale)` — слайдер не читался вовсе. Картинка и FPS не менялись от 50/80/100/200%. Без DLSS и без `HORIZON_HD_SCALE` слайдер работал (native TAAU), поэтому баг был виден только на RTX.
**Семантика после исправления** (`hd::scale_override(slider)`, чистое решение `scale_for`, юнит-тест `the_resolution_slider_drives_hd_scale`). Приоритет, первое совпадение выигрывает:
1. **Film quality** (`render.set-film-quality`, захват) — мир в полный размер окна.
2. **`HORIZON_HD_SCALE`** (0.25–1, читается один раз при старте) — явное dev-переопределение, сильнее слайдера.
3. **DLSS оценивает кадр** (запрос включён + SDK открыт): слайдер — это render-размер, ограниченный размером выхода (апскейлер не рендерит больше выхода), **монотонно**: **100% = render 1:1 (DLAA**, neural AA без апскейла), **ниже 100%** — DLSS апскейл (50% → половина, 80% → 0.8, 67% ≈ Quality); **выше 100%** мир рендерится в размер выхода (суперсэмплинг >1 — только native TAAU с выключенным DLSS).
4. **Иначе (native TAAU)** — слайдер как есть, 0.5–2.0, включая суперсэмплинг; при 1.0 без HD/FXAA мир рисуется прямо в экран (как раньше, бит-в-бит).
**Живое обновление.** `set_world_post` (слайдер) пишет `world_post.scale`; `hd_scale` пересчитывается каждый кадр до джиттера, поэтому джиттер и motion-буфер (`Globals.hd_motion.xy`) соответствуют размеру мира этого же кадра. `world_post.prepare()` пересоздаёт таргет при смене размера, `Hd::resize` → `Taa::resize` сбрасывает истории и зовёт `Dlss::resize(world, out)`. Контекст NGX создаётся под размер выхода; render-размер передаётся в каждой evaluate через `partial_texture_size`, поэтому при смене слайдера контекст **сохраняется**, пока новый render-размер вписывается в `render_resolution_range()` контекста (динамическое разрешение NGX); вне диапазона или при смене размера окна — пересоздание. Пересоздание ждёт idle девайса (`DlssSuperResolution::drop`), поэтому reuse важен для живого слайдера. Первая evaluate после смены масштаба идёт с `InReset` (истории сброшены в `Taa::resize`) — ghosting между масштабами исключён. Контракт motion/jitter #143 не тронут: `MVJittered`, `MVLowRes`, `jitter_offset` в render-пикселях, `motion_vector_scale [1,1]`.
**Что проверено на Mac (M5/Metal, без DLSS-устройства):** юнит-тест приоритета (все ветки, включая DLSS-арифметику — она платформенно-независима); GPU-тест `gfx::world_post::tests::the_world_target_follows_the_resolution_slider` — таргет мира следует за слайдером 50/100/200% (960×540 / 1920×1080 / 3840×2160), live-ресайз без пересоздания `Post`, `hd_scale` заменяет слайдер (0.67, 0.5, 1.0); `taau_gpu_smoke_still_surface_ab` проходит; вся сюита `cargo test -p horizon-client --lib`; сборка без фичи `dlss`.
**Что ждёт RTX (обязательно проверить):**
1. Слайдер 50 / 80 / 100 / 200% при включённом DLSS: в `latest.log` строка `DLSS Super Resolution: [w, h] -> [W, H]` меняет render-размер (для 1440p: 50% → [1280, 720], 80% → [2048, 1152], 100% → [2560, 1440] (DLAA, 1:1), 200% → [2560, 1440]); картинка и FPS меняются от 50/80/100 (100% = DLAA, тяжелее апскейла); 200% при DLSS даёт render в размер выхода (не суперсэмплинг).
2. Статичная сцена после каждого переключения слайдера 10–15 с: нет дрожи/вибрации (регрессия #143), нет ghosting после смены масштаба (первый кадр с `InReset`).
3. Движение (`/airdef move 2`, налёт): модели не двоятся; дым/вспышки как раньше.
4. Живой прогон слайдера туда-сюда: без перезапуска, без микрофризов от пересоздания контекста на каждом шаге (в логе — строки размера, но не шторм пересозданий; reuse в диапазоне NGX). Если NGX Auto не принимает render-размер вне своего диапазона — в логе будет `DLSS context creation failed` / `DLSS evaluation failed` и fallback на native TAAU; прислать лог.
5. DLSS off → слайдер 200%: суперсэмплинг native TAAU (мир 2× окна, FPS ниже, картинка чище); DLSS on → возврат к capped-масштабу.
6. `HORIZON_HD_SCALE=0.67` по-прежнему переопределяет слайдер; film quality — полный размер.
## Быстрый старт ## Быстрый старт
1. Один раз запусти обычный Horizon Launcher, чтобы он подготовил ресурсы Minecraft 26.3. 1. Один раз запусти обычный Horizon Launcher, чтобы он подготовил ресурсы Minecraft 26.3.
@@ -52,16 +139,41 @@ DLSS Super Resolution: [1280, 720] -> [1920, 1080]
## Сборка самостоятельно вместо готового архива ## Сборка самостоятельно вместо готового архива
Нужны Visual Studio Build Tools с C++, Rust, clang, Vulkan SDK и NVIDIA DLSS SDK v310.9.1. Ветка — `kimi-work`. Нужны только Rust (с `x86_64-pc-windows-msvc` и `wasm32-unknown-unknown`) и Visual Studio Build Tools с C++. Ветка — `kimi-work`.
NVIDIA DLSS SDK, Vulkan SDK и LLVM ставить вручную больше не нужно: на Windows с NVIDIA RTX `airdef.py` сам скачивает всё, что читает `dlss_wgpu` при сборке (включая `libclang.dll` для bindgen), и кладёт `nvngx_dlss.dll` рядом с `horizon-client.exe`.
```powershell ```powershell
git clone --branch kimi-work https://gitea.maoniao.team/chexit/airdef.git git clone --branch kimi-work https://gitea.maoniao.team/chexit/airdef.git
cd airdef cd airdef
rustup target add x86_64-pc-windows-msvc wasm32-unknown-unknown rustup target add x86_64-pc-windows-msvc wasm32-unknown-unknown
$env:DLSS_SDK = "C:\path\to\DLSS" py tools\airdef.py all
$env:VULKAN_SDK = "C:\path\to\VulkanSDK"
cargo build --manifest-path horizon/Cargo.toml -p horizon-client --target x86_64-pc-windows-msvc --features "mods,dlss"
py tools\airdef.py mod
``` ```
Скопируй `horizon/target/x86_64-pc-windows-msvc/debug/horizon-client.exe`, `airdef-mod/target/horizon-mod/airdef.hmod`, `dist/play.bat`, `dist/test-dlss.bat`, `dist/test-native.bat` и `$env:DLSS_SDK/lib/Windows_x86_64/rel/nvngx_dlss.dll` в одну папку. Для реальной игры нужен и `latest.log` с фактическим backend/кадрами. `all` делает `fork`, `game`, `mod`, `install`. На Windows + RTX шаг `game`:
1. Определяет новейший стабильный тег `v310.9.x` в [NVIDIA/DLSS](https://github.com/NVIDIA/DLSS) через GitHub API; при недоступности API берёт закреплённый `v310.9.1`.
2. Скачивает выборочно (не весь репозиторий): `include/*.h`, `lib/Windows_x86_64/x64/nvsdk_ngx_d.lib` и `nvsdk_ngx_s.lib`, `lib/Windows_x86_64/rel/nvngx_dlss.dll` (~59 МБ). Итог — около 67 МБ один раз.
3. Скачивает только заголовки [KhronosGroup/Vulkan-Headers](https://github.com/KhronosGroup/Vulkan-Headers) в `Include/`: полный LunarG SDK не нужен, `build.rs` линкует Vulkan сам.
4. Ищет уже установленный `libclang.dll` (`LIBCLANG_PATH`, `PATH`, `C:\Program Files\LLVM\bin`, LLVM из Visual Studio). Если его нет — скачивает NuGet-пакет [`libclang.runtime.win-x64`](https://www.nuget.org/packages/libclang.runtime.win-x64) (~34 МБ) и распаковывает из него только `runtimes/win-x64/native/libclang.dll`.
5. Собирает с `--features mods,dlss`, передавая `DLSS_SDK`, `VULKAN_SDK` и `LIBCLANG_PATH` в окружение cargo, затем копирует свежий `nvngx_dlss.dll` рядом с собранным `horizon-client.exe`.
Кэш и повторные сборки:
```text
.horizon-cache/dlss-sdk/<tag>/ include/ + lib/Windows_x86_64/{x64,rel} + airdef-install.json
.horizon-cache/vulkan-headers/<tag>/ Include/vulkan/ + Include/vk_video/ + airdef-install.json
.horizon-cache/libclang/<version>/ libclang.dll + airdef-install.json
```
Повторный запуск видит маркер и полный набор файлов и ничего не скачивает. Удалить кэш можно целиком — при следующей сборке он появится снова.
Ручное переопределение по-прежнему работает и имеет приоритет: если задать `DLSS_SDK` (корень с `include/nvsdk_ngx*.h` и `lib/Windows_x86_64/x64/`), `VULKAN_SDK` (с `Include/vulkan/vulkan.h`) и/или `LIBCLANG_PATH` (каталог с `libclang.dll`), автоскачивание для этого компонента не выполняется. Если явный путь неполный, `airdef.py` предупреждает и собирает `mods`; чтобы вернуть автоскачивание, убери переменную.
Ручная альтернатива для libclang: `winget install LLVM.LLVM`, затем задать `LIBCLANG_PATH` на каталог `bin` установленного LLVM (там лежит `libclang.dll`).
При любой сетевой ошибке, недоступном GitHub/nuget.org, неполном скачивании или если libclang так и не нашёлся, сборка не падает: печатается предупреждение, ставится `--features mods`, и игра остаётся на native TAAU. На macOS и Linux, а также на Windows без RTX, автоскачивания нет — сразу `mods`.
Если bindgen всё же пишет `Unable to find libclang`, проверь `LIBCLANG_PATH`: он должен указывать на каталог, в котором лежит `libclang.dll` (не на сам файл). Удобно один раз выполнить `winget install LLVM.LLVM` и указать `C:\Program Files\LLVM\bin`.
Если `nvngx_dlss.dll` нужен отдельно (например, для ручной раскладки), он лежит в кэше: `.horizon-cache/dlss-sdk/<tag>/lib/Windows_x86_64/rel/nvngx_dlss.dll`. Его версия совпадает с самым новым тегом, который нашёл `airdef.py`.
+5 -2
View File
@@ -63,8 +63,11 @@ runtime закреплённого движка. Используется вре
## Акустика и владение захватом (API 27) ## Акустика и владение захватом (API 27)
Текущий pin: `2bcce642362ab5d3f04de193e390d8293cd1bf30` (API 31; `render.project` — проекция Текущий pin: `3428a571bda382c9c5b388710efd1baf92ed8d9c` (API 31; GPU-instancing одной
мировых точек через камеру последнего отрисованного кадра, #132; ниже — staging, cascades, массовой группы моделей мода с fallback до паритета и диагностическим toggle
`model-instancing`, #147; ниже — decode motion buffer по history grid в TAA/TAAU #143,
порядок DLSS-кадра #137, `render.project` — проекция мировых точек через камеру
последнего отрисованного кадра, #132; ниже — staging, cascades,
previous-frame motion и feature-gated DLSS SR backend #124, API 30). Акустические previous-frame motion и feature-gated DLSS SR backend #124, API 30). Акустические
`render.acoustics-status` и `render.capture-owner-status` возвращают поколение, `render.acoustics-status` и `render.capture-owner-status` возвращают поколение,
`available`, `enabled`, `request-accepted`, `prepared` и причину. В игре всё это показывает `available`, `enabled`, `request-accepted`, `prepared` и причину. В игре всё это показывает
+33 -10
View File
@@ -47,7 +47,7 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
## Конвейер кадра (HD включён) ## Конвейер кадра (HD включён)
Цели мира (G-буфер, AO, освещение, пост-проход мода) — в «масштабированном» разрешении мира (`world_post`; при `HORIZON_HD_SCALE` < 1 оно меньше окна), цели после TAA (история, bloom, tonemap) — в разрешении окна. HDR — `Rgba16Float`. Глубина камеры — reversed-Z Цели мира (G-буфер, AO, освещение, пост-проход мода) — в «масштабированном» разрешении мира (`world_post`; масштаб — слайдер Resolution Scale настроек Horizon, `HORIZON_HD_SCALE` переопределяет его, при DLSS 100% = 1:1 (DLAA), < 100% — апскейл; при масштабе < 1 оно меньше окна), цели после TAA (история, bloom, tonemap) — в разрешении окна (или мира, если он суперсэмплирован больше окна). HDR — `Rgba16Float`. Глубина камеры — reversed-Z
(`Depth32Float`, 1 = близко, 0 = далеко). Позиции везде относительно камеры (camera-relative), мир — в `f64` (`Depth32Float`, 1 = близко, 0 = далеко). Позиции везде относительно камеры (camera-relative), мир — в `f64`
на CPU. на CPU.
@@ -94,7 +94,7 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
совпадают, history UV = current UV + motion/render_size; вода, прозрачность и небо используют прежний совпадают, history UV = current UV + motion/render_size; вода, прозрачность и небо используют прежний
depth/camera fallback. Джиттер добавляется к depth/camera fallback. Джиттер добавляется к
`view_projection` только при HD (публичная матрица без джиттера); рука и HUD рисуются после tonemap и не дрожат. `view_projection` только при HD (публичная матрица без джиттера); рука и HUD рисуются после tonemap и не дрожат.
**TAAU**: если мир меньше окна (`HORIZON_HD_SCALE=0.67`), тот же проход (`fs_taau`, в таймингах `hd taau`) восстанавливает **TAAU**: если мир меньше окна (слайдер Resolution Scale < 100%, DLSS апскейл при < 100% или `HORIZON_HD_SCALE=0.67`), тот же проход (`fs_taau`, в таймингах `hd taau`) восстанавливает
полное разрешение. История, bloom и tonemap — в разрешении окна. Для каждого пикселя выхода берётся 3×3 выборки мира полное разрешение. История, bloom и tonemap — в разрешении окна. Для каждого пикселя выхода берётся 3×3 выборки мира
вокруг (с учётом джиттера в `taa_params.zw`), веса — полином, аппроксимирующий Lanczos-2, по расстоянию от центра вокруг (с учётом джиттера в `taa_params.zw`), веса — полином, аппроксимирующий Lanczos-2, по расстоянию от центра
пикселя выхода до выборки; variance clip в YCoCg по тем же 3×3; глубина — ближайшая из 2×2; история (Catmull-Rom, пикселя выхода до выборки; variance clip в YCoCg по тем же 3×3; глубина — ближайшая из 2×2; история (Catmull-Rom,
@@ -231,7 +231,10 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
| #36: ванильная вода не рисует цвет в HD (`fs_translucent` при `Globals.hd_flags.x`, глубину оставляет); прозрачное перед водой (`d` ближе `wd`) не отключает HD-воду: вода считается на освещённом дне и добавляется к сцене с весом 0.7; преломление не берёт тексели с таким прозрачным (`textureGather` по альфе) | готово (проверены стекло; частицы и scale 0.67 не проверялись) | в рабочем дереве форка | | #36: ванильная вода не рисует цвет в HD (`fs_translucent` при `Globals.hd_flags.x`, глубину оставляет); прозрачное перед водой (`d` ближе `wd`) не отключает HD-воду: вода считается на освещённом дне и добавляется к сцене с весом 0.7; преломление не берёт тексели с таким прозрачным (`textureGather` по альфе) | готово (проверены стекло; частицы и scale 0.67 не проверялись) | в рабочем дереве форка |
| #45: `gfx/hd.rs` разделён на модуль `gfx/hd/` (по файлу на проход: `shadows`, `gbuffer`, `ao`, `sky`, `volumes`, `lighting`+`tiles`, `water`, `taa`, `bloom`, `tonemap`, `frame`), WGSL вынесен в `.wgsl` (`include_str!`, общая прелюдия), у каждого прохода своя структура ресурсов/пайплайнов; контракты цвета, глубины, альф и времени записаны в `hd/mod.rs` и в начале файлов проходов; тесты привязок и размера `HdFrame`. Вид не менялся (сверка `tools/hd_bench.py`) | готово | в рабочем дереве форка | | #45: `gfx/hd.rs` разделён на модуль `gfx/hd/` (по файлу на проход: `shadows`, `gbuffer`, `ao`, `sky`, `volumes`, `lighting`+`tiles`, `water`, `taa`, `bloom`, `tonemap`, `frame`), WGSL вынесен в `.wgsl` (`include_str!`, общая прелюдия), у каждого прохода своя структура ресурсов/пайплайнов; контракты цвета, глубины, альф и времени записаны в `hd/mod.rs` и в начале файлов проходов; тесты привязок и размера `HdFrame`. Вид не менялся (сверка `tools/hd_bench.py`) | готово | в рабочем дереве форка |
| #39: веер восхода `vanilla_sunrise_weight` отсекается до цикла по 16 треугольникам выше горизонта (знак x стороны солнца и наклон ≤ α/3; проверено перебором 200 тыс. лучей без пропусков); `hd lighting` на рассвете 5.3 → 3.3 мс (M-серия, 2560×1440) | готово | в рабочем дереве форка | | #39: веер восхода `vanilla_sunrise_weight` отсекается до цикла по 16 треугольникам выше горизонта (знак x стороны солнца и наклон ≤ α/3; проверено перебором 200 тыс. лучей без пропусков); `hd lighting` на рассвете 5.3 → 3.3 мс (M-серия, 2560×1440) | готово | в рабочем дереве форка |
| #126 (этап 1): retained-геометрия моделей мода — грани резолвятся против атласа раз в generation пака, кадр только трансформирует и освещает; motion #124 из тех же граней без второго bake; счётчики `mod_models` в `stats`; вершины бит-в-бит прежние (тест). `entity_geometry` CPU 5.71 → 1.57 мс avg, p95 8.7 → 2.2 (M5, raid-сцена Polygon) | готово; GPU-instancing — следующий этап | форк `a861c1ed2` (`kimi-work-124`), замеры `docs/measurements/issue-126-first-stage/` | | #126 (этап 1): retained-геометрия моделей мода — грани резолвятся против атласа раз в generation пака, кадр только трансформирует и освещает; motion #124 из тех же граней без второго bake; счётчики `mod_models` в `stats`; вершины бит-в-бит прежние (тест). `entity_geometry` CPU 5.71 → 1.57 мс avg, p95 8.7 → 2.2 (M5, raid-сцена Polygon) | готово | форк `a861c1ed2` (`kimi-work-124`), [замеры](measurements/issue-126-first-stage/) |
| #147: GPU-instancing одной массовой группы моделей мода | готово | форк `3428a571b`, [замеры](measurements/issue-147-instancing/) |
| #147: источники света, покрывающие весь экран, хранятся один раз. Шейдер объединяет общие и локальные битовые маски и читает источники по порядку | готово | форк `78591703b` и `0f77eb5c2`, [замеры на RTX 3060](measurements/hd-light-tiles-smoke-skip/rtx3060.md) |
| #126: объёмный туман пропускает пустые области сетки дыма, сохраняя положения оставшихся шагов | готово | форк `4215e8999`, [замеры](measurements/hd-light-tiles-smoke-skip/) |
| Облака в воде, перистые, туман по рельефу, лучи, тень облаков при низком солнце, дальний дым (768 блоков) | готово, в рабочем дереве форка; тайминги не сняты чисто | не закоммичено | | Облака в воде, перистые, туман по рельефу, лучи, тень облаков при низком солнце, дальний дым (768 блоков) | готово, в рабочем дереве форка; тайминги не сняты чисто | не закоммичено |
| Материалы и блики (план 5): G-буфер `levels.zw` = шероховатость, металличность; GGX-блик солнца с Френелем и отражение неба (`sky_along`/`atmosphere_sky`) в `shade_surface`; мокрые поверхности и лужи в дождь (`HdFrame.surface`); `HORIZON_HD_SPECULAR=0` — выкл. | готово | в рабочем дереве форка | | Материалы и блики (план 5): G-буфер `levels.zw` = шероховатость, металличность; GGX-блик солнца с Френелем и отражение неба (`sky_along`/`atmosphere_sky`) в `shade_surface`; мокрые поверхности и лужи в дождь (`HdFrame.surface`); `HORIZON_HD_SPECULAR=0` — выкл. | готово | в рабочем дереве форка |
@@ -248,14 +251,19 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
Каждый пункт — самостоятельная задача. Перед началом прочитай `gfx/hd/mod.rs` (контракты) и файл нужного прохода. Каждый пункт — самостоятельная задача. Перед началом прочитай `gfx/hd/mod.rs` (контракты) и файл нужного прохода.
1. **TAAU — временной апскейлер** (поверх TAA) — СДЕЛАНО (патч 18, см. статус; масштаб — `HORIZON_HD_SCALE`, переопределяет «масштаб разрешения» настроек Horizon только для HD; поля в `HdSettings` нет). Осталось: LOD-bias текстур террейна, MetalFX. Исходное ТЗ: Мир и G-буфер рендерятся в `render_scale` (например 0.67), 1. **TAAU — временной апскейлер** (поверх TAA) — СДЕЛАНО (патч 18, см. статус; масштаб — слайдер Resolution Scale настроек Horizon, живой, без перезапуска; `HORIZON_HD_SCALE` — явное dev-переопределение поверх слайдера, film quality — полный размер; поля в `HdSettings` нет). Приоритет и DLSS-взаимодействие — `hd::scale_override(slider)` / `scale_for` и тест `the_resolution_slider_drives_hd_scale`; с DLSS слайдер capped на 1 (апскейлер), монотонно: 100% = 1:1 (DLAA), < 100% — апскейл, >100% — render в размер выхода; суперсэмплинг >1 — native TAAU без DLSS. Исправлен баг: раньше DLSS всегда пинил мир на 2/3 и слайдер игнорировался (ветка `agent/resolution-scale`, см. `docs/DLSS-TESTING.md`). Осталось: LOD-bias текстур террейна, MetalFX. Исходное ТЗ: Мир и G-буфер рендерятся в `render_scale` (например 0.67),
TAA-проход восстанавливает полное разрешение: история в полном разрешении, текущий кадр семплируется с учётом TAA-проход восстанавливает полное разрешение: история в полном разрешении, текущий кадр семплируется с учётом
джиттера (Catmull-Rom/Lanczos-веса по субпиксельной позиции), клиппинг окрестности как в TAA. Настройка джиттера (Catmull-Rom/Lanczos-веса по субпиксельной позиции), клиппинг окрестности как в TAA. Настройка
масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно
выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature
и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit: и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit:
world+linearize → NGX → delinearize; native TAAU остаётся fallback. По умолчанию DLSS рендерит world 2/3, world+linearize → NGX → delinearize; native TAAU остаётся fallback. #137 довёл порядок до контракта:
`HORIZON_HD_SCALE` переопределяет это. Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и film/tonemap/UI/capture/present записываются в encoder после delinearize и отправляются одним submit
без CPU sync (раньше они читали `taa.target` до записи NGX), а готовность нативной истории отделена от
истории NGX — первый fallback-кадр после DLSS не читает пустую/устаревшую native history. Render-размер DLSS — слайдер Resolution Scale
(capped на размер выхода; 100% = 1:1 DLAA, < 100% — апскейл), `HORIZON_HD_SCALE` переопределяет это; контекст NGX живёт под размер выхода,
render-размер едет в каждой evaluate (`partial_texture_size`) и меняется вживую без пересоздания, пока вписывается в диапазон NGX.
Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и
`--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build` `--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build`
на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен. на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен.
A/B инструкция — `docs/DLSS-TESTING.md`. A/B инструкция — `docs/DLSS-TESTING.md`.
@@ -390,15 +398,30 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
TAA/wind/clouds/volfog выключены, время заморожено): пиксели identical (0 px > 20/255 при TAA/wind/clouds/volfog выключены, время заморожено): пиксели identical (0 px > 20/255 при
сошедшемся LOD). Байты upload не менялись (~3.1 МБ/кадр вершин + ~4 МБ motion): этап убирает сошедшемся LOD). Байты upload не менялись (~3.1 МБ/кадр вершин + ~4 МБ motion): этап убирает
CPU-bake, не объём upload. Полная таблица и методика — `docs/measurements/issue-126-first-stage/`. CPU-bake, не объём upload. Полная таблица и методика — `docs/measurements/issue-126-first-stage/`.
- **Чем это не является.** Не GPU-instancing: вершины по-прежнему трансформируются на CPU и - **Продолжение.** В `3428a571b` для одной массовой группы моделей добавили GPU-instancing с
загружаются каждый кадр. Per-instance буферы, GPU-интерполяция и indirect draws — следующий общим мешем и буфером инстансов. Для остальных моделей используется описанный здесь CPU-путь.
этап направления A #126. Боевые правила, 20 Гц, API мода, DLSS/RT не тронуты; мод (WASM) тот же. [Замеры GPU-instancing](measurements/issue-147-instancing/)
## Тайлы света и пропуск пустых областей дыма (#147, #126)
- В `tiles.rs`/`light.wgsl` первый блок содержит маски поверхностного света, ореолов и прожекторов,
видимых по всему экрану. Для каждого тайла есть такой же блок местных масок. Шейдер объединяет
маски через OR и перебирает установленные биты в порядке источников. Размер блока зависит от
числа источников, полная ёмкость буфера рассчитана на 512 точечных источников.
- В `smoke.rs`/`fog.wgsl` бит на каждый блок из 8×8×8 ячеек учитывает окрестность 2×2×2, которую
может затронуть трилинейная выборка. Марш пропускает шаги внутри пустого блока, двигаясь по
прежней сетке выборок.
- Оба пути включены по умолчанию. Для запуска с контрольным вариантом есть
`HORIZON_HD_LIGHT_TILES=0` и `HORIZON_HD_SMOKE_SKIP=0`. В текущем процессе их переключают
команды сокета `light-tiles on|off` и `smoke-skip on|off`. [Методика и замеры](measurements/hd-light-tiles-smoke-skip/)
## Прожекторы: направленный свет и объёмный луч (#60) ## Прожекторы: направленный свет и объёмный луч (#60)
- **API 16** `render.set-spot-lights(list<spot-light>) -> bool`: апекс, направление, цвет, интенсивность, `range` (до 1024), внутренний/внешний полуугол (рад), `beam` (видимость луча 0..1). До 32 от мода, рисуются ближайшие 16 (`MAX_SPOTS`). Возвращает, рисует ли HD (`HORIZON_HD_SPOTS=0` выключает), иначе мод держит свой запасной луч. Игра интерполирует по id между двумя вызовами (`mod_models.rs: mod_spots`) и переводит в `HdSpot` (`gfx/hd/frame.rs`): координаты камеры, косинусы углов. - **API 16** `render.set-spot-lights(list<spot-light>) -> bool`: апекс, направление, цвет, интенсивность, `range` (до 1024), внутренний/внешний полуугол (рад), `beam` (видимость луча 0..1). До 32 от мода, рисуются ближайшие 16 (`MAX_SPOTS`). Возвращает, рисует ли HD (`HORIZON_HD_SPOTS=0` выключает), иначе мод держит свой запасной луч. Игра интерполирует по id между двумя вызовами (`mod_models.rs: mod_spots`) и переводит в `HdSpot` (`gfx/hd/frame.rs`): координаты камеры, косинусы углов.
- **Данные в шейдере**: `HdFrame.spots` (4 vec4 на источник: апекс+range, ось+cos внешнего, цвет+интенсивность, cos внутреннего+beam), число в `vfog.w`. Новых привязок нет. - **Данные в шейдере**: `HdFrame.spots` (4 vec4 на источник: апекс+range, ось+cos внешнего, цвет+интенсивность, cos внутреннего+beam), число в `vfog.w`. Новых привязок нет.
- **Тайлы**: заголовок тайла 5 слов (`TILE_WORDS`), пятое: маска конусов, бит j стоит, если выпуклая оболочка конуса (апекс и квадрат вокруг дальнего круга, `tiles.rs: spot_hull`, `cover_points`) на экране накрывает тайл. Маска служит и поверхностям, и лучу. Индекс тайла в WGSL: `* 5u`. - **Тайлы**: последнее слово блока содержит маску прожекторов. Бит j стоит, если проекция выпуклой
оболочки конуса (апекс и квадрат вокруг дальнего круга, `tiles.rs: spot_hull`, `cover_points`)
накрывает тайл. При освещении поверхности шейдер объединяет маски всего экрана и тайла.
- **Поверхности и цели**: `spot_light` (`spot.wgsl`, вставляется маркером `//SPOT` в `assemble`): конус с мягкой кромкой (smoothstep по косинусам), `I/(d²+1)`, окно в последние 3 блока до `range`, угол падения как у точечных; в `shade_surface` (земля, стены, дроны: они в G-буфере). Теней нет: свет обрывается по `range`, который мод ставит по броску оси на землю (`ground.world.probe`, раз в 4 тика). - **Поверхности и цели**: `spot_light` (`spot.wgsl`, вставляется маркером `//SPOT` в `assemble`): конус с мягкой кромкой (smoothstep по косинусам), `I/(d²+1)`, окно в последние 3 блока до `range`, угол падения как у точечных; в `shade_surface` (земля, стены, дроны: они в G-буфере). Теней нет: свет обрывается по `range`, который мод ставит по броску оси на землю (`ground.world.probe`, раз в 4 тика).
- **Луч**: `spot_beams` (`spot.wgsl`): пересечение луча взгляда с конусом (`spot_span`: квадратное уравнение конуса, обрезка по оси и range); внутри 8 шагов с джиттером IGN; яркое ядро, мягкая периферия; затухание `1/(1+d/70)`; плотность воздуха `max(spot_air, 0.0009)` (в чистом воздухе слабый луч, в дымке/тумане ярче и короче); фаза Henyey-Greenstein вперёд (на лампу ярче). Складывается (прозрачный), ограничен глубиной сцены: за стеной не продолжается; камера внутри конуса работает. **Туман вкл**: считается в `fs_fog` (`spot_air = fog_sigma`, длина до 1100 блоков, в небо тоже, не 192 как у тумана); **туман выкл или нет атмосферы**: тот же код в `fs_light` с постоянной плотностью `ambient.z`. - **Луч**: `spot_beams` (`spot.wgsl`): пересечение луча взгляда с конусом (`spot_span`: квадратное уравнение конуса, обрезка по оси и range); внутри 8 шагов с джиттером IGN; яркое ядро, мягкая периферия; затухание `1/(1+d/70)`; плотность воздуха `max(spot_air, 0.0009)` (в чистом воздухе слабый луч, в дымке/тумане ярче и короче); фаза Henyey-Greenstein вперёд (на лампу ярче). Складывается (прозрачный), ограничен глубиной сцены: за стеной не продолжается; камера внутри конуса работает. **Туман вкл**: считается в `fs_fog` (`spot_air = fog_sigma`, длина до 1100 блоков, в небо тоже, не 192 как у тумана); **туман выкл или нет атмосферы**: тот же код в `fs_light` с постоянной плотностью `ambient.z`.
- **Мод**: `sim/lights.rs`: голова прожектора шлёт один `SpotLight` (`Sam::spot_beam`, `lib.rs: spots`; конус 0.03/0.075 рад, range = свободная длина оси + 3.5). Цель «освещена» (`lit`) только в угле 0.05 от оси и если она не дальше свободной длины (за горой бонуса нет). Старые `airdef:beam` рисуются, только когда HD не рисует споты и эффекты включены (тоньше), при эффектах off луча нет. Точечный «шар» на цели остаётся лишь без спотов. В реплеях споты не шлются (реплей не пишет голову прожектора; #56/#58 отдельно). - **Мод**: `sim/lights.rs`: голова прожектора шлёт один `SpotLight` (`Sam::spot_beam`, `lib.rs: spots`; конус 0.03/0.075 рад, range = свободная длина оси + 3.5). Цель «освещена» (`lit`) только в угле 0.05 от оси и если она не дальше свободной длины (за горой бонуса нет). Старые `airdef:beam` рисуются, только когда HD не рисует споты и эффекты включены (тоньше), при эффектах off луча нет. Точечный «шар» на цели остаётся лишь без спотов. В реплеях споты не шлются (реплей не пишет голову прожектора; #56/#58 отдельно).
+27
View File
@@ -33,6 +33,33 @@
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это 137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
синтетический host без GPU и не приёмка Windows GUI. синтетический host без GPU и не приёмка Windows GUI.
### Прореживание не съедает короткие переходы (#142)
Прореживание #122 не различало непрерывную позу и дискретный факт: при большом числе меняющихся
РЛС оно пропускало целиком открытие крышки ТПК (`launch::OPEN_TICKS = 6` тиков, короче шага
sampling) и могло убрать уже записанный переход — ракета в реплее вылетала с нарисованной
закрытой крышкой, а `spent_cells` менялось только на следующем общем сэмпле.
Теперь `Recording::note_sams` вызывается каждый тик: позы по-прежнему снимаются на адаптивной
сетке `sam_step` из прежнего бюджета 32768, а дискретные переходы (`cap_cell`, `spent_cells`,
`radar_on`, режим и роль) и кадры открытия крышки пишутся на том тике, когда произошли, и
помечаются как события. Начало открытия дотягивается отдельным ключом на тик раньше, поэтому
ramp занимает ровно `OPEN_TICKS`, а не «примерно». Прореживание поз половинит только позы и
сохраняет события, первую и последнюю позу.
У событий свой явный бюджет — 4096 ключей на запись поверх 32768 поз; общий бюджет поз не
поднимался. При переполнении старые события перестают быть критическими (прореживаются как
позы), новейшие сохраняются: под записью с «болтливым» датчиком реплей остаётся ограниченным,
а свежий пуск — точным.
Проверки: `airdef-core` `sim::record::tests::decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch`
— 64 вращающихся РЛС + С-400 при `sam_step = 16`, выброс на тике 4103: за тик до выброса
`cap_open = 0.8333333` (как в контрольной записи без давления на бюджет), `spent_cells = 0`
до и `1` на тике выброса, отмена/закрытие и `radar_on` читаются на своих тиках, повторное
прореживание их не убирает;
`critical_transitions_have_their_own_explicit_budget` — 64 РЛС, переключающихся каждый тик,
1500 тиков: событий ровно 4096, позы в своём бюджете, новейшее переключение точное.
## Второй налёт из UI: событие, не тик ## Второй налёт из UI: событие, не тик
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000, Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,
+4 -4
View File
@@ -16,7 +16,7 @@
| `horizon/`, `.gitmodules` | Закреплённый сабмодуль отдельного форка Horizon | | `horizon/`, `.gitmodules` | Закреплённый сабмодуль отдельного форка Horizon |
| `tools/airdef.py` | Сборка мода и установка в папку игры | | `tools/airdef.py` | Сборка мода и установка в папку игры |
| `tools/gen_models.py`, `tools/gen_tex.py`, `tools/gen_sounds.py` | Генераторы контента (см. ниже) | | `tools/gen_models.py`, `tools/gen_tex.py`, `tools/gen_sounds.py` | Генераторы контента (см. ниже) |
| `tools/acoustics_check.py`, `tools/hd_bench.py` | Проверочные скрипты | | `tools/acoustics_check.py`, `tools/hd_bench.py`, `tools/raid_bench.py` | Проверочные скрипты (`raid_bench` — воспроизводимый бой+replay замер рендера, #147) |
| `docs/` | Документация (этот файл, `INSTALL.md`, `ACOUSTICS.md`, `HD-RENDERER.md`) | | `docs/` | Документация (этот файл, `INSTALL.md`, `ACOUSTICS.md`, `HD-RENDERER.md`) |
| `install.sh`, `play.sh`, `dist/` | Установка и запуск | | `install.sh`, `play.sh`, `dist/` | Установка и запуск |
| `run-home/`, `run-home-bench/`, `run-home-smoke/` | Тестовые игровые папки, не часть мода | | `run-home/`, `run-home-bench/`, `run-home-smoke/` | Тестовые игровые папки, не часть мода |
@@ -36,9 +36,9 @@
- `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow). - `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow).
- `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.json`, `catalog/specs.json` или `catalog/sounds.json`; `--check` проверяет актуальность. - `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.json`, `catalog/specs.json` или `catalog/sounds.json`; `--check` проверяет актуальность.
- `python3 tools/gen_models.py` — перегенерировать. - `python3 tools/gen_models.py` — перегенерировать.
- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях. - `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях. PNG сверяются по пикселям: байты файла зависят от zlib в сборке Pillow, и Linux (CI) или Windows сжимают те же пиксели иначе, чем macOS. Правленными вручную считаются только файлы, чьи байты разошлись со своей строкой manifest. Сама запись (`gen_models.py` без `--check`) и manifest остаются побайтовыми.
`catalog/specs.json` — единственный источник числовых профилей симуляции: строки `DroneSpec`, `MissileSpec`/`MissileKind` (включая RCS, seeker, звук пуска и голос мотора), `SamSpec` (оружие, части моделей, приводы, датчик), общие константы (гравитация, высота раскрытия «Орешника», логистика) и именованные наборы частей. `tools/gen_catalog.py` создаёт из него `airdef-mod/src/sim/specs_generated.rs` (включается в `mod.rs`; тот же файл компилирует `airdef-core`) и `airdef-mod/src/sim/unit_specs_generated.rs` (включается в `units.rs`). Эти два файла не редактировать вручную. `tools/airdef_assets/catalog.py::load_specs` проверяет схему, звуковые ссылки, наборы kinds против `content.json`, ссылки на именованные части и заполненность всех строк; `gen_catalog.py --check` в CI ловит расхождение. Значения — игровой масштаб, не реальные характеристики техники. `catalog/specs.json` хранит типы техники, параметры симуляции и их пульты. Из строки техники генератор получает Rust-тип, модель, боекомплект, регистрацию предмета и доступность в меню и командах. `raid_slot` задаёт позицию аппарата в сохранённых составах налётов. Для нового выбираемого аппарата используйте следующий свободный слот. `tools/gen_catalog.py` создаёт `catalog_entries.rs`, `specs_generated.rs` и `unit_specs_generated.rs` для мода и `airdef-core`. Валидатор проверяет уникальность ключей и слотов, ссылки на звуки, совместимость боекомплекта и именованные части. `gen_catalog.py --check` в CI проверяет актуальность Rust-файлов. Все параметры заданы в масштабе игры.
`catalog/sounds.json` хранит звуковые ID, дальности и наличие дальнего варианта; `tools/gen_catalog.py` экспортирует ID для Rust, а `tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`. `catalog/sounds.json` хранит звуковые ID, дальности и наличие дальнего варианта; `tools/gen_catalog.py` экспортирует ID для Rust, а `tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`.
@@ -55,7 +55,7 @@
- `tools/airdef_assets/bounds.py` экспортирует габариты итоговых моделей для headless-навигации; authored overrides входят в расчёт. - `tools/airdef_assets/bounds.py` экспортирует габариты итоговых моделей для headless-навигации; authored overrides входят в расчёт.
- `tools/gen_tex.py` отвечает за вывод процедурных текстур и иконок; переиспользуемые примитивы палитры также находятся здесь. - `tools/gen_tex.py` отвечает за вывод процедурных текстур и иконок; переиспользуемые примитивы палитры также находятся здесь.
- `tools/airdef_assets/texture_catalog.py` связывает стабильную палитру и процедурные функции с текстурами моделей, не смешивая каталог с геометрией. - `tools/airdef_assets/texture_catalog.py` связывает стабильную палитру и процедурные функции с текстурами моделей, не смешивая каталог с геометрией.
- `catalog/content.json` задаёт идентичности техники и предметов и оформление предметов; `tools/airdef_assets/icons.py` читает его и содержит чистую функцию рендера иконки с явными параметрами `(name, color, seed)`. - `catalog/content.json` задаёт варианты развёртывания существующей техники и оформление общих инструментов и пультов вариантов. `tools/airdef_assets/icons.py` получает оформление пультов из обеих таблиц и рендерит иконку по `(name, color, seed)`.
- `tools/airdef_assets/pipeline.py` проверяет manifest, рассчитывает безопасный план обновления и откатывает записи при исключении. - `tools/airdef_assets/pipeline.py` проверяет manifest, рассчитывает безопасный план обновления и откатывает записи при исключении.
- `airdef-mod/source-assets/assets/airdef/` — источник авторских переопределений. Генератор объединяет его с процедурными ресурсами во временном дереве, проверяет ссылки/JSON/PNG, затем устанавливает runtime-файлы. - `airdef-mod/source-assets/assets/airdef/` — источник авторских переопределений. Генератор объединяет его с процедурными ресурсами во временном дереве, проверяет ссылки/JSON/PNG, затем устанавливает runtime-файлы.
- `airdef-mod/assets/` и `airdef-mod/data/` — упакованные generated output. Не редактируйте их вручную; добавляйте авторские исходники в `source-assets`. - `airdef-mod/assets/` и `airdef-mod/data/` — упакованные generated output. Не редактируйте их вручную; добавляйте авторские исходники в `source-assets`.
+76
View File
@@ -0,0 +1,76 @@
# Веб-пульт AirDef
Пульт работает рядом с Horizon. «Рельеф» показывает загруженные чанки цветами игровой карты. «К игроку» возвращает к текущей позиции в мире. В режиме «Радар» доступны кольца расстояния и выбор работающей станции с её номинальной дальностью. Обе подложки используют одинаковые отметки. До подтверждения класса контакт помечен знаком вопроса, затем получает силуэт соответствующего типа. На карте видны отметки сети, своя техника, объекты и перехватчики. Карточка показывает состояние, источник отметки и связанные записи. В «Истории» можно выбрать налёт, отфильтровать события по времени или ID и собрать доступные звенья цепочки контакта. Под шкалой отмечены попадания, промахи и отказы. События рядом по времени открываются списком из одного маркера. Нажатие на запись или отметку открывает детали и ближайший сохранённый кадр в пределах пяти игровых секунд. Событие хранит своё точное игровое время. Архив сохраняет отметки примерно раз в секунду. Подложка рельефа загружается отдельно и доступна для текущего мира. Если подложку уже открывали в этой вкладке, она может оставаться видимой в повторе той же сессии.
## Запуск на компьютере с игрой
Соберите и установите актуальную версию стандартной командой `python3 tools/airdef.py all`. На Windows вместо `python3` можно использовать `py -3`. Затем запустите пульт из каталога AirDef.
```text
python3 tools/airdef.py web
```
Команда запускает Horizon и выводит адрес `http://127.0.0.1:8765` и одноразовый код просмотра. Откройте мир в Horizon, откройте адрес в браузере и введите код. Параметры игры передаются после `--` как при обычном запуске.
Параметр `--allow-launch` выдаёт отдельный код оператора. В разделе «Сценарий» выберите готовый состав или отредактируйте черновик, откройте предпросмотр и подтвердите запуск. Ответ игры появляется внизу формы. После обрыва связи браузер запрашивает результат по ID уже отправленного запроса. Для нового запуска нужно снова подтвердить сценарий.
Параметр `--allow-debug` выдаёт отдельный код анализа. В этом профиле в меню ракурсов доступны донесения игрового противника и «Истина» для песочницы. Обычный просмотр и профиль оператора получают только картину игрока. Архив карт тоже записывается с этого ракурса.
Код действует 10 минут и принимается один раз. Чтобы выдать новые коды, перезапустите пульт. Уже подключённые устройства сохраняют доступ до отзыва или истечения 30 дней. «Отвязать» отзывает доступ текущего устройства. `--reset-pairings` отзывает все устройства с этого компьютера.
## Планшет
Для Tailscale используйте Serve по инструкции ниже. Для прямого подключения по локальной сети укажите LAN-адрес интерфейса ПК и HTTPS-адрес, для которого у вас есть PEM-сертификат и ключ. Планшет должен доверять сертификату и открывать адрес ровно с тем именем или IP, которое в нём указано.
```text
python3 tools/airdef.py web --listen 192.168.1.170 --port 8765 --origin https://airdef.home:8765 --cert cert.pem --key key.pem --allow-launch --allow-debug
```
Замените адрес, имя и пути на свои. Используйте адрес пульта, который выводится при запуске. Для установки на Android откройте меню Chrome и выберите установку приложения. На iPad откройте Safari, меню «Поделиться» и «На экран Домой». [Требования браузеров к установке PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable).
### Tailscale Serve на Windows
Установите Tailscale на ПК и планшет, войдите на обоих в одну сеть и включите MagicDNS. В PowerShell с правами администратора на ПК запустите
```powershell
tailscale serve 8765
```
При первом запуске разрешите включение HTTPS, если Tailscale предложит это сделать. Скопируйте показанный адрес `https://device.tailnet.ts.net` целиком. Оставьте это окно открытым; в другом окне PowerShell из каталога AirDef запустите пульт, подставив свой адрес.
```powershell
py -3 tools/airdef.py web --tailscale https://device.tailnet.ts.net --allow-launch
```
Откройте показанный HTTPS-адрес на планшете и введите нужный одноразовый код с ПК. `--allow-launch` и `--allow-debug` необязательны. Для другого локального порта укажите одинаковый порт в `--port` и команде `tailscale serve`. Остановка Serve: Ctrl+C в его окне. Подробнее: [Tailscale Serve](https://tailscale.com/docs/features/tailscale-serve), [команда Serve](https://tailscale.com/docs/reference/tailscale-cli/serve).
Serve предоставляет доступ внутри tailnet согласно его правилам доступа; сопряжение по коду по-прежнему необходимо. Пульт слушает только `127.0.0.1`, а HTTPS завершается в Tailscale. Другие программы на самом ПК могут обращаться к локальному порту, поэтому используйте доверенный компьютер. Не включайте Funnel и не публикуйте сокет Horizon: Serve должен проксировать только порт веб-пульта. Режим `--tailscale` нельзя совмещать с `--listen` на внешнем интерфейсе, `--origin`, `--cert` или `--key`.
В портретной ориентации список находится под картой, в альбомной при достаточной ширине сбоку. Перетаскивание смещает карту, жест двумя пальцами меняет масштаб. Без связи виден последний загруженный снимок и уже открытая история. Устройство сохраняет положение карты, выбранную карточку и черновик. Для запуска требуется связь с игрой.
## Архив и подключение
Сервер хранит журнал в `airdef-panel/history.sqlite3` внутри каталога игры. Он переживает перезапуск игры и пульта. Хранятся до 3 600 снимков карты, 30 000 событий и 400 налётов. В интерфейсе видны пропуски журнала и ограничения хранения. Браузер дополнительно хранит до 600 загруженных событий, 20 открытых исторических кадров и отметки шкалы последних восьми просмотренных налётов. Отвязка устройства очищает браузерный архив.
Для присоединения к уже запущенному Horizon укажите `--attach путь_к_локальному_сокету`. На Windows это JSON-файл с локальным портом и токеном Horizon. Для `--dev-mod` путь к данным мода можно задать через `--mod-data`. Пульт запрашивает снимок игры каждые 0,5 секунды при нормальной связи. Открытая вкладка проверяет обновления каждые 0,65 секунды, в фоновой вкладке опрос приостанавливается. Рельеф запрашивается отдельными фрагментами по мере просмотра. После первой загрузки браузер получает изменения карты от своей версии. После долгого обрыва связи, перезапуска пульта или смены мира браузер получает полный снимок. Сам сокет Horizon доступен только на ПК. Внутренние команды мода экспортируют ограниченный снимок и подтверждают структурированный сценарий. Сериализация HTTP, обработка подключений и запись архива происходят в процессе пульта.
Полезные проверки из каталога проекта
```text
python3 -m unittest discover -s tools -p test_web_panel.py
python3 tools/airdef.py test-wasm
```
## Замер времени кадра
На Mac с M5 сравнили одну и ту же короткую запись боя с двумя аппаратами. После прогрева бралось окно в 6 секунд, 180–181 кадр. В первом режиме опрос игры был приостановлен. Во втором клиент регулярно читал карту и историю. В третьем одновременно висел запрос с незавершёнными HTTP-заголовками.
| Режим | p95 кадра, мс | p99 кадра, мс |
| --- | ---: | ---: |
| Опрос приостановлен | 34,61 | 35,33 |
| Карта и история открыты | 35,00–35,09 | 36,05–36,38 |
| Дополнительный медленный запрос | 34,84–35,04 | 35,50–35,64 |
Эти числа относятся к короткой записи на Mac. Для большого налёта и Windows сопоставимых замеров времени кадра пока нет.
В отдельной проверке переподключения карта с 77 комплексами получила 391 байт изменений при полном размере снимка 18 621 байт. Объём обновления зависит от числа изменившихся отметок.
@@ -0,0 +1,77 @@
# Замеры HD-рендера на M5, 24 ноября 2026
Вариант «до» — Horizon `b4c68a78b`. Вариант «после» включает общие списки тайлов света
(`78591703b`, #147) и пропуск пустых областей сетки дыма (`4215e8999`, #126). AirDef закрепляет
обе правки коммитом `4b8fef6`. Замеры ниже сняты на MacBook Air M5, macOS/Metal, вне экрана.
На Windows проверили обе правки и следующее изменение тайлов. [Замеры на RTX 3060](rtx3060.md)
## Нагруженная сцена, 2560×1440
Четыре отдельных запуска старого и нового клиентов в порядке «до → после → после → до».
В каждом запуске использовался `server-thread`, масштаб 100%. Сцены расходились между
запусками по количеству эффектов. FPS и времена описывают получившиеся сцены и не дают
изолированного эффекта отдельной правки. Все времена в таблице указаны в миллисекундах.
| Прогон | FPS | Кадр p50 | Кадр p95 | GPU среднее | CPU среднее | Фаза `render` средняя |
|---|---:|---:|---:|---:|---:|---:|
| До 1 | 11,02 | 69,07 | 150,60 | 87,24 | 42,65 | 27,43 |
| После 1 | 15,11 | 49,39 | 218,42 | 48,49 | 22,19 | 12,66 |
| После 2 | 17,26 | 54,32 | 76,78 | 56,73 | 8,38 | 5,02 |
| До 2 | 6,49 | 136,91 | 342,89 | 47,43 | 146,56 | 83,01 |
`render` — время фазы на потоке окна по настенным часам за вычетом ожиданий, учтённых
рендерером. До правок профиль потока окна отдавал около 21–25% сэмплов на `tile_lists`.
На новом клиенте фаза короче в обоих прогонах. В p95 кадра виден большой разброс даже
между двумя запусками одного бинарника. В каждом окне есть один скриншот, который
добавляет задержку кодирования PNG. Он входит в исходную статистику выше.
## Дым, 2560×1440
Один клиент и одна запись, `in-frame`. Шесть 10-секундных окон с `smoke-skip` в порядке
`on, off, off, on, on, off`. Запись продолжалась между окнами, поэтому плотность дыма
менялась по ходу теста. Таблица показывает среднее время GPU из каждого окна.
| Участок записи | Пропуск вкл., мс | Пропуск выкл., мс | Разница |
|---|---:|---:|---:|
| Первые два окна, с заметным дымом | 46,87 | 52,47 | −5,60 мс (−10,7%) |
| Последние четыре окна, дым рассеялся | 40,58 | 41,58 | −1,00 мс (−2,4%) |
Пиксельная сверка проводилась на одном кадре в том же процессе с переключателями
`smoke-skip on|off` и `light-tiles on|off`. Маска покрыла 54,75% кадра. На этой области
все устойчивые отклонения лежали в пределах 2 уровней из 255 для обеих правок.
Контрольное повторение одного состояния дало один пиксель с устойчивой разницей ≥3.
Движущиеся области, включая воду, лежат за пределами этой проверки.
## Покой, `polygon_noon`, 2560×1440
Первый замер старого клиента дал 28,76 мс GPU при бюджете 18 мс и вернул `exit 1`.
У нового клиента запуск сорвался из-за относительного пути, а отчёт упал с `KeyError: 'frame'`.
После исправления сделаны четыре запуска в порядке «до → после → после → до» с паузами
45 секунд, одинаковым 8-секундным окном и выключенными таймингами отдельных проходов.
[Драйвер `hd_bench.py`](../../../tools/hd_bench.py)
| Прогон | SHA-256 бинарника (начало) | GPU среднее, мс | Кадр p95, мс | FPS |
|---|---|---:|---:|---:|
| До 1 | `8649de0e6ed491c0` | 28,41 | 31,62 | 35,16 |
| После 1 | `e6ae3d715b3a4ba8` | 26,56 | 28,73 | 37,61 |
| После 2 | `e6ae3d715b3a4ba8` | 27,08 | 29,48 | 36,85 |
| До 2 | `8649de0e6ed491c0` | 27,98 | 30,66 | 35,66 |
В этой серии время GPU уменьшилось в среднем с 28,19 до 26,82 мс (−4,9%). В более ранних
окнах покоя того же стенда значения были 24,61–26,76 мс до и 26,46–26,50 мс после. Данные
показывают разброс между сериями, поэтому улучшение в покое за пределами `polygon_noon`
остаётся неподтверждённым. Все четыре повторных запуска собрали данные и вернули `exit 1`
по бюджету. Проверка с отсутствующим бинарником вернула `exit 2` и сохранила оба отчёта.
## Паузы в повторах
В обоих бинарниках есть кадры порядка 220–230 мс. `frame_ms` — интервал между началами
кадров. `cpu_ms` записывается внутри обработки кадра за вычетом учтённого ожидания, а
результаты GPU считываются асинхронно по мере готовности. Вычитание `frame_ms − cpu_ms − gpu_ms`
по одинаковым индексам не измеряет время ожидания одного кадра.
Сопоставление последовательности `cpu_ms` с логом `slow frame` показало, что часть длинных
интервалов возникает за пределами замеренного вызова рендера. Например, в `raid_after2`,
окно `replay_before`, перед интервалом 232,2 мс лог показывает 20,6 мс работы кадра и
12,8 мс в полном спане `renderer`. Для локализации оставшегося времени нужны отдельные
замеры между кадрами. В этих запусках использовался offscreen, где нет оконного swapchain.
@@ -0,0 +1,78 @@
# HD на Ryzen 5 5600X и RTX 3060
24 ноября 2026. Windows, Vulkan, RTX 3060 12 ГБ, драйвер 617.14, вывод 2560×1440.
Основные прогоны вне экрана. Внутренний размер 1664×936 при масштабе 65%, дальность
отрисовки 25 чанков. HD, VSync и звук выключены, ресурсы и `airdef.hmod` одинаковые. Замеры
снимались в копии Polygon с фиксированной камерой, 96 неподвижными источниками света
и 128 сегментами дыма. В каждом окне 8 секунд работы прогретого рендера.
## Ранее опубликованные правки
Два окна на вариант. Старая сборка была на ПК до начала работы, свежая собрана из
Horizon `4215e8999`. Для каждой пары режим сглаживания принудительно переключался
через `horizon-ctl dlss`, а `dlss status` подтверждал состояние после каждого окна.
| Вариант | Старая сборка, FPS | `4215e8999`, FPS | GPU до → после, мс | CPU до → после, мс |
|---|---:|---:|---:|---:|
| DLSS, 65% | 61,3 | 61,1 | 16,18 → 16,26 | 7,19 → 5,07 |
| TAAU, 65% | 110,6 | 111,0 | 8,94 → 8,92 | 6,69 → 4,53 |
CPU в таблице — метрика движка по настенным часам за вычетом учитываемых ожиданий.
GPU ограничивает FPS в обеих парах. В первых кросс-прогонах режимы различались
даже при одинаковом `HORIZON_DLSS=1`: движок открывал устройство для DLSS, затем
настройка из сохранения AirDef переключала его во время загрузки мира. Эти прогоны
помогли обнаружить расхождение настройки. В таблицу вошли сравнения с явным
переключением режима после загрузки.
## Стоимость DLSS на этом стенде
На `4215e8999` два окна с DLSS дали 60,1–61,2 FPS и 16,23–16,52 мс GPU. Два окна
TAAU между ними дали 107,4–108,1 FPS и 9,15–9,21 мс GPU. Масштаб, камера и эффекты
одинаковы, а алгоритм временного сглаживания менялся в одном процессе. Это замер
пути DLSS целиком, включая подготовку входа и обработку выхода.
Отдельное переключение пропуска пустого дыма с активным DLSS дало 16,32–16,45 мс
GPU с пропуском против 16,62 мс в обоих контрольных окнах. Эта сцена показывает
малый выигрыш пропуска дыма. При замере отдельных проходов `hd lighting` занимал
около 2,37 мс, `hd fog` около 0,74 мс, обе сетки дыма суммарно около 0,24 мс.
## Битовые маски тайлов света
Horizon `0f77eb5c2` объединяет маски всего экрана и тайла через OR, затем читает
установленные биты в исходном порядке источников. На тайл приходится до 33 слов
по 32 бита, включая маску прожекторов. При внутреннем разрешении 2560×1440 буфер
уменьшился с 16,14 до 0,91 МиБ.
Парные серии в порядке «списки → маски → маски → списки». В тяжёлой сцене
480 источников света и 480 сегментов дыма. Показаны средние по окнам при 65%.
| Сцена и режим | Списки, FPS | Маски, FPS | GPU, мс | CPU, мс |
|---|---:|---:|---:|---:|
| 96 источников, DLSS | 61,25 | 63,40 | 16,21 → 15,67 | 5,32 → 4,27 |
| 96 источников, TAAU | 110,79 | 117,03 | 8,93 → 8,47 | 4,53 → 3,69 |
| 480 источников, DLSS | 36,98 | 41,63 | 26,85 → 23,89 | 8,62 → 6,21 |
Строка TAAU включает одну пару, строки DLSS по две. На тяжёлой сцене до
первоначальных правок наблюдалось 36,32 FPS, GPU 27,38 мс, CPU 21,98 мс.
Битовые маски сократили средний GPU-кадр на 11% относительно списков.
На масках сравнили DLSS и TAAU прямо в тяжёлой сцене. Вне экрана переключение
DLSS → TAAU сократило время GPU с 23,85–24,11 до 16,83–16,85 мс и подняло
FPS с 41,3–41,7 до 59,0. В полноэкранном Vulkan с `Immediate` тот же тест
дал 38,3–40,5 → 57,7–57,8 FPS. В обоих случаях использовался один процесс,
тот же масштаб 65% и порядок DLSS → TAAU → TAAU → DLSS. Сцена воспроизводит
нагрузку на свет и дым. Замер конкретного игрового эпизода с 25 FPS остаётся
отдельной проверкой.
Пиксельная проверка на RTX 3060 использовала неподвижную каменную площадку, по четыре
кадра на режим. При переключении масок и полного перебора источников в одном
процессе устойчивые расхождения на 63,34% статичных пикселей не превысили одного
уровня из 255. При сравнении двух отдельных бинарников на 77,31% статичных пикселей
максимум составил три уровня, такую разницу дали 19 пикселей.
Проверки кода включают оракул покрытия всех тайлов для 500 источников, порядок
суммирования, неполное последнее слово, прожекторы и трансляцию WGSL в HLSL.
Прошли 36 тестов HD и отдельный графический тест TAAU на Metal.
Начала SHA-256 бинарников. Сборка с ПК `20a13b781985d436`, `4215e8999`
`a3e3b9752e0297e4`, битовые маски `e7750bf06b14eb31`.
@@ -0,0 +1,103 @@
# Issue #126, пункт 4: пропуск рэймарча огненного шара при нулевом fade — проверка
Мёртвая работа в `airdef-mod/shaders/effects.wgsl` (раздел «2. Fireballs and their smoke»). Счёт и
картинка не менялись ни на пиксель; меняется только то, что при `fade == 0` цикл марша больше не
крутится.
## Изменение
```wgsl
// было (для каждого шара): ds, затем сразу цикл
for (var s = 0; s < steps; s++) { ... let n = fbm(...); ... }
// стало
if fade > 0.0 {
for (var s = 0; s < steps; s++) { ... } // тот же цикл, тот же выход по trans < 0.02
}
// свечение огня после марша осталось; оно само под `if heat > 0.0`
```
Почему картинка та же: при `fade == 0` на каждом шаге `density = shape * (1.2 + n*2.0) * fade == 0`,
значит `absorb = 1 - exp(0) == 0`, `lit += trans * absorb * c` ничего не добавляет, а
`trans *= 1 - absorb` не меняет `trans`. HD-ветка гасит `fade` уже к `k = 0.28`
(`1 - smoothstep(0.08, 0.28, k)`), поэтому у позднего шара марш (6–14 вызовов `fbm` на пиксель)
не виден, но выполнялся. Свечение (`heat = 1 - smoothstep(0.05, 0.55, k)`) живёт до `k = 0.55` и
вынесено из нового условия; второй `if heat > 0.0` убирает только заведомо нулевое слагаемое.
Шаги, разрешение, плотность, семплирование, свет и туннели не тронуты.
## Стенд
- Apple M5, Metal, 2560×1440 offscreen; engine pin `3428a571b`, база мода `c08b73729`, правка
`7d77c09f0` (только `effects.wgsl`).
- Мир `Polygon` — копия в `run-home/saves` рабочего дерева (оригинальные сохранения не трогались),
свежий `HORIZON_HOME` в `run-home-bench/home` на прогон.
- Сцена: spectator, `tp @s 40.5 76 40.5 135 <pitch>`, `time set 6000`,
`advance_time/advance_weather false`, `weather clear`, `doMobSpawning false`,
`randomTickSpeed 0`, `kill @e[type=!minecraft:player]`, HUD скрыт; `HORIZON_HD_TAA=0`,
`HORIZON_HD_WIND=0`, `HORIZON_HD_CLOUDS=0`, `HORIZON_HD_VOLFOG=0`, `HORIZON_HD_WATER=0`,
`HORIZON_HD_AO=0`. В кадре только небо и один/32 шара: никакого дрейфа LOD и сущностей.
- Все прогоны игры — под `flock -x /tmp/airdef-bench.lock` (один клиент за раз).
## Пиксельный паритет: A/B на одном замороженном кадре
Кросс-процессные прогоны расходятся (LOD/стриминг, партиклы, интерполяция настроек мода по
частичному тику), поэтому сравнение сделано **в одном процессе**: временная сборка мода (в коммит
не входит, дерево после неё чистое) содержала
- `testblast` — ставит шар(ы) в фиксированной мировой точке с `start 0, life 4000`, так что
состояние зависит только от абсолютного тика;
- выбор шейдера файлом `<HORIZON_HOME>/horizon-mods/.horizon-mod-data/airdef/harness-command`
(`old` — `effects.wgsl` из `7d77c09f0~1`, `new` — из `7d77c09f0`; обе версии вкомпилированы);
- настройки мода (`set-params`, `set-lights`, `set-smoke`) выталкиваются каждый кадр, иначе хост
интерполирует последние два тика по частичному тику и кадр «плывёт» даже на паузе.
Игра ставится на паузу без меню (F3+Esc) в нужном тике, затем на **этом же тике** снимаются кадры
`new → old → new` (переключение шейдера — запись файла). `p[1020] = 1` в харнессе убирает частичный
тик из часов эффектов.
Результаты (2560×1440, кадр целиком; `mean` — средняя разница по каналам из 255, методика
`tools/hd_bench.py`: `compare_runs`, движущиеся пиксели маскируются по размаху между `new` и `new2`):
| сцена | тик | k | путь | old-vs-new mean | >20/255 | шум того же шейдера (new-vs-new2) |
|---|---|---|---|---|---|---|
| 32 шара, небо | 623 | 0.156 | активный марш | 0.0054 | 0 | 0.0030 |
| 32 шара, небо | 1603 | 0.401 | fade = 0, марш пропущен | 0.0075 | 0 | 0.0069 |
| 1 шар 20 блоков, небо | 620 | 0.155 | активный марш | 0.0455 | 0 | 0.0597 |
| 1 шар 20 блоков, небо | 1608 | 0.402 | fade = 0, марш пропущен | 0.0436 | 0 | 0.0770 |
Покадрово: максимум расхождения **1/255** (32 шара) и **2/255** (один шар), пикселей с разницей
> 5/255 — **ноль**; разница old-vs-new не больше, чем у двух кадров одного и того же шейдера.
То есть правка невидима и в активном пути, и в пропущенном.
## Пиксельный паритет в штатной сцене hd_bench
`tools/hd_bench.py --only polygon_noon` (Polygon, полдень, статичное окружение
`HORIZON_HD_WIND/CLOUDS/VOLFOG=0`), старый мод против нового, под локом:
- old: GPU 18.06 мс; new: GPU 21.29 мс (бюджет 18 мс превышен в обоих — это шум/нагрузка стенда:
тот же кадр в этой сессии давал 18–31 мс);
- сравнение кадров new к базе old: средняя разница 0.79/255, пикселей >20/255 — 0.58% (порог 5%),
т.е. в пределах мерцания TAA между прогонами; в этой сцене нет взрывов, ветка правки не
выполняется.
## Время кадра (честно)
Парные `bench` на одном замороженном кадре, шейдеры чередуются каждую секунду (снимает дрейф
частот/тепла), сцена — небо, late-life шары невидимы:
| сцена | тик | new, медиана | old, медиана | old − new |
|---|---|---|---|---|
| 32 шара (каждый ~полэкрана) | 1606 | 79.27 мс | 79.63 мс | +0.37 мс (mean +1.15, σ 3.65, N=10) |
| 1 шар на 20 блоках | 1604 | 15.49 мс | 16.30 мс | +0.82 мс (mean +0.95, σ 3.79, N=16) |
Разброс между парами больше эффекта, знак нестабилен: на M5 выигрыш **ниже шума** измерения кадра.
Это ожидаемо — экономится один 7-шаговый `fbm`-марш по площади шара на пиксель, доли миллисекунды
на типичном кадре; замер требует изоляции прохода мода (в таймингах паков прохода мода нет).
## Что проверено
- `cargo test` в `airdef-mod`: 113 lib + 1 `core_boundary` + 2 `saturation` + 5 `scenarios` = 121,
0 падений.
- `python3 tools/test_hd_bench.py`: 5 тестов OK.
- Шаги/плотность/свет/туннели не менялись: см. diff `7d77c09f0` (только `effects.wgsl`).
@@ -0,0 +1,118 @@
{
"issue": 126,
"point": 4,
"base": "c08b73729",
"engine_pin": "3428a571b",
"change": "7d77c09f0",
"method": "same-process same-frozen-tick A/B (temporary harness build, reverted); pair benches interleaved",
"scene": {
"world": "Polygon (copy)",
"resolution": [
2560,
1440
],
"env": {
"HORIZON_HD_TAA": "0",
"HORIZON_HD_WIND": "0",
"HORIZON_HD_CLOUDS": "0",
"HORIZON_HD_VOLFOG": "0",
"HORIZON_HD_WATER": "0",
"HORIZON_HD_AO": "0"
},
"tick_clock": "p[1020]=1 (no partial tick), blast start 0 life 4000",
"parity_frames": {
"32_blasts": [
"/tmp/st4/new_623.png",
"/tmp/st4/old_623.png",
"/tmp/st4/new2_623.png",
"/tmp/st4/new_1603.png",
"/tmp/st4/old_1603.png",
"/tmp/st4/new2_1603.png"
],
"one_blast": [
"/tmp/st3/new_620.png",
"/tmp/st3/old_620.png",
"/tmp/st3/new2_620.png",
"/tmp/st3/new_1608.png",
"/tmp/st3/old_1608.png",
"/tmp/st3/new2_1608.png"
]
}
},
"pixel_parity": [
{
"scene": "32 blasts, sky",
"tick": 623,
"k": 0.156,
"path": "march runs (fade>0)",
"old_vs_new_mean_255": 0.0054,
"px_over_20": 0,
"same_shader_floor_mean_255": 0.003,
"max": 1
},
{
"scene": "32 blasts, sky",
"tick": 1603,
"k": 0.401,
"path": "march skipped (fade=0)",
"old_vs_new_mean_255": 0.0075,
"px_over_20": 0,
"same_shader_floor_mean_255": 0.0069,
"max": 1
},
{
"scene": "one blast at 20 blocks, sky",
"tick": 620,
"k": 0.155,
"path": "march runs (fade>0)",
"old_vs_new_mean_255": 0.0455,
"px_over_20": 0,
"same_shader_floor_mean_255": 0.0597,
"max": 2
},
{
"scene": "one blast at 20 blocks, sky",
"tick": 1608,
"k": 0.402,
"path": "march skipped (fade=0)",
"old_vs_new_mean_255": 0.0436,
"px_over_20": 0,
"same_shader_floor_mean_255": 0.077,
"max": 2
}
],
"frame_time": [
{
"scene": "32 blasts, late life",
"tick": 1606,
"new_median_ms": 79.274,
"old_median_ms": 79.628,
"old_minus_new_median_ms": 0.37,
"old_minus_new_mean_ms": 1.15,
"stdev_ms": 3.65,
"pairs": 10
},
{
"scene": "one blast at 20 blocks, late life",
"tick": 1604,
"new_median_ms": 15.493,
"old_median_ms": 16.302,
"old_minus_new_median_ms": 0.82,
"old_minus_new_mean_ms": 0.95,
"stdev_ms": 3.79,
"pairs": 16
}
],
"hd_bench_polygon_noon_static": {
"old_gpu_avg_ms": 18.06,
"new_gpu_avg_ms": 21.29,
"budget_ms": 18,
"vs_baseline_mean_255": 0.79,
"vs_baseline_pct_over_20": 0.58,
"note": "no blasts in the scene; the changed branch is not taken; budget exceeded in both runs (this session's same scene ranged 18-31 ms)"
},
"tests": {
"cargo test airdef-mod": "121 passed, 0 failed",
"tools/test_hd_bench.py": "5 passed"
}
}
@@ -0,0 +1,58 @@
{
"schema": 1,
"issue": 145,
"title": "Intercept regression under WASM saturation: 522 -> 302 (#133) -> 243 (#134)",
"scenario": "airdef-mod/tests/budgets/wasm_flat_budget.toml",
"checkpoint_tick": 2102,
"engine": "2bcce642362ab5d3f04de193e390d8293cd1bf30",
"fuel_budget_per_tick": 300000000,
"method": "One unchanged fixture, one WASM host (cargo-horizon-mod test --fuel-profile budget), one SDK; each slice built from its own commit against the pinned engine. The checkpoint stats line is read by a deliberate expect.feedback mismatch that prints the real line; fuel counters come from the host. Native replica: airdef-mod/tests/saturation.rs (same sim, host block tracer, deterministic).",
"ab_checkpoint": [
{"slice": "main release v0.4.0-rc1", "commit": "c525feb", "kills": 522, "hits": 1789, "missiles_airborne": 5},
{"slice": "parent of #133", "commit": "95739c95b", "kills": 522, "hits": 1789, "missiles_airborne": 5, "fuel_max_tick": 113866321},
{"slice": "#133 class/speed from measurements", "commit": "ac7521936", "kills": 302, "hits": 2024, "missiles_airborne": 8, "fuel_max_tick": 114068675},
{"slice": "#134 radar profiles", "commit": "858735a4c", "kills": 243, "hits": 2083, "missiles_airborne": 24, "fuel_max_tick": 135803282},
{"slice": "kimi-work HEAD", "commit": "a983177d3", "kills": 243, "hits": 2083, "missiles_airborne": 24, "fuel_max_tick": 136067073}
],
"decomposition_variants_wasm": [
{"variant": "#133 with class estimate forced Unknown", "base": "ac7521936", "kills": 249, "hits": 2092, "note": "confounded: Unknown also disables last-chance and halves the ballistic salvo; class/roles is not the #133 cause (native class-off 296 ~= baseline 294)"},
{"variant": "#134 cue restricted to separate radars (cue-off)", "base": "858735a4c", "kills": 325, "hits": 2011, "fuel_max_tick": 124349576, "note": "recovers the whole #134 drop: the embedded cue flood is the cause"},
{"variant": "#134 own_fire_within relaxed to own_within (no FIRE_QUALITY/product gate)", "base": "858735a4c", "kills": 243, "hits": 2083, "fuel_max_tick": 135800131, "note": "zero effect: embedded radars always produce Fire plots of quality >= 64"},
{"variant": "#134 channel limit never binds", "base": "858735a4c", "kills": 243, "hits": 2083, "fuel_max_tick": 135438135, "note": "zero effect: embedded profiles have channels = 0"},
{"variant": "cue precise + carry network velocity (Fix D)", "base": "a983177d3", "kills": 260, "hits": 2051, "note": "partial: early cue authority fires with a stale carried velocity"},
{"variant": "cue restricted to separate fire-quality radars (Fix F, chosen)", "base": "a983177d3", "kills": 325, "hits": 2011, "fuel_max_tick": 118325396, "note": "the fix; restores embedded acquisition to pre-#134 beam/revisit/lock"}
],
"native_replica_checkpoint": {
"note": "Deterministic native replica (tests/saturation.rs); chaotic combat answers render rays a tick later than the WASM host, so counters sit a few apart from WASM. Same drops, same fix.",
"pre133": {"kills": 605, "hits": 1706},
"s133": {"kills": 294, "hits": 2037},
"s134_head": {"kills": 247, "hits": 2079},
"class_off": {"kills": 296, "hits": 2045},
"cue_off": {"kills": 314, "hits": 2022},
"authority_relaxed": {"kills": 247, "hits": 2079},
"channels_off": {"kills": 247, "hits": 2079},
"fix_f": {"kills": 314, "hits": 2022}
},
"causes": {
"drop_133_522_to_302": "Track.vel became an estimate from noisy measured places (was the target's true velocity); the forecast, the aim lead and the interceptor's launch Fix all read it. Class-off ~= baseline, so class/roles is not the cause. The pre-#133 522 used the target's true velocity, which the #133 contract ('class and speed only from measurements') forbids; this portion is the intentional cost of honest measurement-only tracks.",
"drop_134_302_to_243": "#134 extended the network cue from the separate engagement radar to every fire-quality radar, including each weapon's embedded radar. Cueing every relayed contact each tick flooded the embedded fire control with one-tick plots whose noisy velocity degraded guidance. Restricting the cue back to separate radars recovers the drop (243 -> 325).",
"own_fire_FIRE_QUALITY_channels": "Not causes here: relaxing the own-fire gate or the channel limit each changed nothing (243 -> 243). Embedded radars always measure Fire plots of quality >= 64 and have no channel limit.",
"issue_140": "Does not affect this loadout, by fact: the fixture deploys 64 integrated complexes and no separate radar, so every profile is embedded with channels = 0; the channel-age bug binds only where a profile has channels. The channels-off A/B changed nothing."
},
"fix": {
"file": "airdef-mod/src/sim/sight.rs",
"change": "The network cue looks only through a separate fire-quality radar (sam.kind == SamKind::Radar), never the weapon's embedded radar; the embedded radar keeps its beam/revisit/lock acquisition as before #134.",
"preserved": "All radar profiles, channel limits, own-fire authority (own_fire_within / FIRE_QUALITY), and the measurement-only class/speed contract (#133). No target truth is injected.",
"tests": [
"airdef-mod/tests/saturation.rs (deterministic checkpoint replica + audit + #140 loadout fact)",
"airdef-mod/src/sim/sensor_tests.rs::a_network_plot_cues_a_separate_fire_radar_but_not_the_embedded_one",
"airdef-mod/src/sim/why.rs::Sim::launch_audit (on-demand tolerance diagnostic)"
]
},
"after_fix_wasm": {
"checkpoint_tick_2102": {"kills": 325, "hits": 2011, "airborne": 184, "missiles_airborne": 4, "fuel_max_tick": 118325396, "fuel_failures": 0},
"final_tick_3302": {"kills": 385, "hits": 2472, "airborne": 9, "missiles_airborne": 2, "fuel_max_tick": 176588234, "fuel_failures": 0},
"late_raid_chat": ["Разведка противника: впереди налёта высланы разведчики"]
},
"target_range": "Post-fix checkpoint ~325 intercepts (WASM) / 314 (native replica) at tick 2102, fuel max ~118M/300M. The residual gap to the pre-#133 522 is the measurement-only velocity contract cost (#133), kept deliberately: class and speed come from measurements, never the target's own figures."
}
@@ -0,0 +1,258 @@
# Issue #147, шаг 3.1: CPU-профиль боевого кадра — кто виноват (#126 D/E)
> Основа: engine `3428a571b` + instrumentation-коммит `d073783f5` (ветка
> `agent/126-cpu-profile`), AirDef `c08b73729` + `92c058f60`. Замер — только
> инструментация: правила симуляции, частоты, лимиты и точность не менялись.
> Worker НЕ реализован (это шаг 3.2, вне scope): задача — измерить и назвать
> виновника по данным, затем рекомендовать первого worker'а.
## Что инструментировано
### Хост: спаны `tick_mods` (engine, `HORIZON_MOD_CPU_PROFILE=1`)
`crates/horizon-client/src/game/mods.rs`: один record на игровой тик, в порядке
исполнения на потоке кадра:
| span | что меряется |
|---|---|
| `ground` | ответы `mod_ground(x,z)` → `answer_ground` (цикл ground-запросов) |
| `world` | `answer_mod_world()` — rays/sections + упаковка (`mod_world.rs`) |
| `snapshot` | `mod_snapshot()` + `set_snapshot` + resolver/acoustics setup |
| `wasm` | `mods.tick(self.ticks)` — wall-time всего WASM-тика (включая `Sim::step`) |
| `models` | `refresh_mod_trees` + `update_mod_models` (подготовка моделей) |
| `output` | `show_mod_output` |
| `total` | весь `tick_mods` (включая `sync_mod_sources`) |
Каждый record несёт `tick` (номер игрового тика) и `frame` — индекс кадра в
сырых массивах `FrameStats` (`frame_ms`/`cpu_ms`/`gpu_ms`), чтобы спаны
соединялись с trace кадров. Гейтинг как у fuel-профиля (выключено по умолчанию,
`OnceLock` по env); запись ограничена `1<<16` тиков (~54 мин). `stats` отдаёт
`mod_cpu` (перцентили по span'ам), `stats raw` — `mod_cpu_ticks` (сырые records);
`stats reset`/`bench` очищают. Overhead выключенного профиля — несколько чтений
часов на тик (как у существующего frame-timing).
### Гость: фазы `Sim::step` (мод, `sim::profile`)
`airdef-mod/src/sim/profile.rs` + `Sim::step`: named-фазы `plan` (plan_step/A*),
`adapt`, `drones` (step_drones), `moves` (step_moves), `sight` (update_sight/радар),
`sams` (step_sams/пуск), `record`, плюс весь `step` и `other` (step минус named).
Счётчики фиксированного размера, per-thread, не читают randomness и не меняют
решений → упорядоченный combat trace идентичен.
Симуляция остаётся SDK-независимой (она же собирается как `airdef-core`):
адаптер ставит хостовые часы `game.monotonic-nanos` (новый WIT-import, API level
32) в `init`; нативные тесты используют `std::time::Instant`. `/airdef stats`
выводит фазы как `PROFILE key=value` chat-строки (мс, totals и per-step maxima),
сброс при открытии нового мира.
### Harness-фиксы control-сокета (не симуляция)
Чтобы замерять бой на пути по умолчанию (server-thread), control-сокет должен
вести себя как чат-бокс игрока. Два минимальных фикса `game/control.rs` (правила
сима, частоты, лимиты и combat-решения не тронуты; in-frame путь не изменился):
- `chat`: в remote-режиме шёл напрямую `send_chat` на сервер, минуя перехват
клиент-мод-команд (`handle_chat_input` → `mod_command`). Теперь как в чат-боксе:
клиент-мод-команда перехватывается первой, иначе строка уходит на сервер.
Без этого `/airdef deploy|wave|stats` не доходили до клиентского мода в
server-thread (первый прогон: отпечатки null, fuel тика 395K против 12.7M
in-frame — бой не состоялся).
- `chat-log`: в remote-режиме читал сырой буфер соединения `remote_chat`, где нет
строк клиентского мода (они идут в `ui.chat` через `add_mod_chat_line`; серверные
строки зеркалируются в `ui.chat` через `chat_line`). Теперь читает `ui.chat` —
чат, который видит игрок, включая feedback мода. `status.chat` (`remote_chat`)
не тронут.
### Драйвер: `tools/raid_bench.py`
- `--scheduler in-frame|server-thread` — два пути single-player, замеряются
РАЗДЕЛЬНО (требование issue). `in-frame`: окно само тикает мир;
`server-thread` (путь по умолчанию): интегрированный сервер на своём потоке,
окно — клиент (`tick_remote` → `tick_mods` синхронно перед prep кадра).
- `HORIZON_MOD_CPU_PROFILE=1` в env прогона.
- `mod_cpu_ticks` соединяются с trace кадров (`mod_cpu_frames`): per-frame total
мод-пути, его p50/p95/p99/max, счётчики кадров >25/33 мс, и что несут худшие 1%
CPU-кадров (avg mod total/wasm/world/models, сколько из них с мод-тиком) —
совпадают ли пики мод-пути с пиками кадров.
- Мод-фазы читаются на idle_warm и после боя; `mod_phases_battle_delta` =
cumulative-после-боя минус cumulative-idle (изолирует бой).
## Стенд и методика
- Apple M5 (10 ядер), macOS, Metal 4. 5600X/RTX 3060 — pending (как #126/#147).
- 2560×1440 offscreen (окно 1280×720 @2x), HD (`/airdef shader hd`),
`HORIZON_HD_SCALE=1`, `HORIZON_NO_AUDIO=1`, `HORIZON_SPIKES=0`,
`HORIZON_MOD_FUEL_PROFILE=1`, `HORIZON_MOD_CPU_PROFILE=1`.
- Мир `Polygon` (копия `run-home/saves/Polygon`), свежий `HORIZON_HOME` на прогон.
Камера `tp @s 40 76 40 135 25`, `time set 6000`, время/погода заморожены,
`weather clear`, creative, HUD скрыт — сцена #126/#147.
- Бой по фиксированным тикам (`BATTLE_SCHEDULE`: 14 батарей, волны shahed 40/160,
kh101 16/180, mix 24/140 — перекрывающиеся налёты + взрывы + плотный дым),
окно замера battle 10 с в середине боя (в потоке). Отпечаток — `airdef stats`
на тиках 400/800/1200/1400.
- Fuel — отдельный сигнал (не включает хост/GPU работу): `mod_fuel` по callback.
- **Сериализация замера**: каждый запуск клиента обёрнут в эксклюзивный
`flock -x` на общем `/tmp/airdef-bench.lock` (другой агент использует тот же
lock): `( flock -x 200; python3 tools/raid_bench.py … ) 200>/tmp/airdef-bench.lock`.
Только один клиент в системе за раз; перед стартом внутри lock ожидается
очистка `pgrep 'horizon-client --world'`. Ранние прогоны, шедшие конкурентно с
клиентом другого агента, признаны невалидными и отброшены; ниже — чистые
замеры под lock. `flock` доставлен через `brew install flock` (0.4.0).
```sh
python3 tools/raid_bench.py --scheduler server-thread --label m5-server --out run-home-bench/out/147-cpu-server
python3 tools/raid_bench.py --scheduler in-frame --label m5-inframe --out run-home-bench/out/147-cpu-inframe
```
## Результаты (M5/Metal, 2560×1440 HD, чистые замеры под flock)
Два раздельных прогона, каждый под эксклюзивным lock: `report-server.json`
(server-thread, путь по умолчанию) и `report-inframe.json` (`--in-frame`,
контроль). Бои реальные: server fp400 — 14 ПВО, 40 сбитых; in-frame fp400 —
14 ПВО, 37 дронов в воздухе, 20 сбитых. **Бои двух планировщиков расходятся по
таймингу событий** (стриминг/акустика; методика #147) — отпечатки разные,
поэтому totals фаз между ними не сравнимы как «один бой»; сравним вклад
мод-пути в пики кадров каждого планировщика.
### Боевой кадр: frame / CPU / GPU (окно battle 10 с)
| метрика, мс | server-thread | in-frame |
|---|---|---|
| кадров в окне | 128 | 103 |
| frame avg / p50 | 78.9 / 73.3 | 97.7 / 70.5 |
| frame p95 / p99 / max | 88.4 / 94.9 / 880.4 | 171.9 / 182.6 / 742.8 |
| **CPU** avg / p50 | 36.4 / 29.5 | 94.3 / 71.4 |
| **CPU p95 / p99** / max | **38.8 / 46.7** / 872.3 | **167.9 / 175.4** / 734.9 |
| **GPU** avg / p95 / p99 | 73.7 / 89.1 / 92.5 | 53.2 / 69.5 / 78.6 |
| кадров >25 мс | 128/128 | 103/103 |
| кадров >33 мс | 127/128 | 103/103 |
| фазы avg: render / tick / update / prepare | 27.0 / 5.95 / 0.3 / 3.1 | 38.2 / 37.4 / 11.6 / 7.1 |
| худший 1% CPU-кадр: render / tick | 449 / 6.8 | 351 / 79.6 |
- **server-thread: кадр GPU-bound.** GPU avg 73.7 мс ≈ frame p95 88 мс; CPU p99
всего 46.7 мс. Почти все кадры >33 мс из-за HD освещения/дыма на 1440p (~74–90 мс
GPU), не из-за CPU мода.
- **in-frame: кадр CPU-bound.** CPU avg 94.3 ≈ frame avg 97.7; GPU avg 53.2 меньше.
Tick-фаза 37.4 мс avg — это Minecraft-сим (мобы/блоки) на потоке кадра + мод;
render-encode 38.2 мс, update 11.6 мс.
- Одиночный catch-up спайк в обоих (server 872 / in-frame 735 мс) —
**render-доминированный** (render-фаза 449 / 351 мс), не мод.
### Мод-путь: спаны `tick_mods` на тик (окно battle, engine `mod_cpu`)
| span, мс | server avg / p95 / p99 / max | in-frame avg / p95 / p99 / max |
|---|---|---|
| ground (ответы земли) | 0.032 / 0.122 / 0.257 / 0.285 | 0.116 / 0.268 / 2.001 / 3.123 |
| world (rays/sections+упаковка) | 0.028 / 0.087 / 0.127 / 0.134 | 0.929 / 4.036 / 6.302 / 6.714 |
| snapshot | 0.031 / 0.042 / 0.052 / 0.072 | 0.114 / 0.107 / 4.070 / 4.222 |
| **wasm (весь WASM-тик)** | 2.322 / 3.200 / 3.491 / 3.630 | 7.930 / 16.869 / 21.422 / 30.226 |
| models (подготовка моделей) | 0.055 / 0.078 / 0.089 / 0.108 | 0.120 / 0.145 / 1.946 / 3.285 |
| output | 0.050 / 0.105 / 0.140 / 0.145 | 0.118 / 0.165 / 2.820 / 3.200 |
| **total мод-путь** | 2.537 / 3.484 / 3.802 / 4.096 | 9.378 / 19.686 / 25.480 / 34.463 |
| тиков в окне | 194 | 156 |
Host world answers (ground+world) и model prep — **ничтожны** на пути по
умолчанию (<0.1 мс/тик); in-frame world заметнее (avg 0.93, p99 6.3 мс), но всё
равно мал против wasm. Мод-путь почти целиком — wasm (`Sim::step` + презентация).
### Совпадение пиков мод-пути с пиками кадров (`mod_cpu_frames`)
| метрика | server-thread | in-frame |
|---|---|---|
| мод-total на кадр p50 / p95 / p99 / max, мс | 3.29 / 6.40 / 7.68 / 14.9 | 10.0 / 33.96 / 38.56 / 38.6 |
| кадров с мод-путём >25 мс | **0** | **27** |
| кадров с мод-путём >33 мс | **0** | **7** |
| худший CPU-кадр: cpu / мод-total / wasm / world, мс | 872 / 2.15 / 2.0 / 0.003 | 735 / 34.5 / 30.2 / 4.0 |
- **server-thread: мод-путь НИКОГДА не превышает 25 мс на кадр** (p99 7.7 мс).
Пик CPU-кадра (872 мс) несёт лишь 2.15 мс мода — спайк не модовый.
- **in-frame: мод-путь >25 мс в 27 кадрах, >33 мс в 7.** Мод — реальный вклад в
CPU-пики, но пик кадра (735 мс) всё равно render-доминированный (мод 34.5 мс).
- **Пики мод-пути двух планировщиков НЕ совпадают**: на пути по умолчанию мод
не создаёт пиков вовсе; in-frame создаёт (бой плотнее + поток кадра уже загружен
симом, wall-time растягивается). Совпадает только природа одиночного
catch-up спайка (render/GPU hitch) и всеобщность >33 мс кадров (HD на 1440p).
### `Sim::step` изнутри: фазы (мод `PROFILE`, delta за весь бой)
Totals за бой (idle→конец), мс; max — худший тик боя. Бои расходятся, поэтому
доли — характеристика каждого планировщика, не сравнение одного боя.
| фаза | server total / max / доля | in-frame total / max / доля |
|---|---|---|
| **drones (step_drones)** | 308.9 / 1.71 / 30% | **1418.8 / 47.05 / 52%** |
| **plan (plan_step, A*)** | **346.5 / 1.40 / 34%** | 397.7 / 31.83 / 15% |
| sight (update_sight, радар) | 173.3 / 1.00 / 17% | 412.0 / 26.81 / 15% |
| other (нетименованное) | 87.3 / 0.53 / 9% | 196.3 / 4.50 / 7% |
| record | 46.5 / 0.22 / 5% | 156.7 / 10.49 / 6% |
| sams (пуск) | 50.0 / 0.26 / 5% | 120.1 / 5.52 / 4% |
| moves | 3.0 / 0.02 / <1% | 12.1 / 3.67 / <1% |
| adapt | 1.4 / 0.06 / <1% | 2.4 / 0.10 / <1% |
| **step всего** | 1016.8 / 2.52 (1250 тиков) | 2716.1 / 47.18 (2091 тик) |
- **server-thread: A* plan_step — крупнейшая фаза** (34%), но весь `Sim::step`
~0.81 мс/тик (max 2.52) — мод мал.
- **in-frame: step_drones доминирует** (52%, max 47 мс/тик — плотный налёт),
A* лишь третий (15%). Host world answers и model prep не лидируют нигде.
### Fuel (отдельный сигнал, без хост/GPU работы)
`airdef:tick` max_used: server 11.15M, in-frame 20.69M при бюджете 300M,
failures 0. Fuel подтверждает: in-frame бой тяжелее по гостевой работе (больше
дронов/тиков), но это не хостовые world answers и не GPU.
## Виновник и рекомендация первого worker'а (шаг 3.2)
**Виновник пиков боевого кадра на пути по умолчанию (server-thread) — GPU.**
GPU avg 73.7 мс ≈ frame p95 88 мс; 127/128 кадров >33 мс из-за HD
освещения/дыма на 1440p. CPU мода — ~2.5 мс/тик, на кадр p99 7.7 мс, **0 кадров
>25 мс**; host world answers <0.1 мс, model prep ~0.05 мс. Одиночный CPU-спайк
(872 мс) — render/GPU hitch (449 мс render-фаза), мод в нём 2.15 мс.
**Рекомендация по данным (worker НЕ реализован):**
1. **Путь по умолчанию (server-thread): CPU-worker не поможет пикам кадров.**
Мод-путь уже ничтожен и вынесен с симом на серверный поток; пики — GPU.
Применяются **шаги 1–2 таблицы #147 (GPU/геометрия)**: HD дым/освещение,
instancing остальных групп моделей. Route-worker / world-worker здесь не
оправданы данными.
2. **Чистый A* route-worker НЕ оправдан.** A* лидирует лишь в крошечном моде
server-thread (34% от 2.5 мс/тик, на пики кадров не влияет); in-frame A* —
только 15% `Sim::step` (третий после step_drones 52% и sight 15%). Снятие A*
не адресует ни GPU-пики дефолта, ни крупнейшую фазу in-frame.
3. **Batch read-only chunk-snapshot world-worker НЕ оправдан.** Host world
answers не лидируют нигде: <0.1 мс/тик дефолт, avg 0.93 / p99 6.3 мс in-frame
— мало против wasm и GPU.
4. **Если целиться в CPU in-frame-пути — единица offload'а весь `Sim::step`
(Wasmtime на своём потоке), а не A*.** In-frame кадр CPU-bound, мод-путь
>25 мс в 27 кадрах, доминирует step_drones (52%, max 47 мс/тик), тесно
связанный с мутабельным состоянием сима и host world answers — это аргумент
за whole-sim offload (следующий шаг таблицы), **но не за pure route-worker**.
При этом и in-frame пики кадров (p99 175 мс) шире мод-пути (38 мс): Minecraft
сим + render-encode тоже велики, а худший спайк — render. Реалистичное
ожидание от whole-sim worker'а — снятие мод-вклада (~38 мс p99), не устранение
>33 мс кадров (их держит GPU/сим/encode).
**Итог:** данные не поддерживают ни pure A* route-worker, ни world-snapshot
worker как первый шаг. На дефолтном пути виновник — GPU (шаги 1–2); на
in-frame контроле CPU-вклад мода реален, но доминирует step_drones, и
оправданный (если делать) следующий шаг — Wasmtime на отдельном потоке целиком,
не route-worker. Реализация worker'а — вне scope 3.1, не делалась.
## Тесты
- `airdef-core` cargo test: 326 passed, 0 failed (8 ignored); timing-тест
`a_smart_raid_plans_and_flies_in_time` (<200 мс/тик) падает только под
параллельной компиляцией (491 мс тик при загрузке CPU), в изоляции — ok.
- `airdef-mod` cargo test: 113+1+2+5 passed, 0 failed, включая
`same_seed_same_result` и `adapter_reexports_core_and_combat_trace_is_deterministic`.
- `tools/test_raid_bench.py`: 11 passed (7 существующих + 4 новых helper'а).
- `horizon-mods` cargo test: 26 lib + sandbox/api_reference ok (exit 0);
api_reference/api_level: ok; WIT-import аддитивен (старые моды линкуются).
- wasm ABI-тест мода `python3 tools/airdef.py test-wasm`: `wasm_contract.toml`
ok (30 шагов, реальный хост, fuel-лимиты) — `game.monotonic-nanos` работает
end-to-end, failures 0.
- Harness-фикс `chat`/`chat-log` (control.rs) — только control-сокет; sim-тесты
его не касаются (нативные тесты не используют бинарник игры). Determinism
(`same_seed_same_result`, `combat_trace_is_deterministic`) перепроверен после
фикса — ok. Инструментация observation-only: combat trace идентичен.

Some files were not shown because too many files have changed in this diff Show More