Compare commits

..

54 Commits

Author SHA1 Message Date
Codex 9370fd4ed4 Check fixed radar profiles at the WASM boundary
build / mod (push) Failing after 49s
Refs #144

Co-Authored-By: Codex <codex@openai.com>
2026-11-21 05:31:07 +00:00
chexit a983177d34 Draw a held-key world overlay of targets through the drawn camera (#132)
build / mod (push) Failing after 59s
Holding C draws square markers over the targets the player can see, each
with the class the radars estimated and the distance; an unidentified
track stays a "?", never the target's type. Stale forecast tracks fade
orange and say their age, the player's own interceptors wear small yellow
squares, and the sandbox truth mode adds white markers of the real drones
apart from the network's estimates. Letting the key go clears the HUD.

The markers project through the camera of the last drawn frame
(render.project, API 31), so they sit on the world as it is drawn and
follow the view frame by frame; the overlay stays off under a replay, the
grid J, the monitor K and the map M, which own the screen themselves. A
full raid stays inside the HUD's 1024-shape budget, keeping the nearest
markers and counting the rest behind the camera or past the edges.

Bump the engine pin to 2bcce6423 (API 31, render.project) and name API 31
in the capabilities diagnostic to match.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 00:39:17 +03:00
chexit 795b1b2fcf Merge recon flights and partial reports into the classified radar picture (#135)
build / mod (push) Failing after 1m5s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>

# Conflicts:
#	airdef-mod/src/sim/mod.rs
2026-11-21 00:07:39 +03:00
chexit c4e002ed8b Add the recon UI and diagnostic layer to the smart enemy (#135)
The core recon flights and partial reports (9d8f3da57) had no player-facing
or diagnostic consumer: enemy_picture().recon/recon_sorties were read only by
core tests. This adds the missing layer on top, without touching the mechanics,
models or textures.

- Map: a tracked recon aircraft is a recognisable yellow hollow diamond with a
  "разведчик" label, a role line in the selection panel and a filter legend; in
  the sandbox truth mode it gets an amber marker of its own.
- Battle UI: the summary panel and the map show the flight's coarse phase
  (разведка → донесение → завершение) only while the player's network actually
  holds a recon aircraft — what the visible aircraft are doing, not what the
  enemy learned. The truth mode adds a recon count line.
- Diagnostics and after-action review: /airdef recon and the menu page
  "Разведка противника (разбор)" (from Main and Replays) list the enemy's marks
  best-first with the reason each outranks the rest — priority = freshness×4 +
  quality×3 + observed role (recon::priority_parts, cross-checked against
  Mark::priority by a test) — plus the sortie phases and the drones aimed at a
  mark. The omniscient enemy picture is never shown in the normal HUD; it is
  explicit debug/review only.

recon_view reads only the current report types (EnemyPictureReport, ReconReport,
ReconSortieReport); the sim side only widens visibility and adds priority_parts
and the is_recon_drone/recon_status read helpers. Tests: recon_view, panel,
command tree, priority_parts cross-check. README and IMPLEMENTATION-STATUS updated.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:59:45 +03:00
chexit 12a706fb67 Refine the network track's class from the optical look (#136)
build / mod (push) Failing after 1m25s
- ClassEst::step_optical: the shared estimate's rule for one passive look —
  an unsure look (over OPTICAL_CLASS_MAX_UNCERTAINTY) names nothing, a sure
  one names a class, firms an agreeing probable, replaces a contrary guess
- Track::refine_class_optical: the minimal common method — class only; the
  plot, age, source, quality and own fire rights stay untouched
- Sim::apply_optical_classes: the explicit adapter, fed by each observation
  made this tick through OpticalObservation::estimate; a relay of the
  refined track carries the class as it was and gains nothing from it
- the post still holds no track, emits nothing and authorizes no shot;
  the refined class reaches the existing #133 track UI through the picture
- tests: network refinement, unsure look, relay/stale look add no
  confidence, equal observables refine equal classes, the step rules

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:55:28 +03:00
chexit 8550de16f8 Finish the optical post's network cue and edge cases (#136)
- a radar's fresh track reaches a post as a cue only: it points the head
  but never enters the post's tracks, seen or own set
- a searching post's sector follows the turning head, not the fixed base
  heading; switching contacts drops the old contact's picture
- dead and blinded posts spend no probe budget and never observe
- the icon alias is part of the generator, so the placeholder item uses
  the radar texture without a duplicate PNG or a hand-written asset
- part diagnostics read "Опт" for a passive post's sensor
- tests: cue wiring, turning sector, contact switch, dead post, graphics
  preset; generator alias

Cherry-picked from 3697a1764aec7a7bdc6311918453dd51e26ecabf onto the
#132/#133/#134 base: the cue-wiring test's track literal now carries the
shared class/source/product/quality contract instead of a DroneKind.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:38:32 +03:00
chexit 245aceb434 Add recon flights and partial reports to the smart enemy (#135)
A smart raid may send a small, bounded flight of unarmed Gerbera aircraft
ahead of its strike. They fly physically through zones round the marked
objectives (and revisit a doubtful mark when nothing is unchecked), look
at units inside a zone, and radio home an area, a public category, the
channel, age and quality only after a delay and only while the aircraft
is alive. A sortie lost before its report sends nothing; marks already
delivered stay, and the picture remembers them across raids.

The planner now reads recon marks as well as disclosure contacts. A mark
carries a synthetic id, an area, a category and a radar role only once a
second independent look refines it -- never a real id, SamKind, exact
point, health, magazine or link. Aims are chosen by observed role,
freshness and quality; a fresh modest mark can outrank a stale doubtful
big one, and a hidden unit is in neither list. In-flight recon aims keep
their old area: hidden moves, re-roles and damage do not rewrite a mark.

Bounded assignments, the route-job queue, the original wave objectives
and the no-eternal-pause rule are preserved. Recon aircraft take ids from
their own range, do not spend the strike's combat RNG and are not part of
the strike's replay. Save/load keeps marks, sorties, pending reports and
checked zones. No new models, textures or weapons.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:36:00 +03:00
chexit e5ee15a2ca Add passive optical observation post (#136)
- new Optical unit kind with its own catalog row and deploy item
- bounded one-contact line-of-sight checks against land and blocks
- day/night reach and hold timing; obstacle and unknown geometry block sight
- independent class observation with source, time and uncertainty, never DroneKind
- map/monitor/panel statuses and a line to the selected contact
- tests: day/night, wall/unknown, ageing, no kind leak, bounded work, passivity

Cherry-picked from 3ae21123964a9d3234bb2b3efc9ff926d64fc77d onto the
#132/#133/#134 base: the cue test's track literal now carries the shared
class/source/product/quality contract instead of a DroneKind.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:33:32 +03:00
chexit 53fbeced22 Cover radar profiles over a ridge (#134)
build / mod (push) Failing after 28s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:13:38 +03:00
chexit e1b09f696f Give the two-raid scenario room for the last contact (#134)
The maximum menu raid keeps a supersonic contact in the air past 5000 ticks under the new fire-authority rules; the recording closes only when the sky is clear. Run the scenario to 8000 ticks, still well inside its 20-minute cap, and keep the replay assertion.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:13:32 +03:00
chexit 858735a4c6 Implement the first full radar-profile slice (#134)
Give the separate radar three real profiles over SamKind::Radar and the
typed catalog variants:

- radar_search: coarse, slow, long-range search plots; no fire authority.
- radar_height: raised mast, local refinement of low plots; no fire authority.
- radar_track: local search, fast revisit, two refined/fire channels.
- radar_multi remains the compatible universal profile, not best everywhere.

Tracks now carry the measuring station, product (search/refine/fire), and
quality (separate from identification), and keep the station's own plot when a
fresher network relay replaces the published position. A relay never refreshes
the measurement or authorizes a launch. Ordinary launches need the battery's
own confirmed fire plot; launcher-only batteries use a supporting radar's own
plot, and the existing heavy far shot keeps its cue-radar exception.

Per-tick refinement/fire work is bounded by profile channels and local search
radius. Off, damage, network and save/replay behavior are preserved: new saves
write the stable profile ID, old role-only lines migrate, and embedded SAM
radars keep their own fire authority. The deploy menu, status lines, map,
monitor, radar scope and /airdef why explain the profile, source, age, quality,
channels and refusal reason.

Models/textures are untouched: all profiles reuse the existing radar
silhouette (the separate art zone remains for its owner).

Tests: profile single/pair/full scenarios and duplicate station, channels,
relay source/age/quality, Off/damage, save migration, replay, embedded and
Multifunction radars, catalog/generator checks, airdef-mod suites, core lib
(non-balance on one thread; the four active balance tests in release) and core
scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:11:12 +03:00
chexit ac7521936d Estimate a track's class from its measurements, not from the target (#133)
build / mod (push) Failing after 1m18s
A radar track is what the network measured, and it never carried the
target's own answers: the tactical Track loses `kind: DroneKind` and the
true velocity, and gains what the measurements say instead.

- Track now holds a ClassEst (unknown / probable / firm) plus an observed
  velocity: none from the first blip, then the change of the measured
  places between real measurements, smoothed so one noisy pair does not
  flap the class. The classifier's bands sit between the game's speed
  clusters (Class::of_speed); a new contrary measurement replaces the
  hypothesis, an agreeing one firms it.
- The class estimate is separate from track confirmation (Track::ident):
  a track can be confirmed with its type still unknown. The estimate
  grows only on real measurements — a forecast and a relayed copy add
  nothing — and it travels with the measurement it grew from, ageing
  with the track and gone when the track drops.
- Roles, last chance, the reserve and the interceptor count read the
  estimate, never the target's class. Explicit policy for the unknown:
  an unidentified track stays a candidate under the general rules (and
  the system with no roles holds its fire at everything); the map, the
  monitor, the summary panel and /airdef why read the same estimate and
  name the reason — «Трек подтверждён · тип не определён», «вероятно
  крылатая ракета». The exact model stays in the sandbox's truth mode.
- A gun or a launcher lets go of a target that classified out of the
  roles since it was taken; a first blip no longer rules a contact out
  as a threat to guarded objects (it has no measured course yet).

Old saves and replays are untouched (tracks are derived, not persisted);
the simulation stays deterministic (the classifier is pure arithmetic on
the measurement noise). The doctrine/first-blip/last-chance tests gained
classified tracks where the contract provably changed; new tests cover
the classifier's steps, kind-independent estimates, first-blip blindness,
and relays and forecasts adding no confidence.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 22:55:36 +03:00
chexit 95739c95b1 Finish radar truth HUD layout and document target modes (#132)
build / mod (push) Failing after 33s
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 22:08:46 +03:00
chexit d302204649 Make map and radar targets legible with an honest hover (#132)
- mini radar: class-shaped blips that merge into one with a count
- map: larger track markers and trails, hover card with distance, type,
  status, target and interception
- explicit network vs sandbox truth: true drones, routes and aims drawn
  apart from the network tracks, with their own trails

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-20 22:08:46 +03:00
chexit 1e2d5dd0c0 Record #126 first stage: retained mod-model meshes, measured
build / mod (push) Failing after 55s
Engine a861c1ed2 (kimi-work-124), based on ed751714e: mod-model faces resolved once per pack generation, frames only transform and light them; motion #124 from the same faces; counters and span; reload/unload invalidate the cache. HD-RENDERER status + section, and docs/measurements/issue-126-first-stage with the A/B method and numbers (M5/Metal, Polygon raid: entity_geometry CPU 5.71 -> 1.57 ms avg, prepare 23.5 -> 7.05 ms; static scene pixel-identical; reload/unload smoke). Not GPU instancing; 5600X/3060 acceptance pending. Issue #126 stays open.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:46:46 +03:00
chexit 80d0cc9c43 Add native wgpu ray-query capability probe (#125)
build / mod (push) Failing after 1m21s
Stage 1 of #125: prove or disprove real hardware ray-tracing support without
touching the client renderer. The probe pins the same wgpu 30.0.1 stack as the
engine, including its vendored third_party/wgpu-hal patch, builds one BLAS/TLAS
and traces a 16x16 ray-query compute frame, checking every ray against a CPU
point-in-triangle expectation.

Verified on macOS aarch64, Apple M5 / Metal: BLAS/TLAS and the ray-query
pipeline build, 32 hits and 224 misses all match, exit 0. RT_PROBE_BACKEND=gl
reports no RT adapter and exits 2; RT_PROBE_NO_OPTIN=1 shows request_device
rejects EXPERIMENTAL_RAY_QUERY without the experimental opt-in and exits 2.

tools/rt-probe/target/ is ignored; the probe is a standalone workspace and is
not wired into the game build.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit c59bfe9e54 Catalog typed battery variants (#91)
The battery deploy pieces (s400_launcher, s500_launcher, radar_search/
track/height) were described three times: the menu table and the
configuration match in lib.rs, and a chained id list in commands.rs. One
catalog decision instead: catalog/content.json gains a variants section
(mode/role reuse the existing SamMode/RadarRole save keys), gen_catalog.py
generates catalog::UnitVariant rows, and the loader rejects duplicates,
unknown kinds/modes and id collisions with kinds or items. The battery
menu, its click handler and the deploy completion read the generated
table; the historical row order and labels are unchanged.

No variant carries its own balance: per-variant ammo profiles stay open
pending a confirmed profile and an explicitly labelled game abstraction
(PAC-3 note on #91), so no new specs, no new matches and no save/replay
change - a variant is only a deploy key over the same kind.

Checks: gen_catalog.py --check and gen_models.py --check clean, the
python catalog/asset and sound tests pass, airdef-core 234 unit + 8
scenarios, airdef-mod 69 unit + 1 boundary + 5 scenarios (save/load and
state round trips included), zero failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit 306af49744 Move battery status text to the presentation adapter
Sam::status, Comps::describe/worst and Sam::parts_text formatted
player-facing Russian in the simulation. The adapter now owns that
text: battery_view::sam_status for the panel and map, why_view::parts
and why_view::worst for the monitor and the status line. The core keeps
the data and gains only the accessors the adapter needs
(preparing_cell, public cells/reload_time/magazine/gun facts).

Texts are unchanged; the adapter tests pin the existing strings.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 21:34:07 +03:00
chexit 60f1bf0fd8 Record the Windows DLSS acceptance build and remaining runtime check
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 13:00:39 +03:00
chexit e194971867 Document Visual C++ runtime needed by the DLSS test build
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 12:56:32 +03:00
chexit 7ae0c5bbba Add Windows DLSS A/B test launchers and acceptance guide (#124)
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-16 12:55:10 +03:00
chexit 217e3ac886 Add feature-gated DLSS SR proof of concept (#124)
Advance to engine ed751714e. Document the optional SDK build, ordered color conversion/submission, native fallback and the remaining MSVC-link and RTX-runtime acceptance.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 22:10:32 +03:00
chexit f33b799551 Record previous-frame motion for mod models (#124)
Advance to engine 7a73e8d26: separate previous-position streams and a depth-read-only motion pass for mod models, with matching alpha cutouts and a debug view.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 21:06:02 +03:00
chexit d8cb98a964 Keep radar target blips above the player arrow
Draw the player marker before network tracks so a close blip is not hidden. Add a shape-order regression and verify a live raid with truth disabled.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 18:25:33 +03:00
chexit e59c49e3bf Blend HD shadow cascade filters at the near boundary
Advance to engine 17382445a and document the six-block near/far transition verified on the forest aerial view.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 18:04:24 +03:00
chexit 9664783b17 Add dense motion foundation for temporal upscaling (#124)
Advance to engine c962cd472. Document the render-pixel current-to-previous contract, native TAA/TAAU consumer and the remaining DLSS/object-motion/linear-HDR work.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:49:23 +03:00
chexit 3db1b73d64 Reuse oversized renderer staging buffers (#130)
Advance the engine to 94b572cd2, backporting upstream f7b77fbc8 with its GPU growth/readback regression. Keep API30 unchanged.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:27:17 +03:00
chexit 367c7f4ac3 Bound recorded SAM poses under the WASM memory cap (#122)
Thin old SAM keyframes in place, reduce allocation capacity and adapt later sampling when a recording exceeds its fixed pose budget. Preserve recent poses and cover the full ten-minute window in native and real WASM stress tests.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-14 17:21:48 +03:00
chexit e7934a1ebb Give the enemy a structured intent and a durable route queue (#127)
build / mod (push) Failing after 22s
release / windows (push) Failing after 2s
Stage 2 of #127. A smart drone now carries why it is aimed where it is
(Intent: plan, sead, react, replace) apart from the aim bookkeeping
(unit, since, switches, confidence). Assignments are throttled per
adaptive tick and per contact, a fresh disclosure replaces an aim only
after a hold, within a switch cap and when the change is worth a new
route, and a killed aim is replaced as a separate, lower-priority
decision. The queue is bounded and taken by priority (plan > sead >
react > replace); unknown land is no longer free in a replanned route.

The autosave now carries the air state: the drones in flight, the launch
queue, every pending job with its id, aim, unit, version, priority,
intent and relief version, the contacts the jobs were chosen from and
the relief snapshots they plan over. The format is a versioned `air 1`
section; older saves read as before, scenarios do not carry the sky,
stale, ghost and duplicate jobs are cancelled on load, and the section is
bounded (512 drones, 512 route points, 4096 contacts, 8 reliefs, 900 KB).
A periodic save waits while a raid is only being planned.

enemy_picture() now explains targets and pending jobs (aims, aimed_by,
pending_jobs, reason, work_per_tick) in English, and intel_bench records
the queue and intent evidence next to completion, losses and failures.
2026-11-06 18:36:20 +03:00
chexit 8fc10c07a1 Give the enemy a last-observation picture and observed-capability pricing (#127) 2026-11-06 18:00:08 +03:00
chexit 0b645d77e9 Normalize #129 measurements and pair the cold-launch capture
build / mod (push) Failing after 22s
Write both measurement CSVs with LF instead of CRLF so the range no longer
fails `git diff --check` on trailing whitespace; the parsed data is unchanged.

Add a matched before/after capture: one copied world, scenario and seed, the
same client/director and the same export command. The baseline hmod is built
from dc36d67 and the final one from the #129 code. Both launch shots start at
frame 94; the first centre illumination is frame 101 (0.233 s) before and
frame 121 (0.900 s) after, against the 0.25/1.00 s cold rules. Raw probe,
hashes and the measurement method are in issue-129-pair.json. The two MP4s
in docs are CRF26 storage copies; the CRF16 originals stay in the scratch
homes.

These are replay exports, not live footage. The capturing agent still has no
image input, so composition is left for human review; the frames before the
launch are not pixel-identical because these are two live sessions.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit 56093b3a55 Record the #129 balance and the cold-launch capture
The stage contract and profiles are in 4b013fb. This commit adds the
measured balance (the #120 grid on identical seeds and the 12-seed raid),
the replay/export video with four stills, and updates the user and handoff
documentation. The visual files are provided for human review; the agent
that captured them has no image input and checked only the encoded
parameters, shot boundaries and the first large plume.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit 1261c30724 Stage the cold launch and spool every interceptor's motor (#129)
The interceptor's launch is one sequence: the cap opens, the round is
thrown out unlit and slows under linear gas drag (`cold` ticks), the motor
lights where it has reached, it turns with a growing rate while thrust
spools up (`boost` ticks), and full guidance starts only at `cold + boost`.
A rail launch lights at once but spools over the same `boost` ticks; the
electric P1-SUN has no rocket spool or plume.

S-400/500 now hold the unlit ejection for 20/24 ticks (1.00/1.20 s at
20 Hz); IRIS-T/Tor keep shorter 8-tick throws. Ignition, its sound, flame
and recorded MotorIgnition event all use the missile's current position.
The RM48U strike follows the same 20-tick choreography, counts the throw
in its flight time and starts its recorded smoke at ignition.

Maximum speed, turn, accel, pk and every collision rule are unchanged.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00
chexit a592ece6e3 fixup! Keep unfinished retarget routes in a bounded job queue (#127)
build / mod (push) Failing after 22s
The planner caches were keyed by (kind, relief Arc pointer, start, aim): two jobs with the same relief but different known-units snapshots could reuse each other's price grid and route. Key relief sampling by its Arc pointer but key prices and routes by the whole knowledge version: adaptive tick plus the known-units and relief Arc pointers. Regression creates two same-start, same-aim jobs on one relief with different known snapshots and checks their routes differ, while a third job of one version still reuses the route cache. Core release, adapter and WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit a47812aadd fixup! Keep unfinished retarget routes in a bounded job queue (#127)
The relief snapshot was still global: a smart plan finishing while a retarget job waited could replace Sim::known_relief, so the pending route was planned on the newer map. RouteJob now carries Arc<KnownRelief> for its knowledge version; Sim::known_relief keeps the same Arc only to seed new jobs. retarget_relief reads the job's snapshot, and relief sampling, price grids and route caches are keyed by that version. The new regression makes a job wait, swaps the global relief for another grid with a wall, and checks the pending route and sample stay those of the original version; outside its grid is Unknown. Core release, adapter and WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit 6f7b041c8b Keep unfinished retarget routes in a bounded job queue (#127)
A mass retarget used to clear every selected drone's route before the planner's per-tick work ran out: the rest flew straight for ever. Route jobs now carry the drone id, new aim, target unit, knowledge version and the intel snapshot, stay in a FIFO across ticks and are drained under the same WORK_PER_TICK. An old safe route is kept until its replacement is ready; a cancelled job falls back to a straight run. Jobs are replaced in place per drone, cancelled when the drone or unit is gone, and retarget routes reuse the original plan's known relief. An in-flight drone no longer turns to a unit behind its turning circle. Core release tests, adapter tests and the real WASM contract pass.
2026-11-06 12:57:36 +03:00
chexit dc36d67eb7 Unblock supply trucks from an impossible RM48U return (#128)
build / mod (push) Failing after 21s
step_supply sent every free truck into the return branch whenever any
S-400 had a pending ground_return, even when that return could not
proceed (the system moving, damaged, reloading or preparing, its round
already claimed by another truck, the route marked unreachable, or no
depot with room). The branch then found no target, cleared the job and
stopped the truck, so independent typed supply requests starved.

The return now keeps its priority only while it is executable: a
carrier holding a reserved round looks for a depot with room in reach,
an empty one for a system ready to hand a round over. Otherwise the
claim stays untouched and only real RM48U demand (a requesting system
with depot stock, or ground rounds aboard for one) pulls the truck
into the typed supply branch; without such demand it holds its watch
exactly as before. Redirecting a reserved round to a waiting request
clears return_cargo once the last one leaves the truck, and a stale
return_cargo with an empty hold no longer sends the truck to a depot
handover it cannot complete.

Regressions: three sim tests (moving claimant, pickup claimed by
another truck with damaged/save-restore phases, unreachable route) and
one full-drive lib test with a mid-flight state round trip; the rounds
are conserved in every phase and the actual return completes once the
claimant is back. All three sim tests fail on the old code.

Checks: core release 200 passed/8 ignored + 8 scenarios; adapter
67 unit + 1 boundary + 5 scenarios; real WASM test-wasm 30 steps.
2026-11-06 11:11:59 +03:00
chexit d45629ae29 Fix the UI-event fuel trap on a second large raid order
build / mod (push) Failing after 22s
The Windows log for #122 showed the mod stopping in the UI event
(fuel budget 1e9, remaining 0) with known_units <- order_raid <-
launch_wave <- ui_select: order_raid recomputed the planner snapshot
known_units() for every drone, and the snapshot itself rescanned the
whole force and the dedup list per intel entry. A second big Smart
order cost drones x intel-log x force-size inside one event.

Reproduced in actual WASM with measured per-callback fuel through the
exact ui_select(BTN_LAUNCH) handler (diagnostic guest, trigger.patch):
before, a 111-drone second order at revealed=13172/known=144 exhausted
exactly 1e9 and stopped the mod (an 11-drone order at the same state:
247805865); after, the same scenario passes with max command fuel
32946177/1e9, failures=0, and /stats at tick 2602 byte-identical.
A stacked single-point layout dies to one warhead (known=0, cheap
order), so the scenario deploys spread clusters with a moved player.

Fix: one known_units snapshot per order_raid passed to radar_strikes
and choose_target; known_units is a single O(log + force) set pass;
price_grid_on reuses its snapshot. Emitter/network targeting and
carrier choice semantics are unchanged (native equivalence test
against the former predicate; WASM checkpoint counters equal).
Limits unchanged; HD/recording untouched; wave size unrestricted.

Committed regressions: native snapshot-equivalence and
second-smart-order tests; the heavy WASM fixture now orders two Smart
raids through the wave screen's launch function (airdef preset +
airdef raid) with EW and a combat intel log, four accepted orders
asserted; the light contract covers preset and the empty-wave refusal.

Core release 195 + 8 scenarios; adapter 65 + 1 boundary + 5 scenarios;
light WASM 30 steps; heavy WASM 283 steps (tick max 182413686/300M,
command max 6939810/1e9, failures 0). Windows GUI acceptance remains
external and is not claimed.

Co-Authored-By: Kimi Code (Moonshot AI) <noreply@moonshot.cn>
2026-11-06 10:29:36 +03:00
chexit 61aaa0bf35 Record the Metal/offscreen camera picture acceptance
build / mod (push) Failing after 22s
The final engine 6a53a626c with the API30 AirDef build was run in the
real game (macOS, Apple M5, Metal, --offscreen, a clean HORIZON_HOME and
copied test worlds), not only in the sandbox: the monitor and the film's
main view report ready with the picture actually drawn (screenshots show
the panel and picture area, not a registered target), an empty set-views
drops the request, a world change bumps the generation and clears it, and
AirDef's next submission prepares the camera again in the new world.

Fixes nothing: no defect showed. It also records what the run does not
prove (a human visual check, Windows/other GPUs, two runs with the same
local id on the GPU, a mod reload on the GPU), the per-tick
set-views/set-main-view ordering that can honestly read awaiting-frame
between tick and note (not flicker), and that a title trip back into the
same world keeps the request because the generation is per world.

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:10:34 +03:00
chexit 9217f9a5cc Report camera readiness in /airdef capabilities
Pin the engine at 6a53a626c (API 30) and show render.camera-status: the
calling run's set-views cameras, whether the last noted frame was a world
frame, the request's world generation, each camera's reason and the run's
own main-view selection. As the other lines, this is a host milestone:
availability, request, preparation and why, not a GPU frame or a visible
picture. A unit test pins the line: readiness stays per camera and apart
from the run's main-view selection.

docs/ENGINE.md, the 4 November continuation and the status table now say
what prepared means (a picture encoded into the camera's target, or a
world frame drawn from it as this run's screen view, only for the run
whose selection the screen used), the per-run/per-world resets, and what
remains: GPU acceptance.

Verified: python3 tools/airdef.py check (gitlink, packer, mod needs 30,
fork 30, game 30); test-wasm 27 steps; airdef-mod 65 unit, 1 boundary and
5 scenarios; python3 -m unittest discover -s tools 28 tests.

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:08:23 +03:00
chexit 46d2274c8d Measure the #120 balance grid across batteries, ranges and target classes
Wider same-seed sampling of the finite-burn/coast change: baseline 2689d93
(pre-#120) against the current tree, 6 variants x 8 seeds of a 46-drone raid
(batt10/20/50, near200, far1500, hills20). Harness-only: Result carries the
tally's fuse/expired/orphaned/energy_lost counts and a new ignored
sim::balance::issue_120_grid test; no simulation parameters changed.

Findings: kills are equal or up and leaks equal or down in every variant;
fuse misses drop (far1500 70 -> 38 over 8 seeds); hills terrain losses fall
(scrubbed 6 -> 2). MotorEnergyLost never fires in the 48 scenarios and
expired stays <= 1: coast ends before drag reaches the 25% guidance
threshold. Leaks stay concentrated in the ballistic/fast classes
(Iskander/Kinzhal/Kh22/Zircon). No confirmed defect, so no tuning.

Full airdef-core suite: 193 + 8 passed, 0 failed (baseline side 169 + 4).

Co-Authored-By: Kimi Code <noreply@moonshot.cn>
2026-11-04 21:03:01 +03:00
chexit 325119b726 refactor: validate specs without a per-kind name list
The armed/support check in load_specs named the ten armed kinds, so a new
unit type would still have required a code edit and repeated the coupling
#91 is removing. Drop it: optional missile/gun rows are still validated
generically, and the existing kind-coverage check against content.json
already ties specs to the catalog.

validate_specs now takes the document, content identities and sound
events, and a test shows a hypothetical unit kind is accepted from a
specs row plus its content entry alone. No data or balance changes.

Verified: gen_catalog --check fresh, test_gen_assets 10 tests, core
release 195 passed + 8 scenarios (7 ignored), adapter 64 unit +
1 boundary + 5 scenarios, WASM contract 27 steps.
2026-11-04 21:00:35 +03:00
chexit 0937ac9e05 fix: keep the P1-SUN motor voice at its played 1.6 pitch
The old engine_voice returned early for flame == 0 with
(DRONE_LANCET, 0.8, 1.6), so the later `P1sun => 1.7` match arm was
unreachable. The catalog migration mistook that arm for the played value
and stored 1.7, which changed the interceptor drone's flight sound.
specs.json is back to 1.6 and specs_generated.rs is regenerated.

Adds missile_engine_voices_keep_their_played_values, pinning P1-SUN to
(DRONE_LANCET, 0.8, 1.6) and M48N6 to (MISSILE_FLIGHT, 1.0, 0.88).

The continuation and handoff text now describe the early return instead
of the dead arm, and tools/airdef_assets/catalog.py gets its final
newline back.

Verified: gen_catalog --check and test_gen_assets, core release
195 passed + 8 scenarios (7 ignored), adapter 64 unit + 1 boundary +
5 scenarios, WASM contract 27 steps.
2026-11-04 21:00:35 +03:00
chexit ead87343d2 feat: generate simulation numeric profiles from catalog/specs.json
catalog/specs.json is now the single copy of the numeric rows for
DroneSpec, MissileSpec and SamSpec: speed, guidance, warheads, models'
parts, RCS, seekers, launch and motor sounds, mount drives, gravity,
the Oreshnik split height and logistics limits, plus the named part
sets. tools/gen_catalog.py generates airdef-mod/src/sim/specs_generated.rs
(included by mod.rs, so the mod and airdef-core compile the same rows)
and unit_specs_generated.rs (included by units.rs). The hand-written
spec matches are gone; DroneKind::spec, MissileKind::spec and
SamKind::spec read the generated constants.

load_specs validates the schema, sound references, kind coverage against
content.json, named-part references and unused rows. gen_catalog.py
--check already runs in the CI generated-assets step, so a JSON/Rust
drift fails the build.

Every value was compared with the literals at 632061d field by field.
The only mismatch was the P1-SUN motor voice pitch in JSON (1.6 instead
of the actual 1.7, the flame == 0 branch in voices.rs); the JSON was
corrected and behaviour is unchanged. Save keys, raid order, RNG and
gameplay traces are untouched.

Verified: core release 194 passed + 8 scenarios (7 ignored), adapter
64 unit + 1 boundary + 5 scenarios, WASM contract 27 steps, catalog and
model generators fresh, asset/sound/model-bound/report tests pass.
2026-11-04 21:00:35 +03:00
chexit abf3d76fdb docs: record the real MP4 acoustics check (#96)
Pairs of the same replay exported with acoustics on and off on the
scratch world (no HORIZON_NO_AUDIO): acoustics and capture ownership
both ready. The open field has no reverb send by design, so it shows
occlusion/air absorption only; the stone court's on-track is quieter
and darker, and its residual after a gain fit is low-passed and
stereo-decorrelated, i.e. the wet path. A clean reverb tail/RT60 in a
real MP4, echoes alone and listening remain open. No code changes.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:52:11 +03:00
chexit e6a7000440 docs: record the engine cleanup for failed film takes
Engine 60cc7b11d removes a failed or cancelled take's video, raw sound
and log, carries the log's last lines in the error, and only creates
<name>.mp4 after a successful finish. A real failing encoder on the
scratch world left no temporaries and kept the earlier film byte for
byte; successful audio and no-audio control films still verified.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:19:51 +03:00
chexit cec7257ea1 Pin the engine that frees a failed film take's files
horizon 60cc7b11d (on top of 57f8b2853, API 29) removes a failed or
cancelled take's video, raw sound and log, carries the log's last lines
in the error, and only creates <name>.mp4 after a successful finish.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 20:17:52 +03:00
chexit 503e6e29af Fix dynamic model lighting and document GPU comparison (#123)
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 17:53:10 +03:00
chexit 675967ce42 End the show when its world closes and verify the MP4 lifecycle (#89)
A frame hook ends an active film or export when the world is gone. The game
stops ticking at the title screen but keeps rendering, so an export used to
keep recording the title with its playback clock frozen (a sec=10 request
produced 3898 frames) and went on after re-entering the world. Session
cleanup runs once with WorldChange and cancels the capture.

Real short exports on a scratch home and world (pin 57f8b2853, API 29,
Metal): h264+AAC both 2.07 s with non-silent audio, reported frames equal
ffprobe nb_frames; cancel, SDK refusal, encoder failure and restart all
leave no capture running; 1920x1080 works. The engine still leaves
*.audio.raw and *.ffmpeg.log behind on an encoder error (game/film.rs).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-04 17:44:28 +03:00
chexit 632061d2ad docs: archive clean API29 WASM fuel acceptance
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:23:22 +03:00
chexit 56339b076e docs: hand off catalog, model, API29 and acoustics continuation
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:21:29 +03:00
chexit c1a595b773 feat: expose light and sound processing diagnostics with isolated cameras
build / mod (push) Failing after 21s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:19:06 +03:00
chexit 914f723d1f Verify aircraft models as lit mod instances
build / mod (push) Failing after 20s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:16:47 +03:00
chexit d45d59df9f build: pin source-manager processing handshake
Co-Authored-By: Codex <noreply@openai.com>
2026-11-04 16:12:53 +03:00
121 changed files with 19373 additions and 1548 deletions
+1
View File
@@ -2,6 +2,7 @@ run-home/
.horizon-cache/
airdef-mod/target/
airdef-core/target/
tools/rt-probe/target/
__pycache__/
/out/
.DS_Store
+49 -10
View File
@@ -31,6 +31,8 @@ python3 tools/airdef.py play # запустить (аргументы игр
```
`all` синхронизирует URL сабмодуля из `.gitmodules`, включая обновление со старого upstream.
Продолжение 4 ноября: [модели, границы ядра, общий каталог, API29 и массовая акустика](docs/CONTINUATION-2026-11-04.md).
Диагностика в игре: `/airdef capabilities` показывает доступность API, принятие запроса и
подготовку дыма, акустики и захвата именно этого мода. Подготовка не означает готовый GPU-кадр или MP4.
Для разработчика: `python3 tools/airdef.py test-wasm` — лёгкий ABI-тест;
@@ -88,6 +90,9 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает то
**Сохранение.** Комплексы, объекты, их повреждения и настройки сохраняются отдельно для каждого мира (и для каждого
сервера); уничтоженный комплекс остаётся остовом и после перезахода, пока его не отремонтируют.
Налёт в воздухе тоже сохраняется: дроны, очередь их запуска и незавершённые задания на маршрут
восстанавливаются, и перезаход не обрывает перенацеливание. Ракеты-перехватчики в воздухе и площадки
запуска не сохраняются; сценарий — стартовое состояние и налёт не несёт.
**Сеть ПВО.** Единицы обмениваются измеренными треками в пределах игровой связи; повреждение связи
сокращает её дальность. Можно поставить несколько С-400/С-500 без собственной РЛС и общие радары
@@ -131,7 +136,9 @@ sandbox-сценария, `/airdef ground-load <С-400>` загружает од
**Умный противник учится.** Он запоминает, откуда его налёты сбивали, а откуда они прорывались, и следующий
налёт ведёт с лучшего направления; помнит комплексы, выдавшие себя пуском, и станции РЭБ, и во время налёта
перенацеливает ещё не взлетевшие Ланцеты и Шахеды на них; если цель-комплекс уничтожен, дроны идут к
следующему известному. Дроны под обстрелом прижимаются к земле.
следующему известному. Маршруты к новым целям достраиваются по бюджету планировщика в следующих тиках:
необработанное задание не теряется, старый безопасный участок остаётся до готовности нового, а дрон без
маршрута летит прямо только до ближайшего бюджета. Дроны под обстрелом прижимаются к земле.
**Ночь.** Исправные пушки с собственным свежим радарным сопровождением не теряют точность из-за темноты.
Цели освещают **прожекторы** (луч ведёт ближайшую
@@ -175,6 +182,20 @@ API мода `render.set-lights` (до 512, плавно интерполиру
самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда.
Повторное J закрывает.
**Тактическая карта:** клавиша **M** открывает общую карту. Цели обозначены крупными отметками с классом,
курсом и измеренной траекторией; наведение мыши показывает дистанцию, тип, состояние трека и перехват.
По умолчанию доступны только данные сети РЛС. **T** переключает явно подписанный режим «Истина» для
песочницы: в нём белые рамки показывают даже незамеченные аппараты, а жёлтый пунктир — их цель и будущий
маршрут. Этот режим не меняет боевую логику.
**Обзор целей поверх мира:** удерживай **C** — вокруг видимых целей появляются квадратные метки с краткой
строкой: класс, который оценили РЛС (неопознанная цель — «?», без утечки типа), и дистанция; устаревший
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется.
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
(хранятся 3 последних). Меню N → «Повторы…» или клавиша **R**:
- **карта налёта** — вид сверху: комплексы и их зоны, объекты, треки целей (красные), ложных целей (серые) и
@@ -193,7 +214,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
Чтобы в повторах и камерах комплексов была видна земля далеко от игрока, мод включает дальний ландшафт
(48 чанков, упрощённый); выключается в меню N → «Огонь, ремонт, эффекты…» → «Дальний ландшафт».
Клавиши N, K, J, R и U можно переназначить в «Настройки → Моды».
Клавиши N, K, J, 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+ — «Орешник»);
@@ -206,7 +227,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
- `/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 deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — обзорная, сопровождающая и мачтовая игровые РЛС. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию, `/airdef radar <номер> multi|search|engagement|height` — роль отдельной РЛС. Обзорная РЛС передаёт подсказки; станция сопровождения должна сама получить свежее измерение, чтобы разрешить пуск. Старые С-400/С-500 сохраняют упрощённую сборную конфигурацию. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
- `/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 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 deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
@@ -216,10 +237,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef clear` — убрать дроны и ракеты;
- `/airdef targets clear` — снять все цели;
- `/airdef stats` — сводка.
- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится.
Интерфейс:
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт;
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели (с хвостом по курсу), жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара.
- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение);
- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик».
**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет
невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой
только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип,
прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит
между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик —
узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и
счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник
запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню
N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и
дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный
HUD не выводится. Простые пресеты налёта фазу разведки не получают.
Комплексы ПВО и цели сохраняются между сессиями.
@@ -258,7 +292,9 @@ API мода `render.set-lights` (до 512, плавно интерполиру
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
контакта по прямой видимости и передаёт уточнение в класс уже известного сетевого трека — без своего трека,
свежести и права на пуск; не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
**Согласование огня.** Комплексы делят цели между собой: на обычную цель идёт одна ракета, на баллистическую две; чем ближе цель к своей точке попадания,
тем больше перехватчиков разрешено на неё сразу (за ~12 с до удара ещё один, за ~5 с — ещё один). Комплекс, у которого кончились ракеты
@@ -266,10 +302,13 @@ API мода `render.set-lights` (до 512, плавно интерполиру
«Герберы» выглядят для них как настоящие. Геометрия встречи проверяется по движению обоих объектов
за тик, а остаточный шанс учитывает фактическую скорость перехватчика.
**Энергетика перехватчика.** После холодного выброса ракета разгоняется, но двигатель работает
конечное игровое время. После выгорания ракета летит по инерции, теряет скорость и манёвренность;
при недостаточной скорости сопровождение срывается. Факел, звук двигателя и новый дым прекращаются
при выгорании и в live, и в повторе; уже созданный дым продолжает рассеиваться.
**Энергетика перехватчика.** Сначала ракета выходит из ТПК без двигателя: у С-400 это 1,0 с,
у С-500 — 1,2 с; только потом в её текущей точке зажигается факел, и тяга плавно нарастает.
После выброса ракета разгоняется, но двигатель работает конечное игровое время. После выгорания
ракета летит по инерции, теряет скорость и манёвренность; при недостаточной скорости сопровождение
срывается. Факел, звук двигателя и новый дым прекращаются при выгорании и в live, и в повторе;
уже созданный дым продолжает рассеиваться. У ракет с горячим (рельсовым) пуском тяга тоже
нарастает плавно, но холодного выброса нет; электрический P1-SUN не получает ракетную струю.
**Последний шанс** (`/airdef lastchance on|off`, по умолчанию вкл). Комплекс стреляет и по классу целей вне своих ролей
(С-400, С-500 и Patriot по умолчанию не бьют дроны), если цель долетит до своей точки меньше чем за 10 с и на ней ещё нет
+8
View File
@@ -0,0 +1,8 @@
//! The enemy-picture bench (#127) without building the Horizon SDK.
extern crate airdef_core as airdef;
#[path = "../../airdef-mod/examples/intel_bench.rs"]
mod bench;
fn main() {
bench::main();
}
+3 -1
View File
@@ -144,7 +144,9 @@ fn two_maximum_menu_raids_with_answered_flat_terrain() {
let mut second = false;
let mut overlap = false;
let mut peak = 0;
for now in 1..=5000 {
// Two maximum menu raids can keep the last supersonic contact in the air past
// 5000 ticks under the radar profiles; the recording closes once the sky is clear.
for now in 1..=8000 {
if !second && !sim.planning() {
overlap = !sim.queue.is_empty() || sim.drones.iter().any(|d| d.alive());
assert_eq!(sim.order_raid(&order, &targets, &mut out), expected);
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "airdef:item/deploy_optical"
}
}
+1
View File
@@ -123,6 +123,7 @@
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
+1
View File
@@ -123,6 +123,7 @@
"item.airdef.deploy_tzm": "Развернуть ТЗМ",
"item.airdef.deploy_ew": "Развернуть станцию РЭБ",
"item.airdef.deploy_light": "Развернуть прожектор",
"item.airdef.deploy_optical": "Развернуть оптический пост",
"item.airdef.mover": "Пульт перемещения",
"item.airdef.flare_gun": "Осветительная ракета",
"item.airdef.remover": "Свернуть ПВО",
@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
@@ -0,0 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
+57
View File
@@ -0,0 +1,57 @@
//! Enemy-picture outcomes on fixed seeds (#127): what changed for the raids, measured.
//!
//! Runs the standard scenarios over a fixed seed set and prints one JSON object with the
//! completion, losses and failure reasons of every run — the before/after comparison of the
//! honest EnemyPicture is judged on these, not on "it got smarter".
//!
//! cargo run --release --example intel_bench
#[path = "sim_run/harness.rs"]
mod harness;
use harness::{big_smart, ew_adaptive, logistics, Scenario};
fn esc(s: &str) -> String {
s.chars().flat_map(|c| match c {
'"' => "\\\"".chars().collect::<Vec<_>>(),
'\\' => "\\\\".chars().collect::<Vec<_>>(),
c => vec![c],
}).collect()
}
fn run(sc: &Scenario) -> String {
let r = harness::run(sc);
format!(
"{{\"scenario\":\"{}\",\"seed\":{},\"ticks_run\":{},\"raids_ordered\":{},\"raids_ended\":{},\"all_ended\":{},\"launched\":{},\"kills\":{},\"hits\":{},\"crashes\":{},\"sams_lost\":{},\"fired\":{},\"retargets_max\":{},\"air_bytes\":{},\"switches_max\":{},\"intents\":\"{}\",\"failures\":\"{}\"}}",
esc(&r.name),
r.seed,
r.ticks_run,
r.raids_ordered,
r.raids_ended,
r.all_ended,
r.launched,
r.kills,
r.hits,
r.crashes,
r.sams_lost,
r.fired,
r.retargets_max,
r.air_bytes,
r.switches_max,
esc(&r.intents),
esc(&r.failures),
)
}
pub fn main() {
let scenarios: Vec<fn() -> Scenario> = vec![big_smart, logistics, ew_adaptive];
let seeds = [1u64, 7, 42];
let mut rows = Vec::new();
for make in &scenarios {
for &seed in &seeds {
let mut sc = make();
sc.seed = seed;
rows.push(run(&sc));
}
}
println!("[{}]", rows.join(",\n"));
}
+35
View File
@@ -128,6 +128,25 @@ pub struct Report {
pub raids_ordered: usize,
pub raids_ended: usize,
pub all_ended: bool,
/// Systems the defence lost (destroyed units at the end).
pub sams_lost: u32,
/// The most retarget route jobs waiting at once (#127).
pub retargets_max: usize,
/// The largest air section a save would have taken, in bytes (#127).
pub air_bytes: usize,
/// The aims every drone ended with, by intent: "plan:1,sead:2,react:3,replace:0".
pub intents: String,
/// The most aim switches one drone went through.
pub switches_max: u16,
}
/// The last intent every smart drone of the run was seen carrying, as `name:count`.
fn intent_counts(seen: &HashMap<u32, &'static str>) -> String {
let mut counts = std::collections::BTreeMap::new();
for name in seen.values() {
*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(",")
}
fn finite(v: DVec3) -> bool {
@@ -162,6 +181,8 @@ pub fn run(sc: &Scenario) -> Report {
let mut ended = vec![false; sc.raids.len()];
// truck id -> (last position, ticks standing while busy)
let mut standing: HashMap<u32, (DVec3, u64)> = HashMap::new();
// drone id -> the last structured intent it carried (#127).
let mut intents_seen: HashMap<u32, &'static str> = HashMap::new();
let mut out = Out::default();
for now in 1..=sc.ticks {
// Raids come in order: one is ordered once the previous one has been sent.
@@ -194,6 +215,18 @@ pub fn run(sc: &Scenario) -> Report {
pending = wanted.into_iter().map(|(x, z)| (x, z, sc.terrain.height(x, z))).collect();
}
r.ticks_run = now;
r.retargets_max = r.retargets_max.max(sim.retargets_len());
r.switches_max = sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)).map(|d| d.aim_switches()).max().unwrap_or(0).max(r.switches_max);
for d in sim.drones.iter().chain(sim.queue.iter().map(|(_, d)| d)) {
if d.alive() && d.smart() {
intents_seen.insert(d.id, d.intent().name());
}
}
// The air section a save would take, sampled when the sky is fullest (writing it every tick
// would distort the timings the bench measures).
if sim.drones.len() > r.air_bytes {
r.air_bytes = sim.air_text().map_or(0, |t| t.len());
}
// NaN check on everything with a position.
let bad = sim.drones.iter().filter(|d| !finite(d.pos) || !finite(d.vel)).count()
+ sim.missiles.iter().filter(|m| !finite(m.pos)).count()
@@ -227,6 +260,7 @@ pub fn run(sc: &Scenario) -> Report {
}
}
r.launched = sim.launched;
r.sams_lost = sim.sams.iter().filter(|s| !s.alive()).count() as u32;
r.kills = sim.kills;
r.hits = sim.hits;
r.fired = sim.sams.iter().map(|s| s.fired).sum();
@@ -236,6 +270,7 @@ pub fn run(sc: &Scenario) -> Report {
r.failures = sim.tally.text();
r.raids_ended = ended.iter().filter(|o| **o).count();
r.all_ended = r.raids_ended == sc.raids.len();
r.intents = intent_counts(&intents_seen);
r.tick_total = times.iter().sum();
times.sort();
if !times.is_empty() {
+5 -2
View File
@@ -114,6 +114,7 @@ b50fe5804cbbe10df992ebbc7e095a32ce8b73fc35159fa19889640681e408e9 assets/airdef/
0c9c5ee3fc87e2dc6d716bdb0bb5f30d3b265268bfd5083462b4861a8da65f0f assets/airdef/items/deploy_irist.json
09e46a6c4b59f66c24060ac627e6a287bf6797c7b1e32a9ec6c9d9662fdc3de3 assets/airdef/items/deploy_light.json
6983561b3558aee16662aa83d2d9af760fb6236cc7dbe79ba20802f8a2ff15b9 assets/airdef/items/deploy_nasams.json
e39c555ff197ed6c7c8fdfab924b7a609b5d111a905ca599a75a7b1270448fcc assets/airdef/items/deploy_optical.json
d8ac6a9258e2fc2e0791bbce18a3a07a72e471fbc72b6be7b5ca545c53f8d633 assets/airdef/items/deploy_p1sun.json
e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json
68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json
@@ -136,8 +137,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/en_us.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/ru_ru.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/en_us.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/ru_ru.json
b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json
c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json
a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json
@@ -254,6 +255,7 @@ a5d0450da8d6757b9b45f86e6b36977894dd9e3e1278c3668b99a8acab36f399 assets/airdef/
e80ee81085241b9712e024bbef73ef744ef5493eebb88770f4912d8aae138fe6 assets/airdef/models/item/deploy_irist.json
637b9bfe426ee50045f8fcbfd4f25dfbc1d819ce36dedbd60abdac63c274f088 assets/airdef/models/item/deploy_light.json
3398844e90203f97ee73e35619684c775d1856c8ca3399b5ed682786170d9327 assets/airdef/models/item/deploy_nasams.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_optical.json
76019c05d070cf1141cdf95b744b3d6198ab99469dba1f88a6903de1de303bde assets/airdef/models/item/deploy_p1sun.json
8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json
d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json
@@ -567,6 +569,7 @@ cc0877f40434365b45b03429222926aa0cf135e504017311be53263fd27c5f8f data/airdef/ho
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_irist.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_light.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_nasams.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_optical.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_p1sun.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json
+188 -17
View File
@@ -1,22 +1,34 @@
//! Player-facing labels for battery configuration snapshots.
use crate::sim::battery::{BatteryStatus, RadarRole, SamMode};
//! Player-facing labels for battery configuration and status.
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
use crate::sim::{Sam, SamKind};
pub fn radar_role_name(role: RadarRole) -> &'static str {
match role {
RadarRole::Multifunction => "многофункциональная",
RadarRole::Search => "обзорная",
RadarRole::Engagement => "сопровождения",
RadarRole::Height => "мачтовая",
}
/// One profile's functions in a line the player can read.
pub fn radar_profile_line(profile: RadarProfile) -> String {
let channels = if profile.channels == 0 { "без каналов уточнения".to_string() } else { format!("каналы {}", profile.channels) };
format!(
"{} [{}]: {}, оборот {:.1} с, {}, локальный поиск {}; развёртывание: {}",
profile.name,
profile.id,
profile.products_text(),
profile.cycle as f64 / 20.0,
channels,
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
profile.deployment,
)
}
pub fn status(status: BatteryStatus) -> String {
match status {
BatteryStatus::Radar { index, role, emitting, operational } => format!(
"№{} РЛС: {}, излучение {}, {}", index + 1, radar_role_name(role),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
),
BatteryStatus::Radar { index, role, emitting, operational } => {
let profile = role.profile();
format!(
"№{} РЛС: {}; излучение {}, {}",
index + 1,
radar_profile_line(profile),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
)
}
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
if mode == SamMode::LauncherOnly {
@@ -26,15 +38,174 @@ pub fn status(status: BatteryStatus) -> String {
}
}
/// One system's line in the summary panel and on the map.
pub fn sam_status(sam: &Sam) -> String {
let spec = sam.kind.spec();
let mut text = spec.name.to_string();
if !sam.alive() {
return text + " УНИЧТОЖЕН";
}
if sam.moving() {
return text + " " + &sam.state.name().to_lowercase();
}
match sam.kind {
SamKind::Depot => return format!("{text}: {} перезарядок, RM48U {}, снятых ПВО {}", sam.cargo, sam.ground_stock, sam.air_48n6_stock),
SamKind::Tzm => return format!(
"{text}: на борту {}/2, RM48U {}, снятых ПВО {}{}",
sam.cargo,
sam.ground_stock,
sam.air_48n6_stock,
if sam.return_cargo { ", везёт RM48U на склад" } else if sam.job().is_some() { ", в пути" } else { "" }
),
SamKind::Ew => {
let state = if sam.ew_on { "ГЛУШИТ" } else if sam.ew_lock { "остывает" } else { "готова" };
return format!("{text}: {state}, нагрев {:.0}%", sam.heat * 100.0);
}
SamKind::Radar => {
let broken = if sam.comps.whole() { String::new() } else { format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)) };
let profile = sam.radar_profile();
let channels = if profile.channels == 0 {
"без уточнения".to_string()
} else {
format!("каналы {}/{}", sam.own_channels_used(), profile.channels)
};
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
}
SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }),
SamKind::Optical => {
let mut t = format!("{text}: {}", sam.optical.status_text());
if sam.health < 1.0 {
t += &format!(" ({:.0}%)", sam.health * 100.0);
}
if !sam.comps.whole() {
t += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
}
return t;
}
_ => {}
}
if let Some(cell) = sam.preparing_cell() {
text += &format!(" · открытие ТПК №{}", cell + 1);
}
if sam.empty && sam.missiles == 0 {
text += " ЖДЁТ БК";
}
if sam.health < 1.0 {
text += &format!(" ({:.0}%)", sam.health * 100.0);
}
if !sam.comps.whole() {
text += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind));
}
if sam.reloading > 0 {
text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20));
} else {
if let Some(magazine) = sam.kind.missile_magazine() {
if sam.kind == SamKind::S400 {
text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells());
if sam.ground_return { text += " · ожидает вывоза RM48U"; }
} else {
text += &format!(" ракеты {}/{}", sam.missiles, magazine);
}
}
if sam.kind.has_gun() {
text += &format!(" очереди {}", sam.bursts);
}
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::SamKind;
use crate::sim::battery::RadarRole;
use crate::sim::{Part, Sam, SamKind, SamState};
use glam::DVec3;
#[test]
fn renders_system_status_in_existing_format() {
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
s400.missiles = 1;
s400.ground_rounds = 2;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
s400.ground_return = true;
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
pantsir.missiles = 7;
pantsir.bursts = 100;
assert_eq!(sam_status(&pantsir), "Панцирь-С1 ракеты 7/12 очереди 100");
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
worn.health = 0.5;
worn.comps.0[Part::Sensor as usize] = 0.4;
worn.reloading = 21;
assert_eq!(sam_status(&worn), "Patriot (50%) [РЛС 40%] перезарядка 2с");
}
#[test]
fn renders_special_system_lines_in_existing_format() {
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
radar.own.push(7);
radar.comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
depot.cargo = 2;
depot.ground_stock = 3;
depot.air_48n6_stock = 1;
assert_eq!(sam_status(&depot), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
tzm.cargo = 1;
tzm.return_cargo = true;
assert_eq!(sam_status(&tzm), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
ew.ew_on = true;
ew.heat = 0.5;
assert_eq!(sam_status(&ew), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
light.target = Some(1);
assert_eq!(sam_status(&light), "Прожектор: в луче цель");
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
assert_eq!(sam_status(&optical), "Оптический пост: ищет");
}
#[test]
fn renders_moving_and_destroyed_systems_in_existing_format() {
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
moving.state = SamState::Moving;
assert_eq!(sam_status(&moving), "С-400 на марше");
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
dead.health = 0.0;
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН");
}
#[test]
fn profiles_explain_their_different_functions() {
for role in [RadarRole::Search, RadarRole::Height, RadarRole::Engagement, RadarRole::Multifunction] {
let text = radar_profile_line(role.profile());
assert!(text.contains(role.profile().id));
assert!(text.contains(&format!("оборот {:.1} с", role.profile().cycle as f64 / 20.0)));
}
assert!(radar_profile_line(RadarRole::Search.profile()).contains("без каналов"));
assert!(radar_profile_line(RadarRole::Engagement.profile()).contains("каналы 2"));
assert!(radar_profile_line(RadarRole::Height.profile()).contains("уточнение"));
}
#[test]
fn renders_battery_status_in_existing_format() {
assert_eq!(status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }), "№1 РЛС: обзорная, излучение выкл, нет связи или РЛС не работает");
assert_eq!(status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }), "№2 РЛС: сопровождения, излучение вкл, работает");
assert_eq!(
status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }),
"№1 РЛС: дальнего обзора [radar_search]: обзор, оборот 8.5 с, без каналов уточнения, локальный поиск во всей дальности; развёртывание: крупная стационарная антенна; излучение выкл, нет связи или РЛС не работает"
);
assert_eq!(
status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }),
"№2 РЛС: сопровождения [radar_track]: обзор, уточнение, пуск, оборот 3.5 с, каналы 2, локальный поиск 12% дальности; развёртывание: мобильная панель; излучение вкл, работает"
);
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
+94 -1
View File
@@ -59,10 +59,42 @@ fn line(
format!("{name}: API={available}, включено={enabled}, запрос={accepted}, подготовлено={prepared}, поколение={generation}, {why}")
}
fn camera_line(s: &render::CameraState) -> String {
let cameras: Vec<String> = s
.cameras
.iter()
.map(|c| {
let why = match c.reason {
render::CameraReason::AwaitingFrame => "awaiting-frame",
render::CameraReason::Ready => "ready",
};
format!("{}:{}", c.id, why)
})
.collect();
let main = match s.main_view {
Some(id) => id.to_string(),
None => "нет".into(),
};
format!(
"Камеры: API={}, включено={}, запрос={}, подготовлено={}, поколение={}, {}, main={}, [{}]",
s.available,
s.enabled,
s.request_accepted,
s.prepared,
s.generation,
reason(s.reason),
main,
cameras.join("; ")
)
}
pub fn diagnostics() -> String {
let smoke = render::smoke_status();
let acoustic = acoustics();
let capture = render::capture_owner_status();
let lights = render::point_lights_status();
let sources = render::sound_sources_status();
let cameras = render::camera_status();
let smoke_reason = match smoke.reason {
render::SmokeReason::AwaitingFrame => "awaiting-frame",
render::SmokeReason::Disabled => "disabled",
@@ -70,7 +102,7 @@ pub fn diagnostics() -> String {
render::SmokeReason::Ready => "ready",
};
[
"Возможности движка (API 27; подготовка не означает готовый GPU-кадр или файл):".into(),
"Возможности движка (API 31; подготовка не означает готовый GPU-кадр, слышимый звук или файл):".into(),
line(
"Дым",
smoke.generation,
@@ -89,6 +121,25 @@ pub fn diagnostics() -> String {
acoustic.prepared,
reason(acoustic.reason),
),
line(
"Точечный свет",
lights.generation,
lights.available,
lights.enabled,
lights.request_accepted,
lights.prepared,
reason(lights.reason),
),
line(
"Постоянные звуки",
sources.generation,
sources.available,
sources.enabled,
sources.request_accepted,
sources.prepared,
reason(sources.reason),
),
camera_line(&cameras),
line(
"Захват этого мода",
capture.generation,
@@ -144,4 +195,46 @@ mod tests {
s.reason = CapabilityReason::Failed;
assert!(capture_problem(&s).is_some());
}
fn camera(id: u32, prepared: bool) -> render::CameraReadiness {
render::CameraReadiness {
id,
request_accepted: true,
prepared,
reason: if prepared {
render::CameraReason::Ready
} else {
render::CameraReason::AwaitingFrame
},
}
}
#[test]
fn the_camera_line_separates_readiness_from_the_screens_selection() {
let line = camera_line(&render::CameraState {
generation: 5,
available: true,
enabled: true,
request_accepted: true,
prepared: true,
reason: CapabilityReason::Ready,
cameras: vec![camera(7, true), camera(8, false)],
main_view: Some(7),
});
assert_eq!(
line,
"Камеры: API=true, включено=true, запрос=true, подготовлено=true, поколение=5, \
ready, main=7, [7:ready; 8:awaiting-frame]"
);
// No accepted submission: no cameras, no main view, and the reason says so.
let line = camera_line(&render::CameraState {
generation: 5,
available: true,
enabled: false,
request_accepted: false,
prepared: false,
reason: CapabilityReason::NotRequested,
cameras: Vec::new(),
main_view: None,
});
assert!(line.ends_with("not-requested, main=нет, []"), "{line}");
}
}
+18 -5
View File
@@ -14,7 +14,7 @@ fn on_off() -> Value {
/// `/airdef ...` as `lib.rs` accepts it.
pub fn tree() -> Tree {
let wave_kinds: Vec<&str> = DroneKind::ALL.iter().map(|k| k.spec().key).chain(["mix"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(crate::sim::catalog::VARIANTS.iter().map(|v| v.id)).collect();
let armed: Vec<&str> = SamKind::ARMED.iter().map(|k| k.key()).chain(["all"]).collect();
let toggle = |word: &str| Node::lit(word).then(Node::arg("on/off", on_off()).runs());
Tree::new("airdef").runs().with([
@@ -73,7 +73,7 @@ pub fn tree() -> Tree {
Node::lit("target").then(Node::lit("here").runs()),
Node::lit("give").runs(),
Node::lit("battery").runs().then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::choice(["integrated", "launcher"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("роль", Value::choice(["on", "off", "multi", "search", "engagement", "height"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).runs())),
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
Node::lit("wave").then(
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
@@ -106,6 +106,7 @@ pub fn tree() -> Tree {
Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]),
Node::lit("reset").runs(),
])),
Node::lit("recon").runs(),
Node::lit("stats").runs(),
])
}
@@ -162,7 +163,7 @@ mod tests {
#[test]
fn every_branch_of_the_handler_parses() {
for line in [
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles",
"", "menu", "capabilities", "monitor", "grid", "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 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",
@@ -241,10 +242,10 @@ mod tests {
fn completion_offers_the_next_word_only() {
let top = complete("", &[]);
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", "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"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 35);
assert_eq!(top.len(), 36);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
@@ -258,6 +259,18 @@ mod tests {
assert!(complete("wave nothing ", &[]).is_empty());
}
/// A station's profile is fixed at deployment: completion offers only emission, while an
/// old role word still reaches the handler's explanation instead of a bare parse error.
#[test]
fn radar_completion_offers_emission_only() {
let words = complete("radar 1 ", &[]);
assert_eq!(words.len(), 2, "{words:?}");
assert!(words.contains(&"on".to_string()) && words.contains(&"off".to_string()));
for old in ["multi", "search", "engagement", "height"] {
assert!(tree().parse(&format!("radar 1 {old}")).is_ok(), "`{old}` should reach the handler");
}
}
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
#[test]
fn scenario_names_follow_a_save_and_a_delete() {
+43 -1
View File
@@ -31,6 +31,9 @@ pub struct SamRec {
pub air_48n6_stock: u32,
pub mode: sim::battery::SamMode,
pub radar_role: sim::battery::RadarRole,
/// The stable profile ID when the file names one (new saves); old files
/// have only the role key, which migrates to the matching profile.
pub radar_profile: Option<sim::battery::RadarProfile>,
pub spent_cells: u8,
pub radar_on: bool,
}
@@ -147,10 +150,20 @@ impl Layout {
let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true);
let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false);
let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false);
let radar_profile = match l.w.get(32) {
None => None,
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 radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
}
if let Some(profile) = radar_profile {
if kind != SamKind::Radar { return Err(l.bad("профиль РЛС", "профиль поддерживается только отдельной РЛС")); }
if profile.role() != radar_role { return Err(l.bad("профиль РЛС", "профиль и роль не совпадают")); }
}
// 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)));
if mode == sim::battery::SamMode::LauncherOnly && !matches!(kind, SamKind::S400 | SamKind::S500) {
return Err(l.bad("режим", "пусковая поддерживается только С-400 и С-500"));
}
@@ -160,7 +173,7 @@ impl Layout {
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 {
return Err(l.bad("боезапас", "больше четырёх ячеек"));
}
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, 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 });
}
"target" => {
if out.targets.len() >= MAX_UNITS {
@@ -220,6 +233,7 @@ mod tests {
assert_eq!(l.sams[0].mode, sim::battery::SamMode::LauncherOnly);
assert_eq!(l.sams[0].spent_cells, 5);
assert_eq!(l.sams[1].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(l.sams[1].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT), "an old role-only line migrates");
assert!(!Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 false")).unwrap().sams[0].radar_on);
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 nope")).is_err());
assert!(Layout::parse(&data.replace("engagement", "invalid")).is_err());
@@ -230,6 +244,13 @@ mod tests {
SamKind::Patriot.key()
}
#[test]
fn an_optical_post_loads_by_its_catalog_key() {
let l = Layout::parse("sam optical 10 70 20 0.5\n").unwrap();
assert_eq!(l.sams[0].kind, SamKind::Optical);
assert_eq!(l.sams[0].mode, sim::battery::SamMode::Integrated);
}
// #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line
#[test]
fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() {
@@ -258,6 +279,27 @@ mod tests {
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
}
#[test]
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 l = Layout::parse(old).unwrap();
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Search);
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::SEARCH));
let new = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement 0 0 true false false radar_track";
let l = Layout::parse(new).unwrap();
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT));
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(
Layout::parse("sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 0 true false false radar_multi").unwrap().sams[0].radar_profile,
Some(sim::battery::RadarProfile::MULTI)
);
// A profile and the legacy role must agree; a profile on a non-radar is refused.
assert!(Layout::parse(&new.replace("engagement 0", "search 0")).is_err());
assert!(Layout::parse(&new.replace("sam radar", "sam s400").replace("engagement", "multi")).is_err());
assert!(Layout::parse(&new.replace("radar_track", "radar_unknown")).is_err());
assert_eq!(sim::battery::RadarProfile::from_id("multi"), Some(sim::battery::RadarProfile::MULTI));
}
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
#[test]
fn older_valid_saves_still_load() {
+317 -38
View File
@@ -21,9 +21,11 @@ mod layout;
mod map;
mod film;
mod monitor;
mod overlay;
mod panel;
mod presentation;
mod radar;
mod recon_view;
mod replay;
mod scene;
mod smoke;
@@ -96,6 +98,10 @@ struct AirDef {
by_id: Vec<ModelInstanceId>,
/// The command map (#48).
map: map::MapUi,
/// The world overlay's key held (#132): markers over normal gameplay while it is.
overlay_held: bool,
/// The overlay's shapes are the mod's `set-hud` now: cleared when it lets go.
overlay_shown: bool,
}
/// What `/airdef replay export` was asked for.
@@ -200,33 +206,27 @@ enum Page {
More,
/// The last raid's events and its replays.
Replays,
/// The enemy's recon picture and why it prices each mark: debug and after-action review (#135).
Recon,
/// The systems with their doctrines, and one system's doctrine (by id) (#47).
Fleet,
Doctrine(u32),
}
const MENU_KINDS: u32 = 1;
const BATTERY_ROWS: u32 = 5;
const BTN_BATTERY: u32 = 22;
const BATTERY_DEPLOY: [(&str, &str); 5] = [
("s400_launcher", "С-400 — отдельная пусковая"),
("s500_launcher", "С-500 — отдельная пусковая"),
("radar_search", "РЛС обзора"),
("radar_track", "РЛС сопровождения"),
("radar_height", "Мачтовая РЛС"),
];
const BATTERY_ROWS: u32 = sim::catalog::VARIANTS.len() as u32;
/// A battery deploy piece from the catalog: a unit kind or one of its variants.
fn deploy_configuration(key: &str) -> Option<(SamKind, sim::battery::SamMode, sim::battery::RadarRole)> {
use sim::battery::{RadarRole as R, SamMode as M};
Some(match key {
"s400_launcher" => (SamKind::S400, M::LauncherOnly, R::Multifunction),
"s500_launcher" => (SamKind::S500, M::LauncherOnly, R::Multifunction),
"radar_search" => (SamKind::Radar, M::Integrated, R::Search),
"radar_track" => (SamKind::Radar, M::Integrated, R::Engagement),
"radar_height" => (SamKind::Radar, M::Integrated, R::Height),
_ => (SamKind::from_key(key)?, M::Integrated, R::Multifunction),
})
match sim::catalog::variant(key) {
Some(v) => Some((v.kind, v.mode, v.role)),
// A bare kind deploys its ordinary integrated configuration.
None => Some((SamKind::from_key(key)?, M::Integrated, R::Multifunction)),
}
}
const BTN_HOLD: u32 = 10;
const BTN_SHADER: u32 = 11;
const BTN_DAMAGE: u32 = 12;
@@ -243,7 +243,9 @@ const BTN_LAUNCH: u32 = 34;
const BTN_NEXT: u32 = 35;
const BTN_MORE: u32 = 17;
const BTN_REPLAYS: u32 = 18;
const BTN_RECON: u32 = 23;
const REPLAY_EVENTS: u32 = 3;
const RECON_ROWS: u32 = 6;
const BTN_MAP: u32 = 40;
const BTN_FULL: u32 = 41;
const BTN_REEL: u32 = 42;
@@ -879,14 +881,37 @@ impl AirDef {
}
self.hud_shown = true;
hud::set_panel(Corner::TopRight, &panel::summary(&self.sim, &pic, player));
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::SIZE + 12.0, &radar::draw(&self.sim, player, yaw));
let truth_label = self.sim.truth && !pic.unaided;
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::height(truth_label), &radar::draw(&self.sim, player, yaw));
}
/// Whether the world overlay draws now (#132): its key held over normal gameplay — not under
/// a replay, the grid, a monitor or the map, which own the screen themselves.
fn overlay_active(&self) -> bool {
self.overlay_held
&& self.presentation.is_live()
&& !self.grid
&& self.monitor.is_none_or(|i| i >= self.sim.sams.len())
&& !self.map.open
}
fn draw_overlay(&mut self) {
let Some(p) = player() else { return };
let shapes = overlay::draw(&self.sim, DVec3::new(p.x, p.y, p.z), render::gui_size(), |w| render::project(w.x, w.y, w.z));
render::set_hud(&shapes);
}
// ------------------------------------------------ saving
/// The state as text, lines of words: the autosave's format, and the body of a scenario.
/// `fresh`: every system and object whole, magazines full (a scenario to replay from the start).
/// The air state (the raid's drones, launch queue, retarget jobs and the picture behind them,
/// #127) belongs to the autosave only: a scenario is a start state, not a raid frozen mid-flight.
fn state_text(&self, fresh: bool, view: bool) -> String {
self.state_text_with(fresh, view, !fresh)
}
fn state_text_with(&self, fresh: bool, view: bool, air: bool) -> String {
let mut text = String::new();
for s in &self.sim.sams {
// Then its ammunition (missiles, bursts, out and waiting for a truck, reload ticks
@@ -901,8 +926,9 @@ impl AirDef {
// The parts' states (sensor, mount, launcher, gun, tracks, comms) close the line; older saves lack them.
let comps = if fresh { new.comps } else { s.comps };
let parts = comps.0.iter().map(|v| format!("{v:.3}")).collect::<Vec<_>>().join(" ");
let profile = if s.kind == SamKind::Radar { format!(" {}", s.radar_profile().id) } else { String::new() };
text += &format!(
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}\n",
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}{profile}\n",
s.kind.key(),
s.pos.x,
s.pos.y,
@@ -939,11 +965,27 @@ impl AirDef {
for (i, s) in self.sim.sams.iter().enumerate().filter(|(_, s)| !s.doctrine.is_default()) {
text += &format!("doctrine {i} {}\n", s.doctrine.save_text());
}
// The enemy's air state, last: it names its own format version, so an older build (or an
// older save) reads the layout and ignores it (#127).
if air && let Some(a) = self.sim.air_text() {
text += &a;
}
text
}
fn save(&mut self) {
let text = self.state_text(false, true);
self.save_with(true);
}
/// Writes the state. `air`: include the enemy's air state (#127). A raid still being *planned* has
/// no durable form — its items, sites and routes are half made — so a periodic save waits for it
/// to be launched (at most `sites::SEARCH_TICKS`), while a world change takes the layout alone.
fn save_with(&mut self, air: bool) {
if air && self.sim.planning() {
self.next_save = self.sim.tick + 20;
return;
}
let text = if air { self.state_text(false, true) } else { self.state_text_with(false, true, false) };
// Clean only once written: a failed write is tried again after a pause.
match storage::set(&self.state_key(), text.as_bytes()) {
Ok(()) => {
@@ -993,7 +1035,15 @@ impl AirDef {
/// naming the line and field, and the scene stays as it was (#86).
fn apply_state(&mut self, text: &str) -> Result<(), String> {
let layout = layout::Layout::parse(text)?;
// The air section is checked before anything is touched, like the layout (#127).
let air = sim::Sim::parse_air(text)?;
self.commit_layout(layout);
if let Some(air) = air {
let cancelled = self.sim.restore_air(air);
if cancelled > 0 {
say(&format!("Воздушная обстановка восстановлена: отменено устаревших заданий {cancelled}"));
}
}
Ok(())
}
@@ -1031,7 +1081,9 @@ impl AirDef {
sam.air_48n6_stock = r.air_48n6_stock;
sam.fit_cells();
sam.set_mode(r.mode);
sam.set_radar_role(r.radar_role);
// New saves name the stable profile; old ones only the role, which
// parses to the same profile (`Layout::parse`).
sam.set_radar_role(r.radar_profile.map_or(r.radar_role, |p| p.role()));
sam.radar_on = r.radar_on;
sam.spent_cells = r.spent_cells;
sam.sync_tube_cells();
@@ -1134,6 +1186,10 @@ fn durable_mark(sim: &Sim) -> u64 {
.fold(sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h))
.wrapping_mul(31)
.wrapping_add(strikes)
// The air state's shape (#127): a launch, a loss, a new or finished route job makes the
// autosave take the raid as it stands, so a reload resumes it rather than an empty sky.
.wrapping_mul(31)
.wrapping_add(sim.air_mark())
}
impl AirDef {
@@ -1158,7 +1214,9 @@ impl AirDef {
/// Another world opened: the last one's state saved, a clean simulation with this one's loaded.
fn open_world(&mut self, world: Option<String>) {
if self.world.is_some() && self.dirty {
self.save();
// Leaving the world: the layout is kept, a raid still being planned is not (it would have
// no drones to resume and the world it belonged to is going).
self.save_with(false);
}
self.end_session(presentation::ExitCause::WorldChange);
let shader = self.sim.shader;
@@ -1171,6 +1229,9 @@ impl AirDef {
self.map_close();
self.grid = false;
self.grid_ids.clear();
// The overlay key lets go with the world: its camera projects nothing here anyway.
self.overlay_held = false;
self.overlay_shown = false;
// The last world's transient state: its sounds were due on its own
// clock, its picked unit may have another meaning in this one, and
// its models would stay until the next full model list.
@@ -1467,13 +1528,13 @@ impl AirDef {
/// monitored one always; those shown keep a head start, so the grid doesn't flicker.
fn pick_grid(&mut self) {
let shown = &self.grid_ids;
// Units that shoot, and the radars; depots, trucks and lights have nothing to show.
// Units that shoot, the radars and the passive optics; depots, trucks and lights have nothing to show.
let mut scored: Vec<(f64, u32)> = self
.sim
.sams
.iter()
.enumerate()
.filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar)
.filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar || s.kind == SamKind::Optical)
.map(|(i, s)| {
let busy = if self.sim.showing_kill(s) { 98.0 } else { match s.state {
sim::SamState::Launch | sim::SamState::Fire => 100.0,
@@ -1487,7 +1548,11 @@ impl AirDef {
sim::SamState::Waiting => 35.0,
sim::SamState::Packing | sim::SamState::Moving | sim::SamState::Deploying => 40.0,
} };
let near = self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0)));
let near = if s.kind == SamKind::Optical {
0.0
} else {
self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0)))
};
let hurt = if s.alive() && s.health < 0.7 { 15.0 } else { 0.0 };
let keep = if shown.contains(&s.id) { 12.0 } else { 0.0 };
let pinned = if self.monitor == Some(i) { 1000.0 } else { 0.0 };
@@ -1523,7 +1588,8 @@ impl AirDef {
self.sim.sams.push(sam);
self.sim.settle(id);
self.dirty = true;
Ok(format!("{} развёрнут ({}, {})", kind.name(), mode.key(), role.key()))
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
Ok(format!("{} развёрнут ({}, {}{profile})", kind.name(), mode.key(), role.key()))
}
fn open_menu(&mut self, page: Page) {
@@ -1550,11 +1616,16 @@ impl AirDef {
widgets.push(Widget::Button(ButtonWidget { id: BTN_DOCTRINE, label: format!("Доктрины: охрана, сектор, резерв (особых: {custom})…") }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_WAVE, label: "Налёт: состав и запуск…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_REPLAYS, label: "Повторы…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() }));
}
Page::BatteryDeploy => {
title = "Размещение батареи — клик создаёт технику перед игроком".into();
widgets.push(Widget::List(ListWidget { id: BATTERY_ROWS, rows: BATTERY_DEPLOY.iter().map(|(_, name)| (*name).to_string()).collect(), selected: None }));
widgets.push(Widget::List(ListWidget {
id: BATTERY_ROWS,
rows: sim::catalog::VARIANTS.iter().map(|v| format!("{} — {}", v.label, v.description)).collect(),
selected: None,
}));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::Replays => {
@@ -1567,6 +1638,7 @@ impl AirDef {
widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_FULL, label: "Полный повтор".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
}
None => {
title = "Повторы".into();
@@ -1575,10 +1647,17 @@ impl AirDef {
text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(),
color: 0,
}));
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
}
}
Page::Recon => {
title = "Разведка противника — разбор (debug): что враг запомнил и почему".into();
let rows: Vec<String> = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect();
widgets.push(Widget::List(ListWidget { id: RECON_ROWS, rows, selected: None }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::More => {
title = "AirDef — управление".to_string();
widgets.push(Widget::Button(ButtonWidget {
@@ -1817,8 +1896,12 @@ impl Mod for AirDef {
model_generation: u32::MAX,
by_id: Vec::new(),
map: map::MapUi::default(),
overlay_held: false,
overlay_shown: false,
};
let _ = input::register_key("map", "Карта: командная, расстановка", "key.keyboard.m");
// C is free in vanilla's bindings and the mod's own; the player may rebind it.
let _ = input::register_key("overlay", "Обзор: метки целей вокруг видимых дронов и ракет (удерживать)", "key.keyboard.c");
let _ = input::register_key("menu", "Меню AirDef", "key.keyboard.n");
let _ = input::register_key("monitor", "Монитор ПВО: следующий комплекс", "key.keyboard.k");
let _ = input::register_key("grid", "Командный пункт: все комплексы", "key.keyboard.j");
@@ -1839,7 +1922,7 @@ impl Mod for AirDef {
me.apply_far();
// Subcommands, typed arguments and the saved scenarios' names for the chat box (#98).
commands::register(&scenario::saved_names());
Ok((me, Registration::new().command("airdef").on_tick()))
Ok((me, Registration::new().command("airdef").on_tick().on_frame()))
}
fn tick(&mut self, tick: u64) {
@@ -1855,6 +1938,9 @@ impl Mod for AirDef {
for event in input::poll() {
match event {
Event::UseStart(u) => self.use_item(&u.item.id),
// The overlay is a hold, not a toggle (#132): down draws, up clears.
Event::KeyDown(k) if k == "overlay" => self.overlay_held = true,
Event::KeyUp(k) if k == "overlay" => self.overlay_held = false,
Event::KeyDown(k) if k == "map" => self.map_toggle(),
Event::KeyDown(k) if k == "menu" => {
if self.presentation.playback().is_some() {
@@ -2051,6 +2137,15 @@ impl Mod for AirDef {
render::set_views(&[]);
self.monitor_shown = false;
}
// The world overlay owns the HUD while its key is held over normal gameplay;
// the frame hook redraws it every frame, the tick keeps the ownership honest.
if self.overlay_active() {
self.draw_overlay();
self.overlay_shown = true;
} else if self.overlay_shown {
render::set_hud(&[]);
self.overlay_shown = false;
}
}
}
}
@@ -2080,8 +2175,8 @@ impl Mod for AirDef {
return;
}
(Page::BatteryDeploy, BATTERY_ROWS) => {
if let Some((key, _)) = BATTERY_DEPLOY.get(row as usize) {
match self.deploy_configured(key) {
if let Some(v) = sim::catalog::VARIANTS.get(row as usize) {
match self.deploy_configured(v.id) {
Ok(message) => say(&message),
Err(error) => say(&error),
}
@@ -2226,6 +2321,16 @@ impl Mod for AirDef {
self.open_menu(Page::Main);
return;
}
(Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => {
self.open_menu(Page::Recon);
return;
}
(Page::Recon, BTN_BACK) => {
self.open_menu(Page::Main);
return;
}
// The review is read-only: a row click changes nothing.
(Page::Recon, RECON_ROWS) => return,
(Page::Main, BTN_MORE) => {
self.open_menu(Page::More);
return;
@@ -2280,6 +2385,23 @@ impl Mod for AirDef {
self.menu = None;
}
/// A frame runs outside a world too (the title screen), where no tick does: a film or an
/// export still active there is ended, so its capture cannot go on recording the title.
fn frame(&mut self, _seconds: f32) {
if self.presentation.is_live() {
// The overlay tracks the drawn camera frame by frame (`render.project` is at most a
// frame behind); the other screens own the HUD at the tick's pace, as before.
if self.overlay_active() {
self.draw_overlay();
self.overlay_shown = true;
}
return;
}
if let Some(cleanup) = self.presentation.world_left(world_identity().as_deref()) {
cleanup.apply(self);
}
}
fn command(&mut self, _name: &str, args: &str) -> Result<Option<String>, String> {
let w: Vec<&str> = args.split_whitespace().collect();
let mut out = Out::default();
@@ -2305,7 +2427,7 @@ impl Mod for AirDef {
["battery"] => {
let status = self.sim.battery_status();
for entry in status { say(&battery_view::status(entry)); }
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off|multi|search|engagement|height".into())
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off; профиль задаётся deploy radar_search|radar_track|radar_height".into())
}
["battery", n, mode] => {
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер комплекса")?;
@@ -2323,13 +2445,12 @@ impl Mod for AirDef {
self.dirty = true;
Some(format!("№{} {}: излучение РЛС {}", i + 1, sam.kind.name(), state))
}
["radar", n, role] => {
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер РЛС")?;
["radar", _n, role] => {
let role = sim::battery::RadarRole::from_key(role).ok_or("Роль: multi, search, engagement или height")?;
let sam = self.sim.sams.get_mut(i).ok_or("Нет такого комплекса")?;
if !sam.set_radar_role(role) { return Err("Нужна отдельная РЛС".into()); }
self.dirty = true;
Some(format!("№{} РЛС: роль {}", i + 1, role.key()))
return Err(format!(
"Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в {} не меняет оборудование. Доступно on/off.",
role.key()
));
}
["wave", kind, rest @ ..] => {
let count = rest.first().and_then(|v| v.parse().ok()).unwrap_or(5u32).clamp(1, 80);
@@ -2380,6 +2501,12 @@ impl Mod for AirDef {
self.launch_wave(&mut out)?;
None
}
["preset", n] => {
// The wave screen's preset button for scripts: the same apply() the UI cycles.
let n = n.parse::<usize>().map_err(|_| "Номер готового состава: число".to_string())?;
self.wave.apply(n);
Some(format!("Готовый: {}", wave::PRESETS[self.wave.preset].name))
}
["sites"] => {
// The launch sites the radars have found, and the strike missiles (#101).
let p = player().ok_or("Нет игрока")?;
@@ -2535,6 +2662,14 @@ impl Mod for AirDef {
self.set_effects(*v != "off", *v == "hd");
Some(format!("Эффекты: {}", match *v { "off" => "выкл", "hd" => "HD", _ => "обычные" }))
}
["recon"] => {
// The enemy's partial picture and why it prices each mark: explicit debug, never the
// normal HUD (#135). The same lines fill the after-action review page.
for l in recon_view::picture_lines(&self.sim.enemy_picture()) {
say(&l);
}
None
}
["stats"] => Some(format!(
"В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}",
self.sim.drones.iter().filter(|d| d.alive()).count(),
@@ -2568,8 +2703,9 @@ mod tests {
assert_eq!(sim::catalog::UNITS[3].kind, SamKind::S400);
assert_eq!(sim::catalog::UNITS[4].kind, SamKind::S500);
assert_eq!(sim::catalog::UNITS[10].kind, SamKind::Radar);
for (key, _) in BATTERY_DEPLOY {
assert!(deploy_configuration(key).is_some());
for v in sim::catalog::VARIANTS {
let (actual, mode, role) = deploy_configuration(v.id).unwrap();
assert_eq!((actual, mode, role), (v.kind, v.mode, v.role));
}
for kind in SamKind::ALL {
let (actual, mode, role) = deploy_configuration(kind.key()).unwrap();
@@ -2581,6 +2717,25 @@ mod tests {
use super::*;
#[test]
fn radar_profile_survives_a_state_round_trip() {
let mut game = test_mod();
for role in [sim::battery::RadarRole::Search, sim::battery::RadarRole::Height, sim::battery::RadarRole::Engagement] {
let id = game.sim.id();
let mut radar = Sam::new(id, SamKind::Radar, DVec3::new(role as i32 as f64 * 10.0, 70.0, 0.0), 0.0);
radar.set_radar_role(role);
game.sim.sams.push(radar);
}
let saved = game.state_text(false, false);
assert!(saved.contains("radar_search") && saved.contains("radar_height") && saved.contains("radar_track"));
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
assert_eq!(
restored.sim.sams.iter().map(|s| s.radar_profile().id).collect::<Vec<_>>(),
vec!["radar_search", "radar_height", "radar_track"]
);
}
fn test_mod() -> AirDef {
AirDef {
sim: Sim::new(1),
@@ -2615,6 +2770,8 @@ mod tests {
model_generation: u32::MAX,
by_id: Vec::new(),
map: map::MapUi::default(),
overlay_held: false,
overlay_shown: false,
}
}
@@ -2725,6 +2882,75 @@ mod tests {
assert_eq!((after.sim.sams[0].air_48n6_stock, after.sim.sams[2].ground_stock, after.sim.sams[2].air_48n6_stock), (1, 0, 0));
}
/// #128 end to end: A declares a return and drives off, B waits for a round; the truck must
/// serve B anyway (a save/load mid-flight included), and once A is back the actual return
/// completes. Rounds are conserved throughout.
#[test]
fn a_moving_return_claim_drives_and_supplies_and_survives_a_state_round_trip() {
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();
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 120.0), (SamKind::S400, 240.0), (SamKind::Tzm, 0.0)] {
let id = game.sim.id();
game.sim.sams.push(Sam::new(id, kind, DVec3::new(x, 64.0, 0.0), 0.0));
}
game.sim.sams[0].ground_stock = 2;
game.sim.sams[1].ground_rounds = 1;
game.sim.sams[1].missiles = 3;
game.sim.unload_ground_round(1).unwrap();
assert!(game.sim.sams[1].ground_return);
game.sim.sams[2].missiles = 3;
// B is out of the depot's reach: the load becomes a pending delivery request.
game.sim.load_ground_round(2).unwrap();
assert!(game.sim.sams[2].ground_request);
// A drives away: its return claim is impossible for a while.
assert!(game.sim.order_move(1, DVec3::new(420.0, 64.0, 0.0)));
let mut out = Out::default();
let mut restored_mid_flight = false;
let mut supplied = false;
for _ in 0..12000 {
let now = game.sim.tick;
let cols = game.ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
game.ground.answer(cols, now);
let sections = game.ground.world.take_wanted(now);
game.ground.world.serve(&Flat, sections, now);
game.sim.step(&mut game.ground, None, &mut out);
if !restored_mid_flight && game.sim.sams[3].ground_stock == 1 {
// The truck took a round for B: save, reload, continue from the restored state.
let saved = game.state_text(false, false);
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
game = restored;
restored_mid_flight = true;
}
if game.sim.sams[2].ground_rounds == 1 { supplied = true; break; }
out = Out::default();
}
assert!(restored_mid_flight, "truck never picked up a round for B");
assert!(supplied, "B starved while A's return was impossible");
assert!(game.sim.sams[1].ground_return, "claim must survive the supply run");
assert_eq!(game.sim.sams[0].ground_stock + game.sim.sams[3].ground_stock + game.sim.sams[1].ground_rounds + game.sim.sams[2].ground_rounds, 3);
// A returns to its place; the waiting claim is then collected and driven to the depot.
assert!(game.sim.order_move(1, DVec3::new(120.0, 64.0, 0.0)));
let mut returned = false;
for _ in 0..12000 {
let now = game.sim.tick;
let cols = game.ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
game.ground.answer(cols, now);
let sections = game.ground.world.take_wanted(now);
game.ground.world.serve(&Flat, sections, now);
game.sim.step(&mut game.ground, None, &mut out);
if game.sim.sams[0].ground_stock == 2 && game.sim.sams[1].ground_rounds == 0 { returned = true; break; }
out = Out::default();
}
assert!(returned);
assert!(!game.sim.sams[1].ground_return);
assert!(!game.sim.sams[3].return_cargo);
assert_eq!(game.sim.sams[0].ground_stock + game.sim.sams[3].ground_stock + game.sim.sams[1].ground_rounds + game.sim.sams[2].ground_rounds, 3);
}
/// #83: while an export records no other replay or film replaces it; after it, they may.
#[test]
fn typed_ammunition_changes_mark_the_state_dirty() {
@@ -2865,4 +3091,57 @@ mod tests {
sim.strikes.progress = sim::strike::TUNE.progress_save;
assert_ne!(durable_mark(&sim), checkpoint, "a refill checkpoint is not saved");
}
/// #127: the air section of a save is written and read by the adapter, and a save without it (an
/// older one) still loads as before. The section itself is checked in the core's own tests; here
/// the contract is that the text the game writes is the text the next load restores, and that a
/// state with a sky replaces a state without one rather than merging into it.
#[test]
fn the_air_section_of_a_save_is_written_and_read_by_the_adapter() {
let zeros = "0 ".repeat(24);
let air = format!(
"air 1 120 2 0 1 1 1 1\n\
airintel {zeros}\n\
airglobal -\n\
airrelief 0 0 0 16 8 u64\n\
aircontact 32 s400 0 70 0 100 emission - - 0\n\
airqueue 200 48 shahed 0 90 -600 0 1 0 0 70 0 cruise react 32 120 0 confirmed 0 0 0 0 0 0 false false true 0 - 0 - -\n\
airjob 1 48 0 70 0 32 120 1 react 0\n"
);
let saved = format!("sam {} 0 70 300 0\n{air}", SamKind::S400.key());
let mut game = test_mod();
game.apply_state(&saved).expect("a saved raid must load");
assert_eq!(game.sim.tick, 120);
assert_eq!(game.sim.queue.len(), 1, "the launch queue is not restored");
assert_eq!(game.sim.queue[0].0, 200);
assert_eq!(game.sim.drones.len(), 0);
let report = game.sim.enemy_picture();
assert_eq!(report.pending.len(), 1, "the pending route job is not restored");
assert_eq!(report.pending[0].intent, "react");
assert_eq!(report.pending[0].unit, 32);
assert_eq!(report.contacts.len(), 1);
// The game writes the same section back: what it read is what it saves.
let back = game.state_text(false, false);
assert!(back.contains("\nair 1 120 2 0 1 1 1 1\n"), "{back}");
assert!(back.contains("\nairjob 1 48 0.00 70.00 0.00 32 120 1 react 0\n"), "{back}");
assert!(back.contains("\nairqueue 200 48 "), "{back}");
// The air state is replaced, not merged: a save of a quiet world clears the sky.
let quiet = format!("sam {} 0 70 300 0\n", SamKind::S400.key());
let quiet = format!("{quiet}air 1 300 2 0 0 0 0 0\nairintel {zeros}\nairglobal -\n");
game.apply_state(&quiet).unwrap();
assert!(game.sim.queue.is_empty() && game.sim.enemy_picture().pending.is_empty(), "an empty sky merged with the loaded one");
// An older save has no section at all: it loads its layout and leaves the sky as it was.
let mut old = test_mod();
old.apply_state(&format!("sam {} 0 70 0 0\n", SamKind::S400.key())).unwrap();
assert_eq!(old.sim.sams.len(), 1);
assert!(sim::Sim::parse_air("sam s400 0 70 0 0\n").unwrap().is_none());
// A scenario's body is a start state: it does not carry the sky.
let scenario = game.scenario_text("t", false);
assert!(!scenario.contains("\nair 1 "), "a scenario carries the air state");
assert!(sim::Sim::parse_air(&scenario).unwrap().is_none());
}
}
+591 -81
View File
@@ -7,7 +7,7 @@
//! comes from the game as tiles (`render::TerrainShape`): the mod only says which, and the game scans the
//! loaded chunks within a budget; land it hasn't got is drawn as unknown.
use crate::panel::distance;
use crate::sim::{self, Class, LowSensor, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
use crate::sim::{self, Class, Drone, LowSensor, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
use crate::{AirDef, say};
use glam::DVec3;
use horizon_mod_sdk::render::{self, CanvasEvent, FillShape, Point, QuadShape, Rect, Shape, TerrainShape, TextShape};
@@ -27,15 +27,23 @@ const F_TINT: usize = 8;
/// Classes of systems for the filter: missile systems, guns, radars, the rear.
const SYS_CLASSES: [&str; 4] = ["ЗРК", "ЗАК", "РЛС", "тыл"];
/// Classes of the network's targets, by the speed of the track (the network doesn't know what a target is).
/// Classes of the network's targets: the class the tracks were *estimated* (#133), not what the
/// targets are; the unidentified are always shown — they cannot be filtered by a class they don't have yet.
const TGT_CLASSES: [&str; 5] = ["Д", "Г", "К", "С", "Б"];
/// Speed (blocks a tick) below which a track is of the class: drones, jets, cruise, supersonic, the rest ballistic.
const TGT_SPEED: [f64; 4] = [0.8, 1.8, 3.0, 6.5];
/// Whether the track passes the class filter: its estimated class is switched on, or it has none yet.
fn tclass_shown(t: &Track, on: &[bool; 5]) -> bool {
t.class.class().is_none_or(|c| on[c as usize])
}
/// A label line's height, pixels the markers merge within, how far from the pointer labels are kept at
/// a low zoom, and the most labels at once.
const LH: f32 = 9.0;
const CLUSTER_R: f32 = 9.0;
/// Tracks merge within this many pixels: their markers are bigger than the systems' (#132).
const TRACK_CLUSTER_R: f32 = 11.0;
/// A track marker's half-size, and the room its label keeps clear of it.
const TRACK_R: f32 = 6.0;
const MAX_LABELS: usize = 70;
/// Ticks a radar's computed coverage edge lives, and how many are recomputed in a redraw.
const RIM_REFRESH: u64 = 100;
@@ -121,6 +129,15 @@ enum Act {
SaveScn,
LoadScn(usize),
ScnPage(i32),
/// Switches the map between the network's data and the sandbox's truth (#132).
Truth,
}
/// What the pointer hovers: a network track, or a true drone in the truth mode.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Hover {
Track(u32),
Drone(u32),
}
/// A system in the draft layout: an existing one (by id) or one to be built.
@@ -222,7 +239,11 @@ pub struct MapUi {
blocked: Vec<[f32; 4]>,
widths: HashMap<String, f32>,
trails: HashMap<u32, Vec<(f32, f32)>>,
/// The true places sampled while the sandbox's truth mode is on (#132), apart from the network's.
truth_trails: HashMap<u32, Vec<(f32, f32)>>,
seen: HashMap<u32, u64>,
/// When a true drone was last seen, kept apart from the network's `seen` (#132).
truth_seen: HashMap<u32, u64>,
sampled: u64,
draft: Draft,
history: Vec<Draft>,
@@ -273,7 +294,9 @@ impl Default for MapUi {
blocked: Vec::new(),
widths: HashMap::new(),
trails: HashMap::new(),
truth_trails: HashMap::new(),
seen: HashMap::new(),
truth_seen: HashMap::new(),
sampled: 0,
draft: Draft::default(),
history: Vec::new(),
@@ -350,7 +373,9 @@ impl MapUi {
pub fn sample(&mut self, sim: &Sim) {
if sim.tick < self.sampled {
self.trails.clear();
self.truth_trails.clear();
self.seen.clear();
self.truth_seen.clear();
}
if sim.tick < self.sampled + SAMPLE {
return;
@@ -371,10 +396,27 @@ impl MapUi {
}
self.seen.insert(id, sim.tick);
}
// The truth mode keeps its own trail of the real places, never mixed into the network's (#132).
if sim.truth {
for d in sim.drones.iter().filter(|d| d.alive()) {
let trail = self.truth_trails.entry(d.id).or_default();
let p = (d.pos.x as f32, d.pos.z as f32);
if trail.last().is_none_or(|l| (l.0 - p.0).hypot(l.1 - p.1) > 4.0) {
trail.push(p);
if trail.len() > TRAIL_POINTS {
trail.remove(0);
}
}
self.truth_seen.insert(d.id, sim.tick);
}
}
let now = sim.tick;
self.seen.retain(|_, t| now.saturating_sub(*t) < 1200);
self.truth_seen.retain(|_, t| now.saturating_sub(*t) < 1200);
let seen = &self.seen;
self.trails.retain(|id, _| seen.contains_key(id));
let truth_seen = &self.truth_seen;
self.truth_trails.retain(|id, _| truth_seen.contains_key(id));
}
fn enter_editor(&mut self) {
@@ -423,7 +465,7 @@ impl MapUi {
fn sys_class(k: SamKind) -> usize {
if k.armed() {
if k == SamKind::Gepard { 1 } else { 0 }
} else if k.spec().sensor > 0.0 {
} else if k == SamKind::Optical || k.spec().sensor > 0.0 {
2
} else {
3
@@ -438,6 +480,7 @@ fn short_name(k: SamKind) -> &'static str {
SamKind::Tzm => "ТЗМ",
SamKind::Ew => "РЭБ",
SamKind::Light => "Прож.",
SamKind::Optical => "Опт.",
SamKind::Pantsir => "Панцирь",
SamKind::IrisT => "IRIS-T",
SamKind::S400 => "С-400",
@@ -449,14 +492,8 @@ fn short_name(k: SamKind) -> &'static str {
}
}
/// The class of a track by its speed.
fn tgt_class(t: &Track) -> usize {
let v = t.vel.length();
TGT_SPEED.iter().position(|&m| v < m).unwrap_or(TGT_SPEED.len())
}
/// Markers within `r` pixels of the first of a group go with it: the groups, as indices into `pos`.
fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
pub(crate) fn group(pos: &[(f32, f32)], r: f32) -> Vec<Vec<usize>> {
let r2 = r * r;
let mut g: Vec<Vec<usize>> = Vec::new();
'next: for (i, p) in pos.iter().enumerate() {
@@ -567,6 +604,279 @@ fn class_name(c: sim::sites::SiteClass) -> &'static str {
}
}
/// What the pointer is over, in the view: a network track, or a true drone while the sandbox's truth mode is on.
/// The network's tracks come from `Sim::picture` only; a drone the network has not measured is not hoverable
/// outside the truth mode (#132). Panels and cards take the pointer first.
fn hover_at(sim: &Sim, ui: &MapUi) -> Option<Hover> {
let p = ui.cursor;
if ui.blocked.iter().any(|r| p.0 >= r[0] && p.1 >= r[1] && p.0 <= r[0] + r[2] && p.1 <= r[1] + r[3]) {
return None;
}
let near = PICK_R + 2.0;
let mut best: Option<(f32, Hover)> = None;
if ui.filters[F_TRACKS] {
let now = sim.tick;
for (id, t) in sim.picture() {
if !tclass_shown(&t, &ui.tclass) {
continue;
}
let e = t.est(now);
let c = ui.to_screen(e.x, e.z);
if !ui.on_screen(c, 6.0) {
continue;
}
let d = (c.0 - p.0).hypot(c.1 - p.1);
if d <= near && best.is_none_or(|b| d < b.0) {
best = Some((d, Hover::Track(id)));
}
}
}
// The true place wins over its own track: the mode is explicit and the card says so.
if sim.truth {
for d in sim.drones.iter().filter(|d| d.alive()) {
let c = ui.to_screen(d.pos.x, d.pos.z);
if !ui.on_screen(c, 6.0) {
continue;
}
let dist = (c.0 - p.0).hypot(c.1 - p.1);
if dist <= near && best.is_none_or(|b| dist <= b.0 + 0.5) {
best = Some((dist, Hover::Drone(d.id)));
}
}
}
best.map(|b| b.1)
}
/// The network's knowledge of one track: type, status, source, distance, speed, whatever holds or intercepts it.
/// The target and the route are never known to the network unless the sandbox's truth mode adds them (#132).
fn track_lines(sim: &Sim, t: &Track, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
let now = sim.tick;
let age = t.age(now);
let forecast = t.forecast(now);
lines.push((format!("Трек №{} · {}", t.id, t.class.name()), RED));
lines.push((
format!("Статус: {}{}", t.ident().name(), if forecast { format!(" · прогноз {} с", age / 20) } else { format!(" · измерение {} с назад", age / 20) }),
if forecast { YELLOW } else { GREEN },
));
let source = sim.sams.iter().enumerate().find(|(_, s)| s.id == t.source).map_or(
if t.source == 0 { "неизвестен".to_string() } else { format!("№? ({})", t.source) },
|(n, s)| format!("№{} {} ({})", n + 1, s.kind.name(), s.radar_profile().id),
);
lines.push((format!("Источник: {} · измерил {}", if t.own_within(now, t.ttl as u64) { "своя РЛС" } else { "сеть (чужое измерение)" }, source), WHITE));
lines.push((format!("Продукт: {} · качество {}%", t.product.name(), t.quality), WHITE));
let authority = if t.own_authorizes(now) {
"у измерившей станции пригодно для пуска".to_string()
} else if t.own_tick > 0 {
format!("измерение станции {} с назад, для пуска не пригодно", now.saturating_sub(t.own_tick) / 20)
} else {
"передано сетью: собственного измерения нет, нужен огневой трек станции".to_string()
};
lines.push((format!("Пуск: {authority}"), if t.own_authorizes(now) { GREEN } else { YELLOW }));
if t.locked {
lines.push(("Огневой захват: да".into(), YELLOW));
}
let e = t.est(now);
if let Some(p) = player {
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(e.distance(p)), e.y), WHITE));
}
lines.push((
format!("Скорость: {:.0} км/ч · погрешность места {}", t.vel.length() * 20.0 * 3.6, distance(t.uncertainty(now))),
WHITE,
));
let missiles = sim.missiles.iter().filter(|m| m.target() == t.id).count();
lines.push((
if missiles > 0 { format!("Перехват: {missiles} ракет в полёте") } else { "Перехват: ракет нет".into() },
if missiles > 0 { GREEN } else { GREY },
));
let who = who_tracks(sim, t);
if !who.is_empty() {
lines.push((format!("Держат: {who}"), WHITE));
}
}
/// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's).
fn who_tracks(sim: &Sim, t: &Track) -> String {
let n = sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count();
if n == 0 { String::new() } else { format!("{n} комплексов") }
}
/// What a true drone is aimed at, in the sandbox's words: a unit, a marked object, or a bare point (#132).
fn aim_text(sim: &Sim, d: &Drone) -> String {
let unit = d.aim_unit();
if unit != 0 {
return match sim.sams.iter().position(|s| s.id == unit) {
Some(i) => format!("{} №{}", sim.sams[i].kind.name(), i + 1),
None => format!("комплекс №{unit}"),
};
}
let aim = d.aim_pos();
match sim.targets.iter().position(|p| p.distance(aim) < 8.0) {
Some(i) => format!("объект №{}", i + 1),
None => format!("точка {:.0} {:.0}", aim.x, aim.z),
}
}
/// The truth's lines for one drone: what it is, whether the network holds it, where it goes, what it is sent at,
/// and who is shooting at it. Only the sandbox's truth mode asks for these (#132).
fn truth_lines(sim: &Sim, d: &Drone, player: Option<DVec3>, lines: &mut Vec<(String, u32)>) {
let tracked = sim.picture().contains_key(&d.id);
lines.push((format!("ИСТИНА · {} ({}) №{}", d.kind.spec().name, d.kind.spec().class.name(), d.id), YELLOW));
lines.push((
format!("Статус: {}{}", if d.jammed { "в воздухе, навигация подавлена" } else { "в воздухе" }, if tracked { ", в картине сети" } else { ", вне картины сети" }),
if tracked { WHITE } else { ORANGE },
));
if d.kind.spec().decoy {
lines.push(("Ложная цель: без боевой части".into(), GREY));
}
if let Some(p) = player {
lines.push((format!("Дистанция: {} · высота {:.0} м", distance(d.pos.distance(p)), d.pos.y), WHITE));
}
lines.push((format!("Скорость: {:.0} км/ч", d.vel.length() * 20.0 * 3.6), WHITE));
lines.push((format!("Цель: {}", aim_text(sim, d)), YELLOW));
let route = d.route();
if route.is_empty() {
lines.push(("Маршрут: прямо на цель".into(), YELLOW));
} else {
lines.push((format!("Маршрут: {} точек, следующая через {}", route.len(), distance(d.pos.distance(route[0]))), YELLOW));
}
let aim = d.aim_pos();
let speed = d.vel.length().max(0.001);
lines.push((format!("До цели: {} (~{:.0} с)", distance(d.pos.distance(aim)), d.pos.distance(aim) / speed / 20.0), WHITE));
let missiles = sim.missiles.iter().filter(|m| m.target() == d.id).count();
lines.push((
if missiles > 0 || d.engaged > 0 {
format!("Перехват: {missiles} ракет в полёте, наведено {}", d.engaged)
} else {
"Перехват: никто не ведёт".into()
},
if missiles > 0 || d.engaged > 0 { GREEN } else { GREY },
));
}
/// The truth layer: the real drones as white frames, their sampled path, the route and aim ahead in yellow, marked
/// apart from the network's red tracks. Drawn only while the sandbox's truth mode is on (#132).
fn map_truth(sim: &Sim, ui: &mut MapUi, hover: Option<Hover>, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
for d in sim.drones.iter().filter(|d| d.alive()) {
let c = ui.to_screen(d.pos.x, d.pos.z);
if ui.filters[F_TRAILS]
&& let Some(trail) = ui.truth_trails.get(&d.id)
{
let mut prev: Option<(f32, f32)> = None;
for p in trail {
let q = ui.to_screen(p.0 as f64, p.1 as f64);
if let Some(a) = prev
&& (ui.on_screen(a, 0.0) || ui.on_screen(q, 0.0))
{
s.push(line(a, q, 1.4, alpha(WHITE, 0.45)));
}
prev = Some(q);
}
}
if !ui.on_screen(c, 20.0) {
continue;
}
// The way ahead: the route's points, then the aim. Dashes, because a plan is not a measurement.
let aim = ui.to_screen(d.aim_pos().x, d.aim_pos().z);
let mut prev = c;
for p in d.route().iter().map(|p| ui.to_screen(p.x, p.z)).chain(std::iter::once(aim)) {
if ui.on_screen(prev, 0.0) || ui.on_screen(p, 0.0) {
route_dashed(s, prev, p, alpha(0xFFE070, 0.55));
}
prev = p;
}
// The drone: a white frame, never the network's red diamond. A recon aircraft has a
// sign of its own: an amber diamond, not the strike's frame (#135).
let recon = sim.is_recon_drone(d.id);
if recon {
let p = [(c.0, c.1 - 5.0), (c.0 + 5.0, c.1), (c.0, c.1 + 5.0), (c.0 - 5.0, c.1)];
for i in 0..4 {
s.push(line(p[i], p[(i + 1) % 4], 1.2, alpha(0xFFC040, 0.95)));
}
} else {
s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95)));
}
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, if recon { alpha(0xFFC040, 0.95) } else { WHITE }));
if ui.on_screen(aim, 6.0) {
s.push(diamond(aim.0, aim.1, 4.5, alpha(0xFFE070, 0.85)));
s.push(fill(aim.0 - 1.0, aim.1 - 1.0, 2.0, 2.0, alpha(0xFFE070, 0.9)));
}
taken.push([c.0 - 6.0, c.1 - 6.0, 12.0, 12.0]);
let chosen = hover == Some(Hover::Drone(d.id));
let name = if recon { format!("разведчик №{}", d.id) } else { format!("{} №{}", d.kind.spec().name, d.id) };
add_lab(ui, labs, name, c, 7.0, alpha(YELLOW, 0.95), chosen);
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
/// The hover card: beside the pointer, over the picture. A network track's card never claims its target or route;
/// in the truth mode the true drone's card adds the route, the aim and the interception (#132).
fn hover_card(sim: &Sim, ui: &mut MapUi, h: Hover, player: Option<DVec3>, out: &mut Vec<Shape>, taken: &mut Vec<[f32; 4]>) {
let mut lines: Vec<(String, u32)> = Vec::new();
let border;
match h {
Hover::Track(id) => {
let pic = sim.picture();
let Some(t) = pic.get(&id) else { return };
border = RED;
track_lines(sim, t, player, &mut lines);
lines.push(("Цель и маршрут сети неизвестны".into(), GREY));
if sim.truth && let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) {
lines.push(("Истина (песочница):".into(), YELLOW));
lines.push((format!("Тип: {} · {}", d.kind.spec().name, aim_text(sim, d)), YELLOW));
}
}
Hover::Drone(id) => {
let Some(d) = sim.drones.iter().find(|d| d.id == id && d.alive()) else { return };
border = YELLOW;
truth_lines(sim, d, player, &mut lines);
lines.push(("Жёлтый пунктир — маршрут и цель; белые рамки — истина.".into(), GREY));
}
}
if lines.is_empty() {
return;
}
let (w, h) = ui.size;
let card_w = 250.0f32.min(w - 16.0);
let lines = wrap_lines(ui, lines, card_w);
let lh = (11.0 * ui.u).round();
let total = lines.len() as f32 * lh + 8.0;
let mut x = ui.cursor.0 + 14.0;
if x + card_w + 4.0 > w {
x = ui.cursor.0 - card_w - 14.0;
}
let x = x.clamp(4.0, (w - card_w - 4.0).max(4.0));
let y = (ui.cursor.1 - 10.0).clamp(4.0, (h - total - 4.0).max(4.0));
out.push(fill(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 0xE8101814));
out.extend(frame(x - 3.0, y - 3.0, card_w + 6.0, total + 6.0, 1.0, border));
let mut ty = y;
for (l, c) in &lines {
out.push(text(l.as_str(), x + 2.0, ty, *c));
ty += lh;
}
taken.push([x - 3.0, y - 3.0, card_w + 6.0, total + 6.0]);
}
/// Long lines broken at the card's width.
fn wrap_lines(ui: &mut MapUi, lines: Vec<(String, u32)>, width: f32) -> Vec<(String, u32)> {
let mut wrapped: Vec<(String, u32)> = Vec::new();
for (l, c) in lines {
let mut cur = String::new();
for word in l.split(' ') {
let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
if ui.tw(&try_) > width - 8.0 && !cur.is_empty() {
wrapped.push((std::mem::take(&mut cur), c));
cur = word.to_string();
} else {
cur = try_;
}
}
wrapped.push((cur, c));
}
wrapped
}
impl AirDef {
/// Opens the map (the key, or the menu).
pub(crate) fn map_toggle(&mut self) {
@@ -810,6 +1120,7 @@ impl AirDef {
"key.keyboard.r" if ui.mode == Mode::Editor => self.map_act(ui, Act::Rotate),
"key.keyboard.delete" | "key.keyboard.backspace" if ui.mode == Mode::Editor => self.map_act(ui, Act::Delete),
"key.keyboard.f" => self.map_act(ui, Act::Follow),
"key.keyboard.t" => self.map_act(ui, Act::Truth),
k if k.len() == 14 && k.starts_with("key.keyboard.") && k.as_bytes()[13].is_ascii_digit() && k.as_bytes()[13] != b'0' => {
let n = (k.as_bytes()[13] - b'1') as usize;
if n < FILTERS.len() {
@@ -915,6 +1226,8 @@ impl AirDef {
ui.pick = Pick::None;
ui.ed_sel = None;
ui.trails.clear();
ui.truth_trails.clear();
ui.truth_seen.clear();
ui.rims.clear();
ui.note(tick, m);
}
@@ -929,6 +1242,17 @@ impl AirDef {
}
}
Act::Filter(i) => ui.filters[i] = !ui.filters[i],
Act::Truth => {
self.sim.truth = !self.sim.truth;
// The two pictures are kept apart: a mode switch starts its trails afresh (#132).
ui.truth_trails.clear();
ui.truth_seen.clear();
ui.note(tick, if self.sim.truth {
"Режим ИСТИНА (песочница): настоящие дроны, их цели и маршруты. Треки сети остаются на карте."
} else {
"Режим данных сети РЛС: только то, что засекли радары."
});
}
Act::Close => {
ui.close = true;
}
@@ -1115,7 +1439,7 @@ impl AirDef {
let pic = self.sim.picture();
let mut best: Option<(f32, u32)> = None;
for (id, t) in &pic {
if !ui.tclass[tgt_class(t)] {
if !tclass_shown(t, &ui.tclass) {
continue;
}
let e = t.est(now);
@@ -1363,9 +1687,16 @@ impl AirDef {
// The panels first: the labels keep clear of them. They are drawn last, over the picture.
let mut panels: Vec<Shape> = Vec::with_capacity(400);
self.map_panels(ui, &mut panels, &draft);
// The hover card (#132): beside the pointer, over the picture; the labels keep clear of it too.
let hover = if !editing && ui.drag.is_none() { hover_at(&self.sim, ui) } else { None };
let mut hover_taken: Vec<[f32; 4]> = Vec::new();
if let Some(h) = hover {
hover_card(&self.sim, ui, h, crate::player().map(|p| DVec3::new(p.x, p.y, p.z)), &mut panels, &mut hover_taken);
}
let mut s: Vec<Shape> = Vec::with_capacity(2048);
let mut labs: Vec<Lab> = Vec::new();
let mut taken: Vec<[f32; 4]> = ui.blocked.clone();
taken.extend(hover_taken);
// Terrain.
if ui.filters[F_TERRAIN] {
self.map_terrain(ui, &mut s);
@@ -1458,14 +1789,13 @@ impl AirDef {
if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] {
self.map_tracks(ui, &mut s, &mut labs, &mut taken);
}
// The truth, when the sandbox shows it, marked as such.
// The optical posts and the contacts they watch (#136): a line to a contact last seen in clear sight.
if ui.filters[F_SAMS] || ui.filters[F_TRACKS] {
self.map_optical(ui, &mut s, &mut labs);
}
// The truth, when the sandbox shows it, marked as such: the real drones, their routes and aims.
if self.sim.truth {
for d in &self.sim.drones {
let c = ui.to_screen(d.pos.x, d.pos.z);
if ui.on_screen(c, 4.0) {
s.extend(frame(c.0 - 3.0, c.1 - 3.0, 6.0, 6.0, 1.0, alpha(0xFF4040, 0.9)));
}
}
map_truth(&self.sim, ui, hover, &mut s, &mut labs, &mut taken);
}
// The ghost under the pointer while placing.
if editing && let Some(y) = self.ground_y(cur_world.0, cur_world.1) {
@@ -1587,6 +1917,51 @@ impl AirDef {
}
}
/// The optical posts (#136): a short status by each, and a line to the contact it has in clear
/// sight (or last saw), never to a radar's measurement. At most a screenful, so a crowd stays cheap.
fn map_optical(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>) {
let now = self.sim.tick;
let picture = self.sim.picture();
let mut drawn = 0usize;
for (i, sam) in self.sim.sams.iter().enumerate().filter(|(_, sam)| sam.kind == SamKind::Optical && sam.alive()) {
if drawn >= 16 {
break;
}
let c = ui.to_screen(sam.pos.x, sam.pos.z);
if !ui.on_screen(c, 30.0) {
continue;
}
drawn += 1;
let Some(report) = self.sim.optical_report(sam.id) else { continue };
let chosen = ui.sel == Some(Sel::Sam(sam.id));
let color = match report.state {
sim::OpticalState::Observing => GREEN,
sim::OpticalState::Holding => CYAN,
sim::OpticalState::NoSight => ORANGE,
sim::OpticalState::Searching => GREY,
};
add_lab(ui, labs, format!("Опт. №{}: {}", i + 1, report.status()), c, 7.0, alpha(color, 0.95), chosen);
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
// The contact it watches: its own last clear sighting, else the network cue's forecast.
let own = report.seen.is_some();
let point = report
.seen
.or_else(|| report.target.and_then(|id| picture.get(&id).map(|t| t.est(now))));
if let Some(p) = point {
let pc = ui.to_screen(p.x, p.z);
s.push(line(c, pc, 1.0, alpha(color, if chosen { 0.9 } else if own { 0.55 } else { 0.3 })));
let label = match (own, report.observation) {
(true, Some(o)) => format!("вероятно {} · {:.0}%", o.class.name(), (1.0 - o.uncertainty) * 100.0),
(true, None) => "контакт в поле зрения".into(),
(false, _) => "цель по подсказке".into(),
};
add_lab(ui, labs, label, pc, 5.0, alpha(color, 0.95), chosen);
}
}
}
/// The radars' coverage edges. A radar's edge is where the land first hides a low flyer along each ray round it;
/// each is worked out from the sim's own horizon (`low_rim`), a few a redraw, and kept a while. The selected
/// one shows its dead zones filled.
@@ -1922,21 +2297,21 @@ impl AirDef {
fn map_tracks(&self, ui: &mut MapUi, s: &mut Vec<Shape>, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let now = self.sim.tick;
let pic = self.sim.picture();
// Only the classes asked for (the selected one always).
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| ui.tclass[tgt_class(t)] || ui.sel == Some(Sel::Track(**id))).collect();
// Only the classes asked for (the selected one and the unidentified always).
let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| tclass_shown(t, &ui.tclass) || ui.sel == Some(Sel::Track(**id))).collect();
for (id, t) in &shown {
let chosen = ui.sel == Some(Sel::Track(**id));
if ui.filters[F_TRAILS]
&& let Some(trail) = ui.trails.get(*id)
{
let col = alpha(0xFF6060, if chosen { 0.95 } else { 0.5 });
let col = alpha(0xFF6060, if chosen { 1.0 } else { 0.7 });
let mut prev: Option<(f32, f32)> = None;
for p in trail {
let c = ui.to_screen(p.0 as f64, p.1 as f64);
if let Some(a) = prev
&& (ui.on_screen(a, 0.0) || ui.on_screen(c, 0.0))
{
s.push(line(a, c, 1.0, col));
s.push(line(a, c, if chosen { 2.2 } else { 1.6 }, col));
}
prev = Some(c);
}
@@ -1950,7 +2325,7 @@ impl AirDef {
let m = ui.to_screen(t.pos.x, t.pos.z);
// The last measurement and the forecast from it: dashes, never drawn as a certainty.
if forecast {
s.push(line(m, c, 1.0, alpha(0xFFB0B0, 0.4)));
s.push(line(m, c, 1.4, alpha(0xFFB0B0, 0.45)));
let r = (t.uncertainty(now) * ui.scale) as f32;
ring(ui, s, c, r.min(300.0), 1.0, alpha(0xFFB0B0, 0.5));
}
@@ -1958,7 +2333,7 @@ impl AirDef {
// Ahead along the course for 30 s, dashed.
let v = t.vel;
let ahead = ui.to_screen(e.x + v.x * 600.0, e.z + v.z * 600.0);
dashed(s, c, ahead, alpha(0xFF8080, 0.8));
dashed(s, c, ahead, 1.5, alpha(0xFF8080, 0.85));
}
}
if !ui.filters[F_TRACKS] {
@@ -1974,7 +2349,7 @@ impl AirDef {
.collect();
let pos: Vec<(f32, f32)> = vis.iter().map(|v| v.2).collect();
let solo: Vec<bool> = vis.iter().map(|v| ui.sel == Some(Sel::Track(v.0))).collect();
for grp in groups_of(&pos, &solo, CLUSTER_R * 0.8, true) {
for grp in groups_of(&pos, &solo, TRACK_CLUSTER_R, true) {
if grp.len() > 1 {
let members: Vec<(f32, f32)> = grp.iter().map(|&k| vis[k].2).collect();
draw_cluster(ui, s, taken, &members, RED);
@@ -1984,16 +2359,36 @@ impl AirDef {
let chosen = ui.sel == Some(Sel::Track(id));
let forecast = t.forecast(now);
let age = t.age(now);
let col = if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
s.push(diamond(c.0, c.1, 4.0, col));
if !forecast {
s.push(diamond(c.0, c.1, 2.0, 0xFF200808));
// A recon aircraft is a role of its own: a yellow hollow diamond and a named label, so
// the player tells it from a strike drone the network tracks the same way (#135).
let recon = sim::is_drone_id(id);
let r = if recon { 5.0 } else { TRACK_R };
let col = if recon { YELLOW } else if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
s.push(diamond(c.0, c.1, r, col));
if recon || !forecast {
s.push(diamond(c.0, c.1, if recon { 2.0 } else { 3.0 }, 0xFF200808));
}
taken.push([c.0 - 5.0, c.1 - 5.0, 10.0, 10.0]);
let txt = format!("{}{}", if forecast { "~" } else { "" }, if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) });
add_lab(ui, labs, txt, c, 5.0, col, chosen);
// Its measured course, a tick out of the marker.
let v = t.vel.normalize_or_zero();
if v != DVec3::ZERO {
s.push(line(c, (c.0 + v.x as f32 * 10.0, c.1 + v.z as f32 * 10.0), 1.5, col));
}
taken.push([c.0 - r - 1.0, c.1 - r - 1.0, r * 2.0 + 2.0, r * 2.0 + 2.0]);
let age_txt = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) };
let txt = if recon {
format!("разведчик {age_txt}")
} else {
let mark = t.class.mark();
match (mark.is_empty(), forecast) {
(true, true) => format!("~{age_txt}"),
(true, false) => age_txt,
(false, true) => format!("{mark} ~{age_txt}"),
(false, false) => format!("{mark} {age_txt}"),
}
};
add_lab(ui, labs, txt, c, r + 1.0, col, chosen);
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN));
}
}
}
@@ -2018,7 +2413,7 @@ impl AirDef {
};
let tail_w = ui.tw(&tail);
let heads: [&str; 2] = if self.sim.truth {
["КАРТА · ИСТИНА (песочница): красные рамки — настоящие дроны", "КАРТА · ИСТИНА"]
["КАРТА · ИСТИНА (песочница): белые рамки — дроны, жёлтое — их цели и маршруты", "КАРТА · ИСТИНА (песочница)"]
} else {
["КАРТА · режим: данные сети РЛС", "КАРТА · сеть РЛС"]
};
@@ -2069,9 +2464,14 @@ impl AirDef {
for x in &self.sim.sams {
sc[sys_class(x.kind)] += 1;
}
// By the estimated class; the unidentified are counted apart.
let mut tc = [0usize; 5];
let mut unknown = 0usize;
for t in self.sim.picture().values() {
tc[tgt_class(t)] += 1;
match t.class.class() {
Some(c) => tc[c as usize] += 1,
None => unknown += 1,
}
}
inner.push(text("Системы по классу", x0, y, GREY));
y += lh;
@@ -2086,7 +2486,7 @@ impl AirDef {
x += draw_btn(ui, &mut inner, &label, Act::SysClass(i), ui.sclass[i], x, y, bh);
}
y += bh + 6.0;
inner.push(text("Цели сети по скорости", x0, y, GREY));
inner.push(text("Цели сети по классу", x0, y, GREY));
y += lh;
x = x0;
for i in 0..TGT_CLASSES.len() {
@@ -2098,11 +2498,16 @@ impl AirDef {
}
x += draw_btn(ui, &mut inner, &label, Act::TgtClass(i), ui.tclass[i], x, y, bh);
}
// The unidentified: a count, not a filter (they are always shown).
inner.push(text(format!("? {unknown} (не опознано)"), x, y + 2.0, GREY));
y += bh + 5.0;
for l in ["ЗРК ракеты · ЗАК пушки · тыл", "Д дроны · Г реактивные · К крылатые", "С сверхзвук · Б баллистика"] {
inner.push(text(l, x0, y, GREY));
y += lh - 1.0;
}
let rn = self.sim.picture().values().filter(|t| sim::is_drone_id(t.id)).count();
inner.push(text(format!("жёлтый ромб — разведчик ({rn})"), x0, y, GREY));
y += lh - 1.0;
}
_ => {
inner.push(text("Имя сценария", x0, y, GREY));
@@ -2151,7 +2556,7 @@ impl AirDef {
y += 6.0;
// The mode buttons, in rows that wrap.
let mut bx = x0 - 2.0;
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
for (label, act, on) in [("Правка (E)", Act::Editor, editing), ("Истина (T)", Act::Truth, self.sim.truth), ("Игрок (C)", Act::Player, false), ("Выход (M)", Act::Close, false)] {
let bw = ui.tw(label) + 10.0;
if bx + bw > lw + 2.0 {
bx = x0 - 2.0;
@@ -2169,7 +2574,7 @@ impl AirDef {
let helps: [&str; 3] = if editing {
["ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc", "ЛКМ ставить · ПКМ убрать · Enter · Esc", "Enter · Esc"]
} else {
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · ПКМ: марш · Esc", "ЛКМ выбор · колесо масштаб · Esc", "Esc"]
["ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · T: данные · Esc", "ЛКМ выбор · колесо масштаб · T данные · Esc", "Esc"]
};
for help in helps {
let hw = ui.tw(help);
@@ -2204,21 +2609,7 @@ impl AirDef {
self.sel_card(ui, &mut lines, &mut btns);
}
// Long lines break at the card's width.
let mut wrapped: Vec<(String, u32)> = Vec::new();
for (l, c) in lines {
let mut cur = String::new();
for word in l.split(' ') {
let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
if ui.tw(&try_) > card_w - 8.0 && !cur.is_empty() {
wrapped.push((std::mem::take(&mut cur), c));
cur = word.to_string();
} else {
cur = try_;
}
}
wrapped.push((cur, c));
}
let lines = wrapped;
let lines = wrap_lines(ui, lines, card_w);
if !lines.is_empty() || !btns.is_empty() {
let mut y = top;
let ch = lines.len() as f32 * lh + 10.0;
@@ -2311,7 +2702,14 @@ impl AirDef {
lines.push((if bare == 0 { "Все объекты в зоне поражения".into() } else { format!("Без прикрытия: объектов {bare} (красные)") }, if bare == 0 { GREEN } else { RED }));
lines.push(("Зелёное: зона огня, тёмное: дыра".into(), GREY));
match ui.pick {
Pick::Sam(k) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)),
Pick::Sam(k) => {
let reach = if k == SamKind::Optical {
format!("оптика {}", distance(sim::OPTICAL_RANGE))
} else {
format!("дальность {}", distance(k.range()))
};
lines.push((format!("В руке: {}, {reach}", k.name()), YELLOW));
}
Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
}
@@ -2330,7 +2728,11 @@ impl AirDef {
let k = sam.kind;
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
if k == SamKind::Radar {
lines.push((format!("Роль РЛС: {}", crate::battery_view::radar_role_name(sam.radar_role)), WHITE));
let profile = sam.radar_profile();
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
lines.push((format!("Ограничение: {}", profile.limit), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY));
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
}
@@ -2338,7 +2740,19 @@ impl AirDef {
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
}
lines.push((sam.status(), WHITE));
lines.push((crate::battery_view::sam_status(sam), WHITE));
if k == SamKind::Optical
&& let Some(r) = self.sim.optical_report(sam.id)
{
lines.push((r.line(), WHITE));
if let Some(o) = r.observation {
lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE));
}
lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY));
if r.target.is_some() {
lines.push(("Выбранный контакт показан линией".into(), GREY));
}
}
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
if k == SamKind::Depot {
lines.push((format!("Ударные RM48U: {} · снятые 48Н6: {}", sam.ground_stock, sam.air_48n6_stock), WHITE));
@@ -2434,24 +2848,17 @@ impl AirDef {
lines.push((format!("Трек №{id}: потерян сетью"), GREY));
return;
};
lines.push((format!("Трек сети №{id}"), 0xFFFF8080));
lines.push((format!("Опознание: {}", t.ident().name()), WHITE));
let age = t.age(now);
lines.push((
if t.forecast(now) { format!("ПРОГНОЗ: последнее измерение {} с назад", age / 20) } else { format!("Измерение {} с назад", age / 20) },
if t.forecast(now) { YELLOW } else { GREEN },
));
lines.push((format!("Высота {:.0} м, скорость {:.0} км/ч", t.pos.y, t.vel.length() * 20.0 * 3.6), WHITE));
lines.push((format!("Погрешность места до {}", distance(t.uncertainty(now))), GREY));
lines.push(("Цель и маршрут неизвестны сети: тонкая линия —".into(), GREY));
lines.push(("пройденное по измерениям, пунктир — прогноз курса.".into(), GREY));
if sim::is_drone_id(id) {
lines.push((format!("Разведчик противника №{id}"), YELLOW));
lines.push(("Роль: разведка (без оружия) — ищет технику вокруг объектов".into(), YELLOW));
}
let player = crate::player().map(|p| DVec3::new(p.x, p.y, p.z));
track_lines(&self.sim, t, player, lines);
lines.push(("Тонкая линия — пройденное по измерениям,".into(), GREY));
lines.push(("пунктир — прогноз курса.".into(), GREY));
if let Some(trail) = ui.trails.get(&id) {
lines.push((format!("Точек измерений: {}", trail.len()), GREY));
}
let who = self.who_tracks(t);
if !who.is_empty() {
lines.push((format!("Держат: {who}"), WHITE));
}
btns.push(("В центр".into(), Act::Centre, false));
btns.push(("Следить (F)".into(), Act::Follow, ui.follow));
}
@@ -2460,18 +2867,24 @@ impl AirDef {
lines.push(("Ничего не выбрано".into(), GREY));
lines.push((format!("Комплексов: {} · объектов: {}", self.sim.sams.len(), self.sim.targets.len()), WHITE));
lines.push((format!("Целей у сети: {} · известных ПУ: {live}", self.sim.picture().len()), WHITE));
if self.sim.truth {
lines.push(("Режим ИСТИНА: настоящие дроны, их цели и маршруты.".into(), YELLOW));
lines.push(("Это песочница, не данные сети. T — обратно.".into(), YELLOW));
}
// The recon flight's phase, only while the network actually holds a recon aircraft:
// what the visible aircraft are doing, not what the enemy learned (#135).
if self.sim.picture().values().any(|t| sim::is_drone_id(t.id)) {
let pic = self.sim.enemy_picture();
if let Some(phase) = crate::recon_view::battle_phase(&pic) {
lines.push((format!("Разведка противника: {phase} · разведчиков {}", pic.recon_sorties.len()), YELLOW));
}
}
if self.battle() {
lines.push(("Идёт налёт: расстановка закрыта".into(), YELLOW));
}
}
}
}
/// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's).
fn who_tracks(&self, t: &Track) -> String {
let n = self.sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count();
if n == 0 { String::new() } else { format!("{n} комплексов") }
}
}
fn remove_dsam(d: &mut Draft, i: usize) {
@@ -2538,13 +2951,24 @@ fn ring(ui: &MapUi, s: &mut Vec<Shape>, c: (f32, f32), r: f32, w: f32, color: u3
}
}
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), color: u32) {
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), w: f32, color: u32) {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let n = ((len / 8.0) as usize).min(200);
for i in (0..n).step_by(2) {
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.0, color));
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), w, color));
}
}
/// A coarser dash for the truth mode's routes: many drones at once, so fewer, longer dashes.
fn route_dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), color: u32) {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let n = ((len / 24.0) as usize).clamp(2, 24);
for i in (0..n).step_by(2) {
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.2, color));
}
}
@@ -2602,4 +3026,90 @@ mod tests {
let far: Vec<(f32, f32)> = (0..128).map(|i| (i as f32 * 30.0, 0.0)).collect();
assert_eq!(groups_of(&far, &vec![false; 128], CLUSTER_R, true).len(), 128);
}
/// A drone over the map's middle and a system that has not measured anything yet.
fn hover_fixture() -> (Sim, u32, MapUi) {
let mut sim = Sim::new(1);
sim.launch(sim::DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), DVec3::ZERO, DVec3::ZERO, &mut sim::Out::default());
let id = sim.drones[0].id;
let sid = sim.id();
sim.sams.push(Sam::new(sid, SamKind::Buk, DVec3::new(0.0, 64.0, 500.0), 0.0));
let ui = MapUi { size: (800.0, 600.0), centre: (0.0, 0.0), scale: 1.0, cursor: (400.0, 300.0), ..Default::default() };
(sim, id, ui)
}
#[test]
fn hover_reads_the_network_and_only_the_truth_mode_adds_drones() {
let (mut sim, id, ui) = hover_fixture();
// The system holds no track: the drone is not in the network's picture and is not hoverable.
assert_eq!(hover_at(&sim, &ui), None);
sim.truth = true;
assert_eq!(hover_at(&sim, &ui), Some(Hover::Drone(id)));
// A measured track is hoverable in the honest picture too.
sim.truth = false;
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false };
sim.sams[0].tracks.push(t);
assert_eq!(hover_at(&sim, &ui), Some(Hover::Track(id)));
// Away from the marker there is nothing.
let mut away = ui;
away.cursor = (20.0, 20.0);
assert_eq!(hover_at(&sim, &away), None);
}
#[test]
fn the_network_card_never_claims_a_target_and_lists_its_status_and_interception() {
let (mut sim, id, _) = hover_fixture();
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: true };
sim.sams[0].tracks.push(t);
let mut lines = Vec::new();
track_lines(&sim, &t, Some(DVec3::ZERO), &mut lines);
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
for must in ["Трек №", "Статус:", "Источник: сеть", "Скорость:", "Дистанция:", "Огневой захват", "Перехват: ракет нет", "Держат: 1 комплексов"] {
assert!(all.contains(must), "the track card lacks {must}: {all}");
}
assert!(!all.contains("Цель:"), "the network's card claims a target: {all}");
}
#[test]
fn the_truth_card_names_the_type_aim_route_and_interception() {
let (sim, _, ui) = hover_fixture();
let mut lines = Vec::new();
truth_lines(&sim, &sim.drones[0], Some(DVec3::ZERO), &mut lines);
let all: String = lines.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" | ");
for must in ["ИСТИНА", "Шахед", "вне картины сети", "Цель:", "Маршрут:", "До цели:", "Перехват:"] {
assert!(all.contains(must), "the truth card lacks {must}: {all}");
}
assert_eq!(hover_at(&sim, &ui), None, "the truth-off map revealed the drone");
}
#[test]
fn the_truth_layer_draws_white_frames_and_yellow_routes() {
let (mut sim, id, mut ui) = hover_fixture();
sim.truth = true;
// The label's width is cached so the test needs no GUI host call.
let label = format!("{} №{}", sim.drones[0].kind.spec().name, id);
ui.widths.insert(label.clone(), 60.0);
let mut shapes = Vec::new();
let mut labs = Vec::new();
let mut taken = Vec::new();
map_truth(&sim, &mut ui, Some(Hover::Drone(id)), &mut shapes, &mut labs, &mut taken);
assert!(shapes.iter().any(|s| matches!(s, Shape::Fill(f) if f.color == alpha(WHITE, 0.95))), "no white frame for the true drone");
assert!(shapes.iter().any(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFFE070)), "no yellow route or aim");
assert!(labs.iter().any(|l| l.text.contains("Шахед")), "the true drone has no label");
assert!(!taken.is_empty());
}
#[test]
fn the_truth_trail_never_mixes_into_the_network_trail() {
let (mut sim, id, mut ui) = hover_fixture();
sim.tick = SAMPLE;
ui.sample(&sim);
assert!(ui.trails.is_empty() && ui.seen.is_empty(), "the network got the truth's trail");
sim.truth = true;
sim.tick = SAMPLE * 2;
ui.sample(&sim);
assert_eq!(ui.truth_trails.get(&id).map(Vec::len), Some(1));
assert!(ui.trails.is_empty(), "the truth's trail was filed as the network's");
assert!(ui.truth_seen.contains_key(&id) && !ui.seen.contains_key(&id));
}
}
+81 -23
View File
@@ -3,7 +3,7 @@
//! renders it) locked on its target. K shows one system at a time, J all of
//! them in a grid.
use crate::panel::distance;
use crate::sim::{Sam, SamState, Sim, heading_of, roles_text};
use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text};
use glam::DVec3;
use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape};
@@ -91,12 +91,23 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
s.push(fill(x, y, w, h, 0xC0080C0A));
s.push(fill(x, y, w, 12.0, 0xE0142018));
let state = sam.state;
let optical = sam.kind == SamKind::Optical;
let lock = matches!(state, SamState::Lock | SamState::Launch | SamState::Fire);
let blink = lock && (tick / 4) % 2 == 0;
let label = state.name();
let label = if optical { sam.optical.state().name() } else { state.name() };
let color = if optical {
match sam.optical.state() {
OpticalState::Observing => 0xFF60FF80,
OpticalState::Holding => 0xFF9FE0FF,
OpticalState::NoSight => 0xFFFFA040,
OpticalState::Searching => 0xFFE0E0E0,
}
} else {
state.color()
};
let lw = render::text_width(label);
s.push(text(fit(format!("№{} {}", index + 1, spec.name), w - lw - 12.0), x + 3.0, y + 2.0, 0xFF9FE0FF));
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(state.color(), if blink { 0x80 } else { 0xFF })));
s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(color, if blink { 0x80 } else { 0xFF })));
// The radar, at the left: round the system, north up.
let rr = ((h - 28.0) / 2.0).min(w * 0.2).max(10.0);
@@ -114,9 +125,13 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
// A system that only fires (no radar) has no reach: a radar's sensor
// range stands in, and nothing is divided by zero.
let reach = match sam.kind.range() {
r if r > 0.0 => r,
_ => spec.sensor,
let reach = if optical {
crate::sim::OPTICAL_RANGE
} else {
match sam.kind.range() {
r if r > 0.0 => r,
_ => spec.sensor,
}
};
let scale = if reach > 0.0 { rr as f64 / (reach * 1.25) } else { 0.0 };
// The beam is the radar's real one: targets are measured as it passes them.
@@ -146,13 +161,17 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
seen += 1;
let k = scale as f32;
let (bx, by) = (rx + rel.x as f32 * k, ry + rel.z as f32 * k);
let allowed = sam.roles & d.kind.spec().class.bit() != 0;
// By the class the track was estimated (#133): the unknown are candidates too, shown in
// their own colour — the explicit policy — never the target's own class. No roles means
// holding fire, and that greys out the unknown as well.
let color = if Some(d.id) == target.map(|t| t.id) {
0xFFFFE040
} else if allowed {
0xFFFF4040
} else {
} else if !tr.class.in_roles(sam.roles) {
0xFF808080
} else if tr.class == ClassEst::Unknown {
0xFFFFA040
} else {
0xFFFF4040
};
if tr.forecast(tick) {
s.push(fill(bx - 1.5, by - 1.5, 3.0, 1.0, color));
@@ -164,14 +183,30 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
}
s.push(fill(rx - 1.5, ry - 1.5, 3.0, 3.0, 0xFF40A0FF));
let radar_text = if spec.sensor <= 0.0 {
let radar_text = if optical {
format!("ОПТИКА · {}", sam.optical.state().name())
} else if spec.sensor <= 0.0 {
format!("сеть · {seen}")
} else if radar_up {
format!("РЛС {} · {}", distance(reach), seen)
let profile = sam.radar_profile();
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) };
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
} else {
"РЛС ОТКАЗ".to_string()
};
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, if spec.sensor > 0.0 && !radar_up { 0xFFFF5040 } else { 0xFF80FF90 }));
let radar_color = if optical {
match sam.optical.state() {
OpticalState::Observing => 0xFF60FF80,
OpticalState::Holding => 0xFF9FE0FF,
OpticalState::NoSight => 0xFFFFA040,
OpticalState::Searching => 0xFFB0B0B0,
}
} else if spec.sensor > 0.0 && !radar_up {
0xFFFF5040
} else {
0xFF80FF90
};
s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, radar_color));
// Its health under the radar: a bar, red when it is low.
if sam.alive() && sam.health < 1.0 {
@@ -209,7 +244,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
// Worn or failed parts, over the picture: orange, red when one has failed.
if !sam.comps.whole() {
let failed = crate::sim::Part::ALL.iter().any(|p| sam.part_state(*p) == crate::sim::PartState::Failed);
s.push(text(fit(sam.parts_text(), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
s.push(text(fit(crate::why_view::parts(&sam.comps, sam.kind), cw * 0.55), cx + 3.0, cy + 3.0, if failed { 0xFFFF4040 } else { 0xFFFFB030 }));
}
// Crosshair.
s.push(fill(cx + cw / 2.0 - 0.5, cy + 3.0, 1.0, ch * 0.18, 0x90FFFFFF));
@@ -217,6 +252,21 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
s.push(fill(cx + 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
s.push(fill(cx + cw * 0.82 - 3.0, cy + ch / 2.0 - 0.5, cw * 0.18, 1.0, 0x90FFFFFF));
match target {
Some(_) if optical => {
// The optical post's picture: its own class observation, never the true model name.
let (color, info) = match sam.optical.state() {
OpticalState::Observing => (0xFF60FF80, sam.optical.status_text()),
OpticalState::Holding => (0xFF9FE0FF, sam.optical.status_text()),
OpticalState::NoSight => (0xFFFFA040, sam.optical.status_text()),
OpticalState::Searching => (0xFFB0B0B0, sam.optical.status_text()),
};
let (bw, bh) = (cw * 0.3, ch * 0.34);
brackets(s, cx + cw / 2.0 - bw / 2.0, cy + ch / 2.0 - bh / 2.0, bw, bh, 6.0, color);
if ch > 50.0 {
s.push(text(fit(info.clone(), cw - 6.0), cx + 3.0, cy + ch - 20.0, color));
}
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
}
Some(t) => {
let color = if lock { if blink { 0xFFFF3030 } else { 0xFFFF8080 } } else { 0xFFFFE060 };
let (bw, bh) = (cw * 0.3, ch * 0.34);
@@ -233,9 +283,12 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
let rel = at - sam.pos;
let bearing = (heading_of(rel).to_degrees() + 180.0).rem_euclid(360.0);
if ch > 50.0 {
s.push(text(fit(t.kind.spec().name.into(), cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
// What the system knows it by: the estimated class; the sandbox's truth names the model.
let name = if sim.truth { t.kind.spec().name.to_string() } else { track.map_or_else(|| "тип не определён".into(), |tr| tr.class.name()) };
s.push(text(fit(name, cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF));
}
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, t.vel.length() * 72.0);
// The speed its own measurements showed, never the target's own figures.
let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, track.map_or(0.0, |tr| tr.vel.length()) * 72.0);
if let Some(tr) = track {
if tr.forecast(tick) {
info += &format!(" прогноз {:.1}с", tr.age(tick) as f64 / 20.0);
@@ -248,19 +301,24 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0));
}
None if optical => s.push(text(fit(sam.optical.status_text(), cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFB0B0B0)),
None => s.push(text("ПОИСК", cx + 3.0, cy + ch - 10.0, 0xFF80FF90)),
}
// What it carries and does.
let mut line = String::new();
if !matches!(sam.kind, crate::sim::SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles);
if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
if optical {
line = sam.optical.status_text();
} else {
if !matches!(sam.kind, SamKind::Gepard) {
line += &format!("Р{} ", sam.missiles);
if sam.kind == SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); }
}
if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts);
}
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
}
if crate::sim::catalog::unit(sam.kind).has_gun() {
line += &format!("Оч{} ", sam.bursts);
}
line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles));
s.push(text(fit(line, cw), cx, y + h - 10.0, 0xFF9FE0FF));
}
+311
View File
@@ -0,0 +1,311 @@
//! The world overlay (#132): while the player holds the overlay key, square markers over the
//! targets they can see, each with a short line — the class the radars estimated (#133) and the
//! distance. The picture is the network's, as the radar and the map read it; the sandbox's truth
//! mode adds white markers of the real drones, labelled with their actual type, apart from the
//! 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
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
use crate::panel::distance;
use crate::sim::{ClassEst, Sim, Track};
use glam::DVec3;
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 HUD's 1024 shapes — a marker is four sides and a label.
const MAX_MARKERS: usize = 64;
/// A marker's side thickness, pixels.
const LINE: f32 = 1.0;
/// A label line's height (the HUD font with its shadow).
const LH: f32 = 9.0;
/// The half-size a marker clamps to, near and far.
const HALF_MIN: f32 = 5.0;
const HALF_MAX: f32 = 16.0;
const RED: u32 = 0xFF4040;
const ORANGE: u32 = 0xFFB040;
const WHITE: u32 = 0xFFFFFFFF;
const GREEN: u32 = 0xFF80FF90;
const YELLOW: u32 = 0xFFFFE070;
/// The interceptors' own colour (the radar's missile dot).
const MISSILE: u32 = 0xFFE060;
/// An interceptor's marker half-size: small, it is not a target.
const MISSILE_HALF: f32 = 3.0;
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
}
fn text(t: String, x: f32, y: f32, color: u32, centered: bool) -> Shape {
Shape::Text(TextShape { text: t, at: pt(x, y), color, centered, shadow: true })
}
/// 0xAARRGGBB with this alpha (0..1).
fn alpha(rgb: u32, a: f64) -> u32 {
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
}
/// A square outline around a screen point: four thin fills, the world's marker.
fn square_outline(x: f32, y: f32, half: f32, color: u32) -> Vec<Shape> {
let (w, h) = (half * 2.0, LINE);
vec![
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w, h }, color }),
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y + half - LINE, w, h }, color }),
Shape::Fill(FillShape { rect: Rect { x: x - half, y: y - half, w: h, h: w }, color }),
Shape::Fill(FillShape { rect: Rect { x: x + half - LINE, y: y - half, w: h, h: w }, color }),
]
}
/// A marker's half-size by the distance: near targets read bigger, far ones stay legible.
fn half(dist: f64) -> f32 {
(700.0 / dist.max(1.0)).clamp(HALF_MIN as f64, HALF_MAX as f64) as f32
}
/// The short line under a network marker: the estimated class's mark (#133) and the distance to
/// the forecast place; a forecast says how old it is. An unidentified track gets a `?`, never the
/// target's type.
fn track_label(t: &Track, now: u64, player: DVec3) -> String {
let mark = match t.class {
ClassEst::Unknown => "?",
c => c.mark(),
};
let mut s = format!("{mark} {}", distance(t.est(now).distance(player)));
if t.forecast(now) {
s += &format!(" ~{}с", t.age(now) / 20);
}
s
}
/// Where a marker's label sits: under the square, or over it when the bottom edge is close.
fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
if above {
if y - half - LH - 2.0 >= 0.0 { y - half - LH - 2.0 } else { y + half + 2.0 }
} else if y + half + LH + 2.0 <= gui_h {
y + half + 2.0
} else {
y - half - LH - 2.0
}
}
/// 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
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -> Option<Point>) -> Vec<Shape> {
let mut s = Vec::new();
if gui.0 <= 0.0 || gui.1 <= 0.0 {
return s;
}
let pic = sim.air_picture();
let now = pic.now;
let truth = sim.truth && !pic.unaided;
// The network's tracks, nearest first: a full raid keeps the closest markers.
let mut tracks: Vec<&Track> = pic.tracks.iter().collect();
tracks.sort_by(|a, b| a.est(now).distance(player).total_cmp(&b.est(now).distance(player)));
let mut shown = 0usize;
let mut hidden = tracks.len().saturating_sub(MAX_MARKERS);
for t in tracks.into_iter().take(MAX_MARKERS) {
let e = t.est(now);
let dist = e.distance(player);
let Some(p) = project(e) else { hidden += 1; continue };
let h = half(dist);
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
hidden += 1;
continue;
}
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
let (color, a) = if pic.unaided {
(RED, 1.0)
} else if t.forecast(now) {
(ORANGE, (1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3))
} else {
(RED, 1.0)
};
let color = alpha(color, a);
s.extend(square_outline(p.x, p.y, h, color));
s.push(text(track_label(t, now, player), p.x, label_y(p.y, h, gui.1, false), color, true));
shown += 1;
}
// The truth's own markers: the real drones, even the ones no radar holds, white and labelled
// 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.
if truth {
let mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect();
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
hidden += drones.len().saturating_sub(MAX_MARKERS);
for d in drones.into_iter().take(MAX_MARKERS) {
let Some(p) = project(d.pos) else { hidden += 1; continue };
let h = half(d.pos.distance(player)) + 2.0;
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
hidden += 1;
continue;
}
s.extend(square_outline(p.x, p.y, h, WHITE));
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));
shown += 1;
}
}
// 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).
let mut missiles: Vec<_> = sim.missiles.iter().collect();
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
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));
}
// 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
// or past the edges.
let head = if truth {
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}")
} else {
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}")
};
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
s
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{DroneKind, Out, Sam, SamKind};
const GUI: (f32, f32) = (800.0, 600.0);
/// A projector as the game's: the world ahead lands on the screen, behind the camera None.
/// Here: south (+z) is ahead, x spreads across the screen, the height lines up at 64.
fn ahead(p: DVec3) -> Option<Point> {
if p.z <= 0.0 {
return None;
}
Some(pt(400.0 + p.x as f32, 300.0 - (p.y - 64.0) as f32))
}
fn sim_with(kind: DroneKind, at: DVec3) -> Sim {
let mut sim = Sim::new(1);
sim.launch(kind, at, DVec3::ZERO, DVec3::new(at.x, 64.0, 5000.0), &mut Out::default());
sim
}
fn fills(shapes: &[Shape], rgb: u32) -> usize {
shapes.iter().filter(|s| matches!(s, Shape::Fill(f) if f.color & 0xFFFFFF == rgb & 0xFFFFFF)).count()
}
fn texts(shapes: &[Shape]) -> Vec<&TextShape> {
shapes.iter().filter_map(|s| match s {
Shape::Text(t) => Some(t),
_ => None,
}).collect()
}
#[test]
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 shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
// One marker: four red sides, and a label with the firm class's mark and the distance.
assert_eq!(fills(&shapes, RED), 4, "the marker is not one square outline");
let label = texts(&shapes).into_iter().find(|t| t.text.contains("100 м")).expect("no distance label");
assert!(label.text.starts_with("Д "), "the firm drone class is not marked: {}", label.text);
assert!(label.centered && label.at.y > 300.0, "the label sits under the square");
// The header names the network's data and the counts.
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("данные сети РЛС") && head.text.contains("в кадре 1, за кадром 0"), "{}", head.text);
}
#[test]
fn behind_the_camera_and_off_screen_are_counted_not_drawn() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
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::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, RED), 4, "the drone behind the camera drew a marker");
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("в кадре 1, за кадром 1"), "{}", head.text);
// Off the screen's edge: still a place, but no marker.
let shapes = draw(&sim, DVec3::ZERO, GUI, |_| Some(pt(-40.0, 300.0)));
assert_eq!(fills(&shapes, RED), 0);
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("в кадре 0, за кадром 2"), "{}", head.text);
}
#[test]
fn the_label_never_leaks_the_type_of_an_unidentified_track() {
let t = Track { id: 1, class: ClassEst::Unknown, pos: DVec3::new(0.0, 64.0, 100.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 1, locked: false };
let label = track_label(&t, 0, DVec3::ZERO);
assert!(label.starts_with("? "), "{label}");
assert!(!label.contains("дрон") && !label.contains("Шахед"), "{label}");
// A probable class keeps its question mark; a firm one loses it.
let t = Track { class: ClassEst::Probable(crate::sim::Class::Cruise), ..t };
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К? "));
let t = Track { class: ClassEst::Firm(crate::sim::Class::Cruise), hits: 3, ..t };
assert!(track_label(&t, 0, DVec3::ZERO).starts_with("К "));
// A forecast says its age.
let label = track_label(&t, 100, DVec3::ZERO);
assert!(label.contains("~5с"), "{label}");
}
#[test]
fn the_truth_mode_marks_the_real_drones_apart_from_the_network() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
// Without the truth mode: no white markers, no actual type anywhere.
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 0);
assert!(!texts(&shapes).iter().any(|t| t.text.contains("Шахед")), "the network overlay leaked the type");
// With it: a white square with the real type, and the header says whose picture it is.
sim.truth = true;
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 4, "the truth marker is not one white square");
let label = texts(&shapes).into_iter().find(|t| t.text.contains("Шахед-136")).expect("no truth label");
assert!(label.text.contains("100 м") && label.at.y < 300.0, "the truth label sits over the square: {label:?}");
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("ИСТИНА (песочница)"), "{}", head.text);
// The truth mode with no system deployed adds nothing: the sky as it is was already shown.
sim.sams.clear();
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert_eq!(fills(&shapes, WHITE), 0);
}
#[test]
fn a_full_raid_stays_inside_the_huds_shape_budget() {
let mut sim = Sim::new(1);
sim.raid(DroneKind::Shahed, DVec3::new(0.0, 64.0, 0.0), 80, 300.0, &mut Out::default());
sim.truth = true;
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert!(shapes.len() <= 1024, "the overlay overflowed the HUD: {} shapes", shapes.len());
// The nearest markers were kept, the rest counted.
let head = texts(&shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).unwrap();
assert!(head.text.contains("за кадром"), "{}", head.text);
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
}
#[test]
fn interceptors_wear_small_yellow_squares_without_labels() {
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
sim.missiles.push(crate::sim::Missile::test_at(1, DVec3::new(10.0, 70.0, 120.0), 0));
sim.missiles.push(crate::sim::Missile::test_at(2, DVec3::new(0.0, 64.0, -50.0), 0));
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
// The one ahead: four yellow sides; the one behind the camera: nothing.
assert_eq!(fills(&shapes, MISSILE), 4);
assert!(!texts(&shapes).iter().any(|t| t.text.contains("перехват")), "an interceptor is not a target");
// The budget holds with a full salvo too.
for id in 3..100 {
sim.missiles.push(crate::sim::Missile::test_at(id, DVec3::new(id as f64, 64.0, 100.0), 0));
}
let shapes = draw(&sim, DVec3::ZERO, GUI, ahead);
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
assert!(fills(&shapes, MISSILE) / 4 <= MAX_MARKERS);
}
#[test]
fn labels_flip_over_the_square_near_the_edges() {
// Near the bottom: the label goes over the square; near the top: under it.
assert!(label_y(590.0, 10.0, 600.0, false) < 590.0);
assert!(label_y(10.0, 10.0, 600.0, true) > 10.0);
assert!(label_y(300.0, 10.0, 600.0, false) > 300.0);
assert!(label_y(300.0, 10.0, 600.0, true) < 300.0);
}
}
+106 -12
View File
@@ -1,6 +1,6 @@
//! The summary panel (top right): the alert, what is in the air, each
//! air-defence system's state and the score.
use crate::sim::{AirPicture, DroneKind, Sim};
use crate::sim::{AirPicture, Class, ClassEst, Sim};
use glam::DVec3;
use horizon_mod_sdk::hud::Line;
@@ -31,28 +31,50 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
} else {
let blink = (sim.tick / 10) % 2 == 0;
lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", pic.tracks.len()), if blink { RED } else { PINK }));
// By type, as the radars classed them.
// By the class the tracks were estimated (#133): probable and firm counted apart, the
// unidentified named — the exact models stay in the sandbox's truth line.
let mut by_type = String::new();
for kind in DroneKind::ALL {
let n = pic.tracks.iter().filter(|t| t.kind == kind).count();
if n > 0 {
if !by_type.is_empty() {
by_type += ", ";
for c in Class::ALL {
let firm = pic.tracks.iter().filter(|t| t.class == ClassEst::Firm(c)).count();
let prob = pic.tracks.iter().filter(|t| t.class == ClassEst::Probable(c)).count();
for (n, pre) in [(firm, ""), (prob, "вер. ")] {
if n > 0 {
if !by_type.is_empty() {
by_type += ", ";
}
by_type += &format!("{pre}{} ×{n}", c.name());
}
by_type += &format!("{} ×{n}", kind.spec().name);
}
}
let unknown = pic.tracks.iter().filter(|t| t.class == ClassEst::Unknown).count();
if unknown > 0 {
if !by_type.is_empty() {
by_type += ", ";
}
by_type += &format!("не опознано ×{unknown}");
}
lines.push(line(by_type, PINK));
// The nearest track to the player: where it was last measured (a forecast says so, with its age).
if let Some(t) = pic.nearest(player) {
let e = t.est(now);
let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() };
lines.push(line(
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч · {} кач.{}{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel), t.product.name(), t.quality),
PINK,
));
}
}
// Recon aircraft the network tracks: their presence and the coarse phase of the flight. This is
// what the visible aircraft are doing, not the enemy's knowledge — the marks and the reasons are
// the debug command's and the after-action review's alone (#135).
let recon_n = pic.tracks.iter().filter(|t| crate::sim::is_drone_id(t.id)).count();
if recon_n > 0 {
let mut text = format!("Разведка противника: разведчиков в воздухе {recon_n}");
if let Some(phase) = crate::recon_view::battle_phase(&sim.enemy_picture()) {
text += &format!(" · фаза: {phase}");
}
lines.push(line(text, YELLOW));
}
if sim.truth {
let real = sim.drones.iter().filter(|d| d.alive()).count();
let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count();
@@ -61,6 +83,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
text += ", противник планирует налёт";
}
lines.push(line(text, YELLOW));
// The recon phase, in the truth only: the aircraft out and the marks the enemy holds
// are its knowledge, not the player's (#135).
let (out, marks) = sim.recon_status();
if out > 0 || marks > 0 {
lines.push(line(format!("РАЗВЕДКА ПРОТИВНИКА: в воздухе {out}, отметок в картине {marks}"), YELLOW));
}
}
// The launch sites found, and the strike missiles (#101).
if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() {
@@ -77,6 +105,11 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
let worst = sim.target_health.iter().copied().fold(100.0, f64::min);
lines.push(line(format!("Объекты: {}", list.join(" ")), if worst < 50.0 { RED } else { GREEN }));
}
// The passive optical posts (#136): their own status and source, never a radar's emission.
let optics = sim.optical_reports();
if let Some(r) = optics.iter().find(|r| r.state == crate::sim::OpticalState::Observing).or_else(|| optics.first()) {
lines.push(line(format!("Опт. №{}: {}", r.index, r.line()), CYAN));
}
let lost = sim.sams.iter().filter(|s| !s.alive()).count();
if lost > 0 {
lines.push(line(format!("Потеряно комплексов: {lost}"), RED));
@@ -94,12 +127,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
}
for sam in sim.sams.iter().take(shown) {
let mut text = if sam.kind.armed() {
format!("{} [{}]", sam.status(), crate::sim::roles_text(sam.roles))
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles))
} else {
sam.status()
crate::battery_view::sam_status(sam)
};
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos)));
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
}
if sam.kills > 0 {
text += &format!(" ({})", sam.kills);
@@ -119,3 +152,64 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
));
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{Aim, AirPicture, Approach, DroneKind, Out, RaidOrder, Track};
use glam::DVec3;
fn track(id: u32, class: ClassEst) -> Track {
Track { id, class, pos: DVec3::new(0.0, 120.0, 300.0), vel: DVec3::new(0.0, 0.0, -0.5), tick: 100, own_tick: 100, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false }
}
// A recon aircraft the network holds is named as such, with the flight's coarse phase; the line
// carries no mark, area or priority — the enemy's knowledge is not the HUD's (#135).
#[test]
fn a_tracked_recon_aircraft_shows_presence_and_phase_not_marks() {
let mut sim = Sim::new(135);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart };
sim.order_raid(&order, &[object], &mut Out::default());
let pic = sim.air_picture();
assert!(pic.tracks.iter().any(|t| crate::sim::is_drone_id(t.id)), "the smart wave sent no recon to track");
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе"), "{}", recon.text);
assert!(recon.text.contains("фаза:"), "the flight's phase was not shown: {}", recon.text);
assert!(!recon.text.contains("приоритет") && !recon.text.contains("Отметка"), "the HUD leaked the enemy's marks: {}", recon.text);
assert!(lines.iter().all(|l| !l.text.contains("Отметка") && !l.text.contains("приоритет")), "a mark reached the normal HUD");
}
// An ordinary strike track is not a recon flight: no recon line appears.
#[test]
fn an_ordinary_track_is_not_called_recon() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(1, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
// A recon id in the picture is enough for the presence line even without a live sortie (a flight
// finishing its way home): the phase is then omitted, the presence stays.
#[test]
fn a_recon_track_without_a_sortie_still_names_the_presence() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: vec![track(0x3000_0001, ClassEst::Firm(Class::Drone))], unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line");
assert!(recon.text.contains("разведчиков в воздухе 1"), "{}", recon.text);
assert!(!recon.text.contains("фаза:"), "a phase was invented without a sortie: {}", recon.text);
}
#[test]
fn an_empty_sky_has_no_recon_line() {
let sim = Sim::new(1);
let pic = AirPicture { now: 100, tracks: Vec::new(), unaided: false };
let lines = summary(&sim, &pic, DVec3::ZERO);
assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}");
}
}
+34
View File
@@ -286,6 +286,16 @@ impl<P, E> Session<P, E> {
Some(Cleanup { actions })
}
/// The world is gone (the title screen): the game stops ticking there, so an active export
/// would otherwise go on recording the title with its playback clock frozen. Nothing to do
/// in Live, and a world still open is not a leave.
pub fn world_left(&mut self, world: Option<&str>) -> Option<Cleanup> {
if self.is_live() || world.is_some() {
return None;
}
self.end(ExitCause::WorldChange)
}
/// A world change invalidates live work too. Active playback uses the normal cleanup path,
/// which advances generation exactly once; Live advances generation without host cleanup.
pub fn world_changed(&mut self) -> Option<Cleanup> {
@@ -466,6 +476,30 @@ mod tests {
assert_ne!(session.generation(), first);
}
#[test]
fn a_gone_world_ends_an_active_export_once() {
let mut session = Session::<(), ()>::default();
assert!(session.world_left(None).is_none(), "Live has nothing to clean up");
session.replay(());
assert!(session.world_left(Some("world:w")).is_none(), "the world is still open");
let State::Replay(playback) = session.take() else {
panic!("replay state lost")
};
session.export(playback, ());
let cleanup = session.world_left(None).expect("the title screen ends the export");
assert!(cleanup.actions.contains(&CleanupAction::CancelCapture));
let mut host = HostFixture::default();
host.apply(&cleanup);
let count = host.actions.len();
assert!(session.world_left(None).is_none(), "a second frame sees Live");
assert_eq!(host.actions.len(), count, "cleanup is not repeated");
assert_eq!(
host.actions.iter().filter(|a| **a == CleanupAction::CancelCapture).count(),
1
);
}
#[test]
fn end_and_restart_emit_cleanup_once_for_stop_unload_failure_and_success() {
for cause in [
+171 -14
View File
@@ -1,15 +1,24 @@
//! The radar screen (top left): a round scope round the player, north up,
//! with a sweeping beam; blips fade after the beam passes them.
//! The radar screen (bottom right): a round scope round the player, north up,
//! with a sweeping beam; blips fade after the beam passes them. A track's blip is a shape by the
//! class the radar measured (#132), big enough to read at a glance; close ones merge with a count.
use crate::panel::distance;
use crate::sim::{SamKind, Sim};
use crate::sim::{Class, ClassEst, SamKind, Sim};
use glam::DVec3;
use horizon_mod_sdk::render::{FillShape, Point, QuadShape, Rect, Shape, TextShape};
/// The scope's side in GUI pixels.
pub const SIZE: f32 = 112.0;
/// The corner box's height: the scope and its range label, plus the truth mode's own line when it shows one.
pub fn height(truth_label: bool) -> f32 {
SIZE + if truth_label { 22.0 } else { 12.0 }
}
/// Blocks from the centre to the edge.
const RANGE: f64 = 500.0;
const SEGMENTS: usize = 48;
/// A track blip's half-size: the icons span about six pixels, against the old dot's three and a half.
const BLIP: f32 = 3.0;
/// Tracks this close on the scope merge into one blip with their number.
const MERGE_R: f32 = 4.5;
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
@@ -32,6 +41,34 @@ fn alpha(rgb: u32, a: f64) -> u32 {
((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF)
}
/// A track's blip: a shape by the estimated class, pointing along the measured course.
/// Drones are triangles, jets darts, cruise squares, supersonic diamonds, ballistic octagons;
/// an unidentified track gets a question mark instead of leaking the target's type (#133).
fn blip(class: ClassEst, x: f32, y: f32, color: u32, vel: DVec3) -> Vec<Shape> {
let h = DVec3::new(vel.x, 0.0, vel.z).normalize_or_zero();
let (hx, hy) = if h == DVec3::ZERO { (0.0, -1.0) } else { (h.x as f32, h.z as f32) };
let (px, py) = (-hy, hx);
let r = BLIP;
let at = |along: f32, side: f32| pt(x + hx * along + px * side, y + hy * along + py * side);
match class.class() {
Some(Class::Drone) => vec![quad(at(r * 1.2, 0.0), at(-r * 0.8, r * 0.9), at(-r * 0.8, -r * 0.9), at(-r * 0.8, -r * 0.9), color)],
Some(Class::Jet) => vec![quad(at(r * 1.3, 0.0), at(-r * 0.9, r * 0.9), at(-r * 0.3, 0.0), at(-r * 0.9, -r * 0.9), color)],
Some(Class::Cruise) => vec![square(x, y, 2.6, color)],
Some(Class::Supersonic) => vec![quad(pt(x, y - 3.2), pt(x + 3.2, y), pt(x, y + 3.2), pt(x - 3.2, y), color)],
Some(Class::Ballistic) => vec![square(x, y, 2.3, color), quad(pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y), color)],
None => vec![square(x, y, 2.4, color), text("?".into(), x, y - 3.0, 0xFF200808, true)],
}
}
/// Keeps a blip's centre far enough inside the disc that the whole icon stays on the scope: the longest point
/// of any class's icon is 1.3 × a half-size out.
fn inside(x: f32, y: f32, cx: f32, cy: f32, r: f32) -> (f32, f32) {
let (dx, dy) = (x - cx, y - cy);
let d = dx.hypot(dy);
let max = r - BLIP * 1.4 - 0.5;
if d > max && d > 0.0 { (cx + dx / d * max, cy + dy / d * max) } else { (x, y) }
}
pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
let mut s = Vec::new();
let r = SIZE / 2.0 - 2.0;
@@ -143,49 +180,169 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
s.push(square(x, y, 1.5, 0xFFFFFFA0));
}
}
// The player is below target blips: a close target must not disappear under the white arrow.
// Minecraft's yaw 0 looks south (+z, down the scope).
let face = yaw.to_radians();
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
let mut far = 0;
// The air picture is what the systems' radars hold, as they last measured it (a track older than a second
// is a forecast, dimmer); with no system deployed, the sky as it is. Nothing else is read (#93).
let pic = sim.air_picture();
let now = pic.now;
// (x, y, class, colour, brightness, velocity) of every track on the scope, its icon kept inside the disc.
let mut marks: Vec<(f32, f32, ClassEst, u32, f64, DVec3)> = Vec::new();
for t in &pic.tracks {
let (pos, vel) = (t.est(now), t.vel);
match scope(pos) {
Some((x, y, bearing)) => {
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
// The product is visible: a coarse search plot is amber, a refinement yellow, a fire plot red.
let fresh_color = match t.product {
crate::sim::battery::Measure::Search => 0xFFB060,
crate::sim::battery::Measure::Refine => 0xFFE070,
crate::sim::battery::Measure::Fire => 0xFF4040,
};
let (a, color) = if pic.unaided {
(fade(bearing), 0xFF4040)
} else if t.forecast(now) {
((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040)
} else {
(1.0, 0xFF4040)
(1.0, fresh_color)
};
s.push(square(x, y, 1.8, alpha(color, a)));
// Its heading, a short tail.
let v = vel.normalize_or_zero();
s.push(quad(pt(x, y), pt(x + 0.6, y), pt(x - v.x as f32 * 6.0 + 0.6, y - v.z as f32 * 6.0), pt(x - v.x as f32 * 6.0, y - v.z as f32 * 6.0), alpha(color, a * 0.6)));
let (x, y) = inside(x, y, cx, cy, r);
marks.push((x, y, t.class, color, a, vel));
}
None => far += 1,
}
}
// A tight raid reads as one blip with its number, not a pile of icons.
let pos: Vec<(f32, f32)> = marks.iter().map(|m| (m.0, m.1)).collect();
for grp in crate::map::group(&pos, MERGE_R) {
let (x, y, class, color, a, vel) = marks[grp[0]];
s.extend(blip(class, x, y, alpha(color, a), vel));
// Its heading, a short tail, kept on the disc too.
let v = vel.normalize_or_zero();
let (ex, ey) = inside(x - v.x as f32 * 7.0, y - v.z as f32 * 7.0, cx, cy, r);
s.push(quad(pt(x, y), pt(x + 1.0, y), pt(ex + 1.0, ey), pt(ex, ey), alpha(color, a * 0.6)));
if grp.len() > 1 {
s.push(text(format!("×{}", grp.len()), x + 4.0, y - 9.0, alpha(color, a), false));
}
}
// The true places, when the sandbox asks for them: a white dot beside the track, to see how far the picture is off.
if sim.truth && !pic.unaided {
for d in sim.drones.iter().filter(|d| d.alive()) {
if let Some((x, y, _)) = scope(d.pos) {
s.push(square(x, y, 0.8, 0xFFFFFFFF));
let (x, y) = inside(x, y, cx, cy, r);
s.push(square(x, y, 1.3, 0xFFFFFFFF));
}
}
}
// The player: a white arrow the way they look.
// Minecraft's yaw 0 looks south (+z, down the scope).
let face = yaw.to_radians();
let tip = |a: f32, l: f32| pt(cx - (face + a).sin() * l, cy + (face + a).cos() * l);
s.push(quad(tip(0.0, 6.0), tip(2.5, 4.0), pt(cx, cy), tip(-2.5, 4.0), 0xFFFFFFFF));
// Labels.
s.push(text(format!("РЛС · {}", distance(RANGE)), cx, SIZE + 2.0, 0xFF80FF90, true));
if sim.truth && !pic.unaided {
s.push(text("ИСТИНА · песочница".into(), cx, SIZE + 12.0, 0xFFFFE070, true));
}
s.push(text("С".into(), cx, 3.0, 0xFF80FF90, true));
if far > 0 {
s.push(text(format!("+{far} за пределом"), cx, SIZE - 14.0, 0xFFFF8080, true));
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{DroneKind, Out, Sam};
#[test]
fn target_blips_are_drawn_over_the_player_arrow() {
let mut sim = Sim::new(1);
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -10.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let arrow = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFFFFFF)).unwrap();
// The Shahed's blip is a red triangle (a quad with a repeated corner), drawn after the arrow.
let target = shapes.iter().rposition(|s| matches!(s, Shape::Quad(q) if q.color == 0xFFFF4040)).unwrap();
assert!(target > arrow, "the player arrow covers the target blip");
}
#[test]
fn every_class_has_its_own_blip_shape() {
let vel = DVec3::new(0.5, 0.0, 0.0);
let shapes: Vec<Vec<Shape>> = Class::ALL.iter().map(|c| blip(ClassEst::Firm(*c), 50.0, 50.0, 0xFFFF4040, vel)).collect();
for (i, a) in shapes.iter().enumerate() {
assert!(!a.is_empty());
for b in &shapes[i + 1..] {
assert_ne!(format!("{a:?}"), format!("{b:?}"), "two classes share one icon");
}
}
// A courseless track (a ballistic one straight overhead) still draws, pointing north.
assert!(!blip(ClassEst::Firm(Class::Ballistic), 50.0, 50.0, 0xFFFF4040, DVec3::Y).is_empty());
assert!(blip(ClassEst::Unknown, 50.0, 50.0, 0xFFFF4040, vel).iter().any(|s| matches!(s, Shape::Text(t) if t.text == "?")));
}
#[test]
fn blips_stay_inside_the_scope() {
let mut sim = Sim::new(1);
// One track near the rim on every bearing, one of each class among them, one just beyond it.
for k in 0..8 {
let a = k as f64 / 8.0 * std::f64::consts::TAU;
sim.launch(DroneKind::Shahed, DVec3::new(a.sin() * 495.0, 64.0, a.cos() * 495.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
for (k, kind) in [DroneKind::Geran3, DroneKind::Kh101, DroneKind::Kh22, DroneKind::Kinzhal].into_iter().enumerate() {
let a = (k as f64 + 0.5) / 4.0 * std::f64::consts::TAU;
sim.launch(kind, DVec3::new(a.sin() * 490.0, 64.0, a.cos() * 490.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -700.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let (cx, cy, r) = (SIZE / 2.0, SIZE / 2.0, SIZE / 2.0 - 2.0);
let mut blips = 0;
for s in &shapes {
let corners = match s {
Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 => vec![q.corners.0, q.corners.1, q.corners.2, q.corners.3],
Shape::Fill(f) if f.color & 0xFFFFFF == 0xFF4040 => vec![pt(f.rect.x, f.rect.y), pt(f.rect.x + f.rect.w, f.rect.y), pt(f.rect.x, f.rect.y + f.rect.h), pt(f.rect.x + f.rect.w, f.rect.y + f.rect.h)],
_ => continue,
};
blips += 1;
for p in corners {
assert!((p.x - cx).hypot(p.y - cy) <= r + 0.01, "a blip corner leaves the disc: {p:?}");
}
}
assert!(blips >= 8, "the rim tracks were not drawn");
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("за пределом"))), "the track beyond the range is counted");
}
#[test]
fn a_tight_raid_merges_into_one_blip_with_a_count() {
let mut sim = Sim::new(1);
for k in 0..3 {
sim.launch(DroneKind::Shahed, DVec3::new(100.0 + k as f64, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
}
let shapes = draw(&sim, DVec3::ZERO, 0.0);
assert!(shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.text == "×3")), "the merged blip has no count");
let triangles = shapes
.iter()
.filter(|s| matches!(s, Shape::Quad(q) if q.color & 0xFFFFFF == 0xFF4040 && q.corners.2.x == q.corners.3.x && q.corners.2.y == q.corners.3.y))
.count();
assert_eq!(triangles, 1, "three close tracks drew three icons");
}
#[test]
fn the_truth_mode_is_labelled_on_the_scope() {
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.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, -100.0), DVec3::ZERO, DVec3::ZERO, &mut Out::default());
let plain = draw(&sim, DVec3::ZERO, 0.0);
assert!(!plain.iter().any(|s| matches!(s, Shape::Text(t) if t.text.contains("ИСТИНА"))));
sim.truth = true;
let shapes = draw(&sim, DVec3::ZERO, 0.0);
let label = shapes.iter().find_map(|s| match s {
Shape::Text(t) if t.text.contains("ИСТИНА") && t.text.contains("песочница") => Some(t),
_ => None,
}).expect("the truth mode is not marked");
// The corner box is sized to hold the label: a line of the HUD font is 9 pixels with its shadow.
assert!(label.at.y + 9.0 <= height(true), "the truth label falls outside the corner box");
assert!(height(true) > height(false));
}
}
+286
View File
@@ -0,0 +1,286 @@
//! Text for the enemy's reconnaissance (#135): the readable phase of a recon flight and the
//! reason a mark outranks another. It reads only the diagnostic report types (`EnemyPictureReport`,
//! `ReconReport`, `ReconSortieReport`) — an area, a public category, a channel, an age and a quality,
//! never a true place, `SamKind`, health, magazine, link or real id. The full picture is for the
//! explicit debug command and the after-action review; the battle HUD takes only the coarse phase
//! of aircraft the player's own network already tracks.
use crate::sim::{Category, Confidence, EnemyPictureReport, Quality, ReconReport, ReconSortieReport, priority_parts};
/// The public category a look reported, in the panel's words.
pub fn category_name(key: &str) -> &'static str {
match key {
"radar" => "РЛС",
"launcher" => "пусковая",
"gun" => "пушка",
"ew" => "РЭБ",
"support" => "тыл",
_ => "не определено",
}
}
/// A radar's role, public only once a refined look told it.
pub fn role_name(key: &str) -> &'static str {
match key {
"multi" => "многофункциональная",
"search" => "обзорная",
"engagement" => "наведения",
"height" => "высотомер",
_ => "не определена",
}
}
/// The channel that showed the unit.
pub fn source_name(key: &str) -> &'static str {
match key {
"emission" => "излучение",
"jamming" => "РЭБ",
"launch" => "пуск",
_ => "пролёт",
}
}
/// How well the area is known.
pub fn quality_name(key: &str) -> &'static str {
match key {
"refined" => "уточнённая",
_ => "грубая",
}
}
/// The trust the picture puts in a mark of this age.
pub fn confidence_name(confidence: Confidence) -> &'static str {
match confidence {
Confidence::Confirmed => "подтверждена",
Confidence::Probable => "вероятна",
Confidence::Doubtful => "сомнительна",
}
}
/// The phase of a sortie, as the timeline and the battle UI read it.
pub fn phase_name(phase: &str) -> &'static str {
match phase {
"reporting" => "донесение",
"done" => "завершение",
"looking" => "осмотр",
_ => "разведка",
}
}
/// Why a smart drone's aim is what it is, in words.
pub fn intent_name(intent: &str) -> &'static str {
match intent {
"sead" => "подавление ПВО",
"react" => "реакция",
"replace" => "замена",
_ => "план",
}
}
/// One mark in a line: its area's category and role, the channel, the quality, the trust, the age
/// and the priority the planner prices it at.
pub fn mark_line(m: &ReconReport) -> String {
let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default();
format!(
"Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}",
m.id,
category_name(m.category),
role,
source_name(m.source),
quality_name(m.quality),
confidence_name(m.confidence),
m.age / 20,
m.priority
)
}
/// Why the mark has the priority it does: the observed role, the freshness and the quality, each
/// with the weight the planner gives it, summing to the priority. The unit's true importance is not
/// in it — only what the look reported.
pub fn mark_reason(m: &ReconReport) -> String {
let category = Category::from_key(m.category).unwrap_or(Category::Unknown);
let quality = Quality::from_key(m.quality).unwrap_or(Quality::Coarse);
let role = m.role.and_then(crate::sim::battery::RadarRole::from_key);
let (freshness, quality_w, role_w) = priority_parts(m.confidence, quality, category, role);
let role_txt = match m.role {
Some(key) => format!("роль «{}»", role_name(key)),
None => format!("категория «{}»", category_name(m.category)),
};
format!(
"приоритет {} = свежесть {}×4 + качество {}×3 + роль {}: {} {}, {}",
m.priority,
freshness,
quality_w,
role_w,
confidence_name(m.confidence),
quality_name(m.quality),
role_txt
)
}
/// One sortie in a line: its phase, the zones left and when its pending report is due.
pub fn sortie_line(s: &ReconSortieReport) -> String {
let mut text = format!("Разведчик {}: {}", s.drone, phase_name(s.phase));
if s.zones_left > 0 {
text += &format!(" · зон осталось {}", s.zones_left);
}
if let Some(due) = s.report_in {
text += &format!(" · донесение через {} с", due / 20);
}
text
}
/// The coarse phase of the recon flight for the battle UI: a report going home now, else aircraft
/// still looking, else the flight finishing. `None` when no sortie is out. It says nothing of what
/// the enemy learned — only what its visible aircraft are doing.
pub fn battle_phase(pic: &EnemyPictureReport) -> Option<&'static str> {
if pic.recon_sorties.iter().any(|s| s.phase == "reporting") {
Some("донесение")
} else if pic.recon_sorties.iter().any(|s| s.phase == "outbound" || s.phase == "looking") {
Some("разведка")
} else if !pic.recon_sorties.is_empty() {
Some("завершение")
} else {
None
}
}
/// The whole picture for the debug command and the after-action review: the sorties and their
/// phases, then the marks best-first with the reason each outranks the rest, then the drones aimed
/// at a mark. Explicitly the enemy's belief, not the truth; never the normal HUD.
pub fn picture_lines(pic: &EnemyPictureReport) -> Vec<String> {
let mut lines = Vec::new();
if pic.recon.is_empty() && pic.recon_sorties.is_empty() {
lines.push("Разведки не было: противник не высылал разведчиков и ничего не запомнил.".into());
return lines;
}
lines.push(format!(
"Картина противника (debug/разбор): отметок {}, разведчиков в воздухе {}",
pic.recon.len(),
pic.recon_sorties.len()
));
for s in &pic.recon_sorties {
lines.push(sortie_line(s));
}
let mut marks: Vec<&ReconReport> = pic.recon.iter().collect();
marks.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
for m in marks {
lines.push(mark_line(m));
lines.push(format!(" ↳ {}", mark_reason(m)));
}
for a in pic.aims.iter().filter(|a| a.recon) {
lines.push(format!(
"Дрон {} целится в отметку {} (приоритет {}, {})",
a.drone,
a.unit,
a.priority.unwrap_or(0),
intent_name(a.intent)
));
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport};
use glam::DVec3;
fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport {
let cat = Category::from_key(category).unwrap();
let qual = Quality::from_key(quality).unwrap();
let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key);
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 }
}
fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option<u64>) -> ReconSortieReport {
ReconSortieReport { drone, phase, zones_left, report_in }
}
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 }
}
// The reason names all three factors with the planner's own weights, and they sum to the priority.
#[test]
fn the_reason_is_the_observed_role_freshness_and_quality() {
let m = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Confirmed, 100);
let reason = mark_reason(&m);
assert_eq!(m.priority, 4 * 4 + 2 * 3 + 3);
assert!(reason.contains("приоритет 25 = свежесть 4×4 + качество 2×3 + роль 3"), "{reason}");
assert!(reason.contains("подтверждена") && reason.contains("уточнённая") && reason.contains("роль «наведения»"), "{reason}");
// A coarse, doubtful, unknown mark: every part is zero, and the reason says so.
let weak = mark(0x1000_0002, "unknown", None, "coarse", Confidence::Doubtful, 5000);
assert_eq!(weak.priority, 0);
let weak_reason = mark_reason(&weak);
assert!(weak_reason.contains("свежесть 0×4 + качество 0×3 + роль 0"), "{weak_reason}");
assert!(weak_reason.contains("сомнительна") && weak_reason.contains("категория «не определено»"), "{weak_reason}");
}
// A fresh modest mark can outrank a stale big one: the reason reflects the age, not the truth.
#[test]
fn a_fresh_modest_mark_outranks_a_stale_big_one() {
let stale_big = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Doubtful, 5000);
let fresh_modest = mark(0x1000_0002, "gun", None, "coarse", Confidence::Confirmed, 100);
assert!(fresh_modest.priority > stale_big.priority, "{} vs {}", fresh_modest.priority, stale_big.priority);
let fresh_id = fresh_modest.id;
let lines = picture_lines(&picture(vec![stale_big, fresh_modest], Vec::new(), Vec::new()));
let first = lines.iter().position(|l| l.starts_with("Отметка")).unwrap();
assert!(lines[first].contains(&format!("Отметка {fresh_id}")), "the fresh modest mark did not lead: {lines:?}");
}
#[test]
fn the_phase_reads_recon_report_and_done() {
assert_eq!(phase_name("outbound"), "разведка");
assert_eq!(phase_name("reporting"), "донесение");
assert_eq!(phase_name("done"), "завершение");
let reporting = picture(Vec::new(), vec![sortie(0x3000_0001, "reporting", 0, Some(40)), sortie(0x3000_0002, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&reporting), Some("донесение"));
let looking = picture(Vec::new(), vec![sortie(0x3000_0001, "outbound", 2, None)], Vec::new());
assert_eq!(battle_phase(&looking), Some("разведка"));
let done = picture(Vec::new(), vec![sortie(0x3000_0001, "done", 0, None)], Vec::new());
assert_eq!(battle_phase(&done), Some("завершение"));
assert_eq!(battle_phase(&picture(Vec::new(), Vec::new(), Vec::new())), None);
assert!(sortie_line(&sortie(0x3000_0001, "reporting", 1, Some(40))).contains("донесение через 2 с"));
}
#[test]
fn an_empty_picture_says_there_was_no_recon() {
let lines = picture_lines(&picture(Vec::new(), Vec::new(), Vec::new()));
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("Разведки не было"), "{lines:?}");
}
// The review shows the marks with their reasons and the drones aimed at them; the ids are the
// synthetic ones, and nothing of the unit's truth (kind, health, exact place) is in the report.
#[test]
fn the_review_lists_marks_reasons_and_recon_aims() {
let m = mark(0x1000_0001, "launcher", None, "coarse", Confidence::Probable, 1000);
let mid = m.id;
let aim = AimReport { drone: 7, unit: mid, intent: "sead", since: 900, switches: 0, confidence: Some(Confidence::Probable), recon: true, priority: Some(m.priority) };
let unit_aim = AimReport { drone: 8, unit: 3, intent: "plan", since: 900, switches: 0, confidence: Some(Confidence::Confirmed), recon: false, priority: None };
let lines = picture_lines(&picture(vec![m], vec![sortie(0x3000_0001, "outbound", 1, None)], vec![aim, unit_aim]));
assert!(lines.iter().any(|l| l.contains(&format!("Отметка {mid}")) && l.contains("пусковая")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("↳") && l.contains("приоритет")), "{lines:?}");
assert!(lines.iter().any(|l| l.contains("Дрон 7 целится в отметку") && l.contains("подавление ПВО")), "{lines:?}");
// A unit contact's aim is not a recon aim: it is not listed here.
assert!(!lines.iter().any(|l| l.contains("Дрон 8")), "{lines:?}");
// No true unit id leaks: the mark id is synthetic, far above any real unit's.
assert!(mid >= 0x1000_0000);
}
#[test]
fn every_public_name_is_translated() {
for key in ["unknown", "radar", "launcher", "gun", "ew", "support"] {
assert_ne!(category_name(key), key, "{key}");
}
for key in ["multi", "search", "engagement", "height"] {
assert_ne!(role_name(key), key, "{key}");
}
for key in ["flyby", "emission", "jamming", "launch"] {
assert_ne!(source_name(key), key, "{key}");
}
assert_ne!(quality_name("coarse"), "coarse");
assert_ne!(quality_name("refined"), "refined");
}
}
+1 -1
View File
@@ -1210,7 +1210,7 @@ mod engine_tests {
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400_eject"]);
assert!(out.engines.is_empty());
out = Out::default();
p.t = 16.0;
p.t = 10.0 + crate::sim::strike::EJECT_TICKS as f64 + 1.0;
p.sounds(&rec, DVec3::ZERO, &mut out);
p.engines(&rec, DVec3::ZERO, false, &mut out);
assert_eq!(out.sounds.iter().map(|s| s.0).collect::<Vec<_>>(), vec!["airdef:launch.s400"]);
+3 -2
View File
@@ -36,9 +36,10 @@ fn names() -> Vec<String> {
impl AirDef {
/// The scenario as text.
fn scenario_text(&self, name: &str, fresh: bool) -> String {
pub(crate) fn scenario_text(&self, name: &str, fresh: bool) -> String {
let mut text = format!("scenario {VERSION}\nname {name}\nworld {}\n", self.state_key());
text += &self.state_text(fresh, false);
// A scenario is a start state: its body is the layout, not the raid a save happened to catch.
text += &self.state_text_with(fresh, false, false);
text += &format!("seed {}\nwave {}\n", self.sim.rng.state(), self.wave.text());
text
}
+39
View File
@@ -54,6 +54,12 @@ pub(super) struct Result {
pub missed: u32,
/// Missiles fired by the heavy systems (S-400, S-500, Patriot).
pub heavy: u32,
/// Interceptors whose fuse ran without a kill; whose life ran out; that lost their target on the way;
/// and that fell below their guidance speed after motor burnout (#120's coast/energy tally).
pub fuse_missed: u32,
pub expired: u32,
pub orphaned: u32,
pub energy_lost: u32,
pub by_kind: Vec<(DroneKind, u32, u32)>,
pub tally: String,
/// Drones that vanished short of their aim without being shot down: kind, where, how far from the aim.
@@ -322,6 +328,10 @@ pub(super) fn fly(s: &Setup) -> Result {
result.crashes = sim.crashes;
result.blocked = sim.tally.blocked;
result.scrubbed = sim.tally.scrubbed;
result.fuse_missed = sim.tally.missed;
result.expired = sim.tally.expired;
result.orphaned = sim.tally.orphaned;
result.energy_lost = sim.tally.energy_lost;
result.leaked = sim.hits;
let mut kinds: HashMap<DroneKind, (u32, u32)> = HashMap::new();
for h in &gone_unkilled {
@@ -514,6 +524,35 @@ fn one_raid() {
}
}
/// Issue #120's wider sampling: battery sizes, launch-range bounds and the target classes of a raid
/// of 36, on the same seeds against the same cluster mix as `one_raid`. Prints CSV rows:
/// `variant,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind`.
/// `SEEDS=1-8 cargo test --release issue_120_grid -- --ignored --nocapture` (SEEDS overrides the seed range).
#[test]
#[ignore]
fn issue_120_grid() {
let seeds = match std::env::var("SEEDS") {
Ok(v) => {
let (a, b) = v.split_once('-').expect("SEEDS is a range like 1-8");
let a: u64 = a.parse().expect("SEEDS start");
let b: u64 = b.parse().expect("SEEDS end");
a..=b
}
Err(_) => 1..=8,
};
for (variant, sams, dist) in [("batt10", 10usize, 500.0), ("batt20", 20, 500.0), ("batt50", 50, 500.0), ("near200", 20, 200.0), ("far1500", 20, 1500.0), ("hills20", 20, 500.0)] {
for seed in seeds.clone() {
let mut s = Setup::new(sams, false, seed);
s.size = 36;
s.dist = dist;
s.hilly = variant == "hills20";
let r = fly(&s);
let kinds = r.by_kind.iter().map(|k| format!("{:?}:{}", k.0, k.1)).collect::<Vec<_>>().join(";");
eprintln!("{variant},{seed},{sams},{dist},{},{},{},{},{},{},{},{},{},{},{},{},{},{}", r.launched, r.kills, r.leaked, r.missiles, r.heavy, r.ticks, r.blocked, r.scrubbed, r.crashes, r.fuse_missed, r.expired, r.orphaned, r.energy_lost, kinds);
}
}
}
/// Far launches over mountains where only a disc round the player is known: who crashes, where and how often.
/// `cargo test --release far_table -- --ignored --nocapture` (DISC=300 sets the radius, 0 for all known).
#[test]
+258 -11
View File
@@ -33,8 +33,199 @@ impl RadarRole {
pub fn from_key(key: &str) -> Option<Self> {
match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None }
}
pub fn authorizes(self) -> bool { matches!(self, Self::Multifunction | Self::Engagement) }
pub(super) fn reach_factor(self) -> f64 { match self { Self::Multifunction => 1.0, Self::Search => 1.15, Self::Engagement => 0.8, Self::Height => 1.05 } }
pub fn profile(self) -> RadarProfile { RadarProfile::of(self) }
pub fn authorizes(self) -> bool { self.profile().products & RadarProfile::FIRE_BIT != 0 }
}
/// What a measurement is good for. A search plot is a warning, a refined
/// plot fixes a matched contact, and a fire plot is a confirmed measurement
/// a launcher may use. Quality (0..100) is separate from identification:
/// a well-measured track can still be an unknown type (#133).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Measure {
#[default]
Search,
Refine,
Fire,
}
impl Measure {
pub fn name(self) -> &'static str {
match self { Self::Search => "обзор", Self::Refine => "уточнение", Self::Fire => "пригоден для пуска" }
}
pub fn allows_fire(self) -> bool { self == Self::Fire }
}
/// A radar profile: a stable catalog identity over the existing `SamKind::Radar`.
/// The numbers are fictional game settings. The silhouette is shared with the
/// existing radar model: this slice does not add art (a separate owner's zone).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadarProfile {
/// Stable content ID; old saves only have `RadarRole`, which maps here.
pub id: &'static str,
pub name: &'static str,
/// Allowed measurement products (`SEARCH_BIT`, `REFINE_BIT`, `FIRE_BIT`).
pub products: u8,
/// Ticks for the beam to go round.
pub cycle: u32,
/// Electronic revisit of held contacts between beam passes.
pub agile: bool,
/// Extra antenna height over the unit's spec mast (blocks).
pub mast: f64,
/// Search reach, a factor of the unit's sensor.
pub reach: f64,
/// Local search radius, a factor of the unit's sensor (1: the whole reach).
pub local: f64,
/// Simultaneous refined/fire channels; 0 means only search plots.
pub channels: u8,
/// Measurement error scale (blocks) and its growth per block of range.
pub sigma: f64,
pub spread: f64,
/// Vertical error as a share of the horizontal one.
pub vertical: f64,
pub deployment: &'static str,
/// The limit the profile deliberately keeps, shown in the UI.
pub limit: &'static str,
}
impl RadarProfile {
pub const SEARCH_BIT: u8 = 1;
pub const REFINE_BIT: u8 = 2;
pub const FIRE_BIT: u8 = 4;
pub const MULTI: RadarProfile = RadarProfile {
id: "radar_multi",
name: "многофункциональная",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 140,
agile: false,
mast: 0.0,
reach: 1.0,
local: 0.55,
channels: 3,
sigma: 0.7,
spread: 0.004,
vertical: 0.75,
deployment: "стационарная",
limit: "универсальная: уступает специализированным по циклу, каналам и точности",
};
pub const SEARCH: RadarProfile = RadarProfile {
id: "radar_search",
name: "дальнего обзора",
products: Self::SEARCH_BIT,
cycle: 170,
agile: false,
mast: 0.0,
reach: 1.15,
local: 1.0,
channels: 0,
sigma: 1.0,
spread: 0.008,
vertical: 1.0,
deployment: "крупная стационарная антенна",
limit: "редкие грубые отметки; своего права на пуск не даёт",
};
pub const ENGAGEMENT: RadarProfile = RadarProfile {
id: "radar_track",
name: "сопровождения",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 70,
agile: true,
mast: 0.0,
reach: 0.8,
local: 0.12,
channels: 2,
sigma: 0.35,
spread: 0.002,
vertical: 0.6,
deployment: "мобильная панель",
limit: "локальный поиск и два канала; сеть лишь подсказывает, измеряет станция",
};
pub const HEIGHT: RadarProfile = RadarProfile {
id: "radar_height",
name: "мачта низких высот",
products: Self::SEARCH_BIT | Self::REFINE_BIT,
cycle: 140,
agile: false,
mast: 8.0,
reach: 1.05,
local: 0.15,
channels: 3,
sigma: 0.5,
spread: 0.003,
vertical: 0.35,
deployment: "шасси с поднятой антенной",
limit: "уточняет низкие контакты над рельефом; сквозь препятствия не видит и права на пуск не даёт",
};
/// A weapon's own radar: it measures for its own fire control. Kept out of
/// the separate radar roles so embedded radars keep working as before.
pub const EMBEDDED: RadarProfile = RadarProfile {
id: "embedded",
name: "РЛС комплекса",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 0,
agile: false,
mast: 0.0,
reach: 1.0,
local: 1.0,
channels: 0,
sigma: 0.8,
spread: 0.004,
// The old embedded scan drew its vertical error at half the horizontal one.
vertical: 0.5,
deployment: "встроенная",
limit: "обслуживает только свой комплекс",
};
pub fn of(role: RadarRole) -> Self {
match role {
RadarRole::Multifunction => Self::MULTI,
RadarRole::Search => Self::SEARCH,
RadarRole::Engagement => Self::ENGAGEMENT,
RadarRole::Height => Self::HEIGHT,
}
}
/// Old saves write the role key; new saves write the stable profile ID.
/// Both read here, so a legacy `search` line maps to `radar_search`.
pub fn from_id(id: &str) -> Option<Self> {
match id {
"radar_multi" | "multi" => Some(Self::MULTI),
"radar_search" | "search" => Some(Self::SEARCH),
"radar_track" | "engagement" => Some(Self::ENGAGEMENT),
"radar_height" | "height" => Some(Self::HEIGHT),
_ => None,
}
}
pub fn role(self) -> RadarRole {
match self.id {
"radar_search" => RadarRole::Search,
"radar_track" => RadarRole::Engagement,
"radar_height" => RadarRole::Height,
_ => RadarRole::Multifunction,
}
}
pub fn allows(self, product: Measure) -> bool {
match product {
Measure::Search => self.products & Self::SEARCH_BIT != 0,
Measure::Refine => self.products & Self::REFINE_BIT != 0,
Measure::Fire => self.products & Self::FIRE_BIT != 0,
}
}
pub fn products_text(self) -> &'static str {
match self.products {
p if p == Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT => "обзор, уточнение, пуск",
p if p == Self::SEARCH_BIT | Self::REFINE_BIT => "обзор, уточнение",
p if p == Self::SEARCH_BIT | Self::FIRE_BIT => "обзор, пуск",
_ => "обзор",
}
}
}
impl Sam {
/// The profile this unit measures with. Embedded radars keep their kind's
/// own scan and reach; only the separate radar uses a selectable profile.
pub fn radar_profile(&self) -> RadarProfile {
if self.kind == SamKind::Radar { RadarProfile::of(self.radar_role) } else { RadarProfile::EMBEDDED }
}
}
impl Sam {
@@ -113,7 +304,22 @@ mod tests {
}
fn track(now: u64) -> Track {
Track { id: 42, kind: DroneKind::Kh101, pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }
Track {
id: 42,
class: ClassEst::Firm(Class::Cruise),
pos: DVec3::new(0.0, 100.0, -200.0),
vel: DVec3::ZERO,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
}
}
#[test]
@@ -251,6 +457,24 @@ mod tests {
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach);
}
#[test]
fn profiles_have_stable_ids_and_deliberately_different_limits() {
let search = RadarRole::Search.profile();
let height = RadarRole::Height.profile();
let engagement = RadarRole::Engagement.profile();
let multi = RadarRole::Multifunction.profile();
assert_eq!((search.id, height.id, engagement.id, multi.id), ("radar_search", "radar_height", "radar_track", "radar_multi"));
assert!(!RadarRole::Search.authorizes() && !RadarRole::Height.authorizes() && RadarRole::Engagement.authorizes());
assert_eq!(search.products, RadarProfile::SEARCH_BIT);
assert_eq!(height.products, RadarProfile::SEARCH_BIT | RadarProfile::REFINE_BIT);
assert_ne!(search.cycle, engagement.cycle);
assert!(height.mast > search.mast && height.mast > engagement.mast);
assert!(engagement.channels < multi.channels && height.channels > 0 && search.channels == 0);
assert!(search.local > height.local && height.local > engagement.local);
assert_eq!(RadarProfile::from_id(search.id), Some(search));
assert_eq!(RadarProfile::from_id("search"), Some(search), "legacy role keys map to profiles");
}
#[test]
fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() {
let mut sim = Sim::new(3);
@@ -285,7 +509,7 @@ mod tests {
mod emission_tests {
use super::*;
#[test]
fn silence_accepts_network_without_inventing_own_measurements_and_contacts_age() {
fn silence_discloses_nothing_and_contacts_age_and_channels_still_place_a_unit() {
let mut sim = Sim::new(121);
sim.tick = 20;
let mut source = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
@@ -294,29 +518,52 @@ mod emission_tests {
receiver.radar_on = false;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -100.0), DVec3::Z, DVec3::ZERO);
let id = sim.drones[0].id;
source.tracks.push(Track { id, kind: DroneKind::Kh101, pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false });
source.tracks.push(Track {
id,
class: ClassEst::Firm(Class::Cruise),
pos: sim.drones[0].pos,
vel: DVec3::ZERO,
tick: 20,
own_tick: 20,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 200,
hits: 2,
locked: false,
});
sim.sams.extend([source, receiver]);
let mut ground = Ground::default();
sim.update_sight(&mut ground);
assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
assert!(!sim.sams[1].radar_up());
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
// The emitting source is fixed by the drone; the silent receiver is not.
let picture = sim.picture_of_defences();
assert_eq!(picture.len(), 1);
assert_eq!((picture[0].id, picture[0].at), (1, DVec3::ZERO));
assert_eq!(picture[0].seen, ew::Seen::Emission);
sim.sams[0].radar_on = false;
// 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.tick = 40;
sim.update_sight(&mut ground);
assert_eq!(sim.known_units(), vec![(1, DVec3::ZERO)]);
assert_eq!(sim.sams[1].track(id).unwrap().tick, 20);
let picture = sim.picture_of_defences();
assert_eq!(picture.len(), 1);
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.tick = 60;
sim.update_sight(&mut ground);
assert_eq!(sim.known_units(), vec![(1, DVec3::new(400.0, 0.0, 0.0))]);
assert_eq!(sim.picture_of_defences()[0].at, DVec3::new(400.0, 0.0, 0.0));
sim.sams[0].radar_on = false;
// Other disclosure channels still reveal a silent unit.
sim.intel.revealed.push((2, DVec3::ZERO, 60));
assert!(Sim::enemy_knows(&sim.sams[1], &sim.known_units()));
sim.intel.observe(&sim.sams[1], 60, ew::Seen::Launch);
assert!(sim.known_live(2));
sim.tick = 6060;
assert!(sim.known_units().is_empty());
assert!(sim.picture_of_defences().is_empty(), "an unrefreshed contact never ages out");
}
}
+84 -1
View File
@@ -3,7 +3,7 @@
//! Balance and rendering remain in `DroneSpec` and `SamSpec`: the catalog
//! refers to those typed definitions instead of copying their values. The
//! first eleven drone entries retain the historical positional wave-save order.
use super::{DroneKind, SamKind};
use super::{battery::RadarProfile, battery::RadarRole, battery::SamMode, DroneKind, SamKind};
#[derive(Clone, Copy, Debug)]
pub struct Aircraft {
@@ -19,6 +19,28 @@ impl Aircraft {
pub fn id(self) -> &'static str { self.kind.spec().key }
}
/// A variant of a complex: a configuration over an existing kind, deployed
/// under its own command/menu id. Not new balance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnitVariant {
/// Existing command/menu key; changing it requires an explicit migration.
pub id: &'static str,
pub kind: SamKind,
pub mode: SamMode,
pub role: RadarRole,
/// The deploy menu's row.
pub label: &'static str,
/// What the configuration is for (shown in the deploy menu).
pub description: &'static str,
}
impl UnitVariant {
/// The typed radar profile behind a separate radar variant.
pub fn radar_profile(self) -> Option<RadarProfile> {
(self.kind == SamKind::Radar).then(|| RadarProfile::of(self.role))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroundStrike {
/// Game-only RM48U coordinate-strike profile for S-400. Evidence: official agency report,
@@ -59,6 +81,7 @@ pub mod sound {
// Generated entries keep the historical raid and unit ordering.
include!("catalog_entries.rs");
include!("unit_variants_generated.rs");
/// Existing positional serialization makes the first entries' order part of the save format.
const fn raid_count() -> usize {
@@ -132,6 +155,10 @@ pub fn deploy_item(id: &str) -> Option<SamKind> {
UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind)
}
pub fn variant(id: &str) -> Option<&'static UnitVariant> {
VARIANTS.iter().find(|variant| variant.id == id)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,4 +199,60 @@ mod tests {
assert_eq!(kinds, SamKind::ALL.into_iter().collect());
assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]);
}
/// 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
/// order is part of the UI's tested behaviour.
#[test]
fn variants_configure_existing_units_under_free_ids() {
let ids: Vec<&str> = VARIANTS.iter().map(|v| v.id).collect();
assert_eq!(ids, ["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]);
for v in VARIANTS {
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!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
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)));
if v.kind == SamKind::Radar {
let profile = v.radar_profile().expect("a radar variant has a profile");
assert_eq!(profile.id, v.id, "the stable profile ID is the variant ID");
assert_eq!(profile.role(), v.role);
assert!(profile.channels <= 3 && profile.cycle > 0);
} else {
assert!(v.radar_profile().is_none());
}
}
let launcher = variant("s400_launcher").unwrap();
assert_eq!((launcher.kind, launcher.mode, launcher.role), (SamKind::S400, SamMode::LauncherOnly, RadarRole::Multifunction));
assert_eq!(VARIANTS[4].id, "radar_height");
assert!(variant("miss").is_none() && variant("s400").is_none());
}
/// The catalog is the only copy of the numbers: a kind without a row, or a row under
/// another kind, would be a silent balance change.
#[test]
fn generated_specs_cover_every_kind_and_keep_their_keys() {
let mut drones = HashSet::new();
let mut drone_keys = HashSet::new();
for (kind, key) in super::super::DRONE_SPEC_KEYS {
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
assert!(drones.insert(kind), "duplicate drone profile {kind:?}");
assert!(drone_keys.insert(key), "duplicate drone save key {key}");
assert!(kind.spec().rcs > 0.0 && kind.spec().launch_sound.starts_with("airdef:"));
}
assert_eq!(drones, DroneKind::ALL.into_iter().collect());
let mut missiles = HashSet::new();
for (kind, model) in super::super::MISSILE_SPEC_MODELS {
assert_eq!(kind.spec().model, model, "profile/model mismatch for {kind:?}");
assert!(missiles.insert(kind), "duplicate missile profile {kind:?}");
}
let mut units = HashSet::new();
let mut unit_keys = HashSet::new();
for (kind, key) in super::super::units::UNIT_SPEC_KEYS {
assert_eq!(kind.spec().key, key, "profile/key mismatch for {kind:?}");
assert!(units.insert(kind), "duplicate unit profile {kind:?}");
assert!(unit_keys.insert(key), "duplicate unit save key {key}");
}
assert_eq!(units, SamKind::ALL.into_iter().collect());
}
}
+1
View File
@@ -31,4 +31,5 @@ pub const UNITS: &[Unit] = &[
Unit { kind: SamKind::Tzm, deploy_item: "airdef:deploy_tzm" },
Unit { kind: SamKind::Ew, deploy_item: "airdef:deploy_ew" },
Unit { kind: SamKind::Light, deploy_item: "airdef:deploy_light" },
Unit { kind: SamKind::Optical, deploy_item: "airdef:deploy_optical" },
];
+8 -30
View File
@@ -54,6 +54,10 @@ impl Part {
Part::Comms => "Св",
}
}
/// The short label as this kind of unit reads it: a passive post has optics, not a radar.
pub fn short_on(self, kind: SamKind) -> &'static str {
if self == Part::Sensor && kind == SamKind::Optical { "Опт" } else { self.short() }
}
fn index(self) -> usize {
self as usize
}
@@ -61,7 +65,8 @@ impl Part {
pub fn on(self, kind: SamKind) -> bool {
let spec = kind.spec();
match self {
Part::Sensor => spec.sensor > 0.0,
// A passive optical post has a sensor without radar reach: it can be damaged and blinded too.
Part::Sensor => spec.sensor > 0.0 || kind == SamKind::Optical,
Part::Mount => kind.armed() && kind != SamKind::Light && (spec.missile.is_some() || spec.gun.is_some()),
Part::Launcher => spec.missile.is_some(),
Part::Gun => spec.gun.is_some(),
@@ -112,30 +117,6 @@ impl Comps {
pub fn whole(&self) -> bool {
self.0.iter().all(|&v| v >= 1.0)
}
/// Parts of this kind that are not whole, as "РЛС 40%, ходовая отказ".
pub fn describe(&self, kind: SamKind) -> String {
Part::ALL
.iter()
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
.map(|p| match self.state(*p) {
PartState::Failed => format!("{} отказ", p.short()),
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The weakest part alone, for a one-line status (the full list is on the monitor).
pub fn worst(&self, kind: SamKind) -> String {
Part::ALL
.iter()
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
.min_by(|a, b| self.get(**a).total_cmp(&self.get(**b)))
.map(|p| match self.state(*p) {
PartState::Failed => format!("{} отказ", p.short()),
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
})
.unwrap_or_default()
}
}
/// Health points an object loses at the centre of a blast.
@@ -443,9 +424,6 @@ impl Sam {
pub fn part_state(&self, p: Part) -> PartState {
if p.on(self.kind) { self.comps.state(p) } else { PartState::Ok }
}
pub fn parts_text(&self) -> String {
self.comps.describe(self.kind)
}
/// The aiming drive's share of its speed: a failed one doesn't turn at all.
pub(super) fn drive_fit(&self) -> f64 {
let h = self.part(Part::Mount);
@@ -461,7 +439,7 @@ impl Sam {
0.5 + 0.5 * self.part(Part::Gun)
}
/// Its launcher's cells still good: a damaged one holds fewer missiles.
pub(super) fn cells(&self) -> u32 {
pub fn cells(&self) -> u32 {
let Some(load) = &self.kind.spec().missile else { return 0 };
let h = self.part(Part::Launcher);
if h <= 0.0 { 0 } else { ((load.magazine as f64 * (0.4 + 0.6 * h)).ceil() as u32).clamp(1, load.magazine) }
@@ -475,7 +453,7 @@ impl Sam {
}
}
/// Ticks a reload takes: longer with a damaged launcher.
pub(super) fn reload_time(&self) -> u32 {
pub fn reload_time(&self) -> u32 {
let r = self.kind.spec().reload.max(1);
(r as f64 * (1.0 + 1.5 * (1.0 - self.part(Part::Launcher)))).round() as u32
}
+31 -10
View File
@@ -85,6 +85,11 @@ impl Doctrine {
if near <= slack {
return true;
}
// One blip carries no measured course (#133): nothing says the contact passes the
// object by, so it is not ruled out as a threat on a velocity that is not there.
if track.hits <= 1 {
return true;
}
let (vx, vz) = (track.vel.x, track.vel.z);
let speed = vx.hypot(vz);
// Closing, and the line of flight passes the object within the slack.
@@ -97,23 +102,24 @@ impl Doctrine {
(if self.in_sector(pos, track.est(now)) { 0 } else { OUT_SECTOR }) | (if self.guards.is_empty() || self.threatens(track, now).is_some() { 0 } else { NO_THREAT })
}
/// What matters enough to spend the reserve: a ballistic missile, or anything about to hit.
pub fn matters(d: &Drone) -> bool {
d.kind.spec().class == Class::Ballistic || why::arrival(d) < why::URGENT
/// What matters enough to spend the reserve: a ballistic missile (as the track's estimate
/// classes it, an unidentified contact does not count), or anything about to hit.
pub fn matters(d: &Drone, class: ClassEst) -> bool {
class.class() == Some(Class::Ballistic) || why::arrival(d) < why::URGENT
}
/// The reserve holds the launch back: the magazine is at the reserve and the target doesn't matter.
pub fn reserve_blocks(&self, missiles: u32, d: &Drone) -> u8 {
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d) { RESERVE } else { 0 }
pub fn reserve_blocks(&self, missiles: u32, d: &Drone, class: ClassEst) -> u8 {
if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d, class) { RESERVE } else { 0 }
}
/// Interceptors this doctrine asks for on `d`: `why::needed` by default, the base only when economical, one more when heavy.
pub fn needed(&self, d: &Drone) -> u32 {
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
pub fn needed(&self, d: &Drone, class: ClassEst) -> u32 {
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
match self.salvo {
Salvo::Economy => base,
Salvo::Normal => why::needed(d),
Salvo::Heavy => why::needed(d) + 1,
Salvo::Normal => why::needed(d, class),
Salvo::Heavy => why::needed(d, class) + 1,
}
}
@@ -162,7 +168,22 @@ mod tests {
use super::*;
fn track(pos: DVec3, vel: DVec3) -> Track {
Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
Track {
id: 1,
class: ClassEst::Unknown,
pos,
vel,
tick: 0,
own_tick: 0,
source: 0,
product: battery::Measure::Search,
quality: 40,
own_product: battery::Measure::Search,
own_quality: 0,
ttl: 100,
hits: 3,
locked: false,
}
}
#[test]
File diff suppressed because it is too large Load Diff
+1717 -76
View File
File diff suppressed because it is too large Load Diff
+218 -37
View File
@@ -4,14 +4,6 @@
//! reloads to the systems that wait, nearest first, and back.
use super::*;
/// How near a depot a system reloads straight from it.
const DEPOT_REACH: f64 = 60.0;
/// How near a truck must come to hand a reload over, or to load up at a depot.
const HANDOVER: f64 = 10.0;
/// What a truck carries.
const TRUCK_LOAD: u32 = 2;
const STOCK_LIMIT: u32 = 1_000_000;
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,
@@ -127,41 +119,59 @@ impl Sim {
let at = truck.pos;
let truck_id = truck.id;
// A return is picked up physically; its cargo remains marked until a depot accepts it.
// The return keeps its priority only while it can actually proceed (#128): a carrier
// holding a reserved round needs a depot with room in reach, an empty one a system
// ready to hand a round over (whole, deployed, not claimed by another truck, a
// reachable route). A return that is merely claimed but impossible used to clear the
// job and stop the truck, starving independent supply requests; the claim now stays
// untouched and only real RM48U demand pulls the truck away from its watch.
let return_cargo = truck.return_cargo && truck.ground_stock > 0;
let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD;
let return_work = truck.return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return));
if return_work {
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 truck.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)))
} else {
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)))
}.map(|s| (s.id, s.pos));
self.sams[t].job = target.map(|x| x.0);
if let Some((id, to)) = target {
if at.distance(to) > HANDOVER {
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
self.sams[t].ground_stock -= 1;
self.sams[t].return_cargo = false;
} else {
self.sams[j].ground_rounds -= 1;
self.sams[j].ground_return = false;
self.sams[t].ground_stock += 1;
self.sams[t].return_cargo = true;
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
self.sams[t].air_48n6_stock -= 1;
self.sams[j].missiles += 1;
}
let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && 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 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)))
} 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)))
} else {
None
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = target {
self.sams[t].job = Some(id);
if at.distance(to) > HANDOVER {
let side = horizontal(at - to).normalize_or(DVec3::X) * (HANDOVER * 0.6);
self.order_move_near(t, to + side, 3.5);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
self.sams[t].ground_stock -= 1;
self.sams[t].return_cargo = false;
} else {
self.sams[j].ground_rounds -= 1;
self.sams[j].ground_return = false;
self.sams[t].ground_stock += 1;
self.sams[t].return_cargo = true;
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
self.sams[t].air_48n6_stock -= 1;
self.sams[j].missiles += 1;
}
self.sams[t].job = None;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
self.sams[t].job = None;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
continue;
}
if claim_pending {
// 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.
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 == SamKind::Depot && s.alive() && s.ground_stock > 0));
if !supply_demand {
self.sams[t].job = None;
continue;
}
}
// Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed
// after loading a save; the request and physical cargo survive independently.
let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 ||
@@ -184,6 +194,8 @@ impl Sim {
let take = self.sams[t].ground_stock.min(STOCK_LIMIT - self.sams[j].ground_stock);
self.sams[j].ground_stock += take;
self.sams[t].ground_stock -= take;
// 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[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) {
self.sams[j].ground_stock -= 1;
@@ -196,6 +208,9 @@ impl Sim {
if self.sams[j].ground_rounds >= self.sams[j].cells() && self.sams[j].kind.spec().gun.is_none() { self.sams[j].empty = false; }
self.sams[j].ground_request = false;
self.sams[t].ground_stock -= 1;
// A round reserved for return redirected to a waiting request is no
// longer return cargo once the last one leaves the truck (#128).
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
self.sams[t].air_48n6_stock += displaced;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
@@ -416,4 +431,170 @@ mod tests {
assert!(!sim.sams[1].ground_request);
}
/// Runs `step_supply`, jumping the truck beside its current job each tick so handovers
/// resolve without a full drive (movement itself is covered by the lib round-trip tests).
/// Fails after 200 ticks if `done` never holds.
fn serve_until(sim: &mut Sim, truck: usize, mut done: impl FnMut(&Sim) -> bool) {
let mut ok = false;
for _ in 0..200 {
if done(sim) { ok = true; break; }
if let Some(id) = sim.sams[truck].job()
&& let Some(j) = sim.sams.iter().position(|s| s.id == id)
{
sim.sams[truck].pos = sim.sams[j].pos;
}
sim.sams[truck].state = SamState::Search;
sim.tick += 1;
sim.step_supply(&mut Out::default());
}
assert!(ok, "condition not reached within 200 step_supply calls");
}
/// #128: a return that is claimed but cannot proceed (here: the returning system is on the
/// move) must not stop the free truck with job=None; an independent typed request is served.
/// The claim stays, the rounds are conserved, and once the system stops the return completes.
#[test]
fn a_moving_return_claim_does_not_starve_an_independent_supply_request() {
let mut sim = Sim::new(5);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let b_id = sim.sams[b].id;
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
assert!(sim.order_move(a, DVec3::new(400.0, 70.0, 0.0)));
// The free truck loads one RM48U at the depot and starts driving to B within 100 ticks;
// before the fix it entered the return branch, found the moving A impossible and idled.
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
// The claim and the rounds are untouched by the fallback.
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock), (1, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Hand the round over to B; the full drive is exercised in the lib round-trip test.
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
assert!(!sim.sams[b].ground_request);
assert_eq!((sim.sams[b].missiles, sim.sams[truck].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// No request is left, so the truck holds its watch (a stock run aside): the pending
// return still outranks it and the claim survives.
for _ in 0..20 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
// A stops: the actual return is picked up and driven back to the depot.
sim.sams[a].state = SamState::Search;
sim.sams[a].dest = None;
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!((sim.sams[a].ground_rounds, sim.sams[a].missiles), (0, 4));
assert_eq!((sim.sams[truck].ground_stock, sim.sams[truck].air_48n6_stock), (1, 0));
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
/// #128 variant: the pickup is already claimed by another truck, so for this one the return
/// is impossible; it must turn to the waiting request instead of idling with job=None. A
/// dropped job (as after loading a save) is rebuilt, damaged trucks wait, and the repaired
/// claiming truck keeps the priority of the now executable return over the request.
#[test]
fn a_return_claimed_by_another_truck_leaves_the_supply_to_the_second_one() {
let mut sim = Sim::new(7);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 0.0), (SamKind::Tzm, 150.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, t2, t1) = (0usize, 1usize, 2usize, 3usize, 4usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
// The first truck claimed A's pickup earlier; both trucks start damaged: nothing
// moves, no round is lost, the claim waits.
sim.sams[t1].job = Some(a_id);
sim.sams[t1].comps.0[Part::Tracks as usize] = 0.0;
sim.sams[t2].comps.0[Part::Tracks as usize] = 0.0;
for _ in 0..30 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert_eq!(sim.sams[t2].job(), None);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[b].ground_rounds), (2, 0));
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Repaired, the second truck must not idle on the claimed return: depot first, then B.
sim.sams[t2].comps.0[Part::Tracks as usize] = 1.0;
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[t2].job() == Some(b_id) { started = true; break; }
}
assert!(started, "second truck never started the delivery to B");
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t2].ground_stock), (1, 1));
assert!(sim.sams[a].ground_return, "claimed return must survive the fallback");
// A save/load drops the job; the request and the cargo survive and the job is rebuilt.
sim.sams[t2].job = None;
serve_until(&mut sim, t2, |s| s.sams[t2].job() == Some(b_id));
// The claiming truck is repaired: the executable return has priority over the request,
// and the still-hauling second truck is not diverted from B.
sim.sams[t1].comps.0[Part::Tracks as usize] = 1.0;
serve_until(&mut sim, t1, |s| s.sams[t1].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 0);
assert_eq!(sim.sams[t2].job(), Some(b_id), "hauling truck must keep its supply job");
// B gets its round; the displaced air round rides along.
serve_until(&mut sim, t2, |s| s.sams[b].ground_rounds == 1);
assert_eq!((sim.sams[b].missiles, sim.sams[t2].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// And the picked-up return reaches the depot: everything is back except B's new round.
serve_until(&mut sim, t1, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[t1].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t1].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
}
/// #128 variant: the route to the returning system is marked unreachable, so the return is
/// impossible for now; the truck serves the request, and the return completes once the
/// route is passable again and the system is still waiting with its claim.
#[test]
fn an_unreachable_route_falls_back_to_supply_until_it_expires() {
let mut sim = Sim::new(9);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
sim.routes.unreachable.insert((sim.sams[truck].id, a_id), u64::MAX);
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
assert!(sim.sams[a].ground_return, "claim must survive the blocked route");
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
// The route is passable again: the waiting claim is picked up and returned.
sim.routes.unreachable.clear();
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
}
+318 -492
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -18,9 +18,9 @@ impl SamKind {
Family::Truck => 10,
}
}
/// A depot doesn't drive.
/// A depot and a fixed optical post don't drive.
pub fn mobile(self) -> bool {
self != SamKind::Depot
!matches!(self, SamKind::Depot | SamKind::Optical)
}
}
+263 -76
View File
@@ -146,6 +146,7 @@ const LONGEST_WAIT: f64 = 12_000.0;
pub(super) const WORK_PER_TICK: usize = 40_000;
/// The planner's grid over a raid: its corner, its cells' size and how many a side.
#[derive(Clone, Copy)]
pub(super) struct Grid {
pub(super) min: DVec3,
pub(super) cell: f64,
@@ -157,22 +158,20 @@ impl Grid {
let n = self.size;
((((p.x - self.min.x) / self.cell) as i32).clamp(0, n - 1), (((p.z - self.min.z) / self.cell) as i32).clamp(0, n - 1))
}
fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
pub(super) fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
DVec3::new(self.min.x + (i as f64 + 0.5) * self.cell, y, self.min.z + (j as f64 + 0.5) * self.cell)
}
}
/// The cheapest way over `grid` from `from` to `to` by its prices (A*): points along it, `to` last.
pub(super) fn plan_route(grid: &Grid, prices: &[f32], from: DVec3, to: DVec3) -> (Vec<DVec3>, usize) {
plan_route_on(grid, prices, None, from, to)
}
/// The land a route crosses: its height under each cell (NaN unknown), the climb a kind holds for long
/// (rise a block), and the height above which the land forces a drone up from its low altitude.
/// (rise a block), and the height above which the land forces a drone up from its low altitude. Unknown
/// land costs `unknown` per cell on top of the open ground: zero for a plan routed over land it is still
/// mapping, more than free for a replanned retarget (#127).
pub(super) struct Relief<'a> {
pub heights: &'a [f32],
pub slope: f32,
pub floor: f32,
pub unknown: f32,
}
/// [`plan_route`] over relief: a climb steeper than the kind holds is dear (a cliff or a ridge it would have to
@@ -219,6 +218,9 @@ pub(super) fn plan_route_on(grid: &Grid, prices: &[f32], relief: Option<&Relief>
price += (slope - r.slope) * 20.0 * len;
}
}
} else if r.unknown > 0.0 {
// Unmapped land is not free: the route prefers what the plan actually knew.
price += len * r.unknown;
}
}
let ng = g + price;
@@ -278,6 +280,13 @@ impl Sim {
return 0;
}
let smart = order.aim == Aim::Smart;
// The planner's picture of the layout: one snapshot for the whole order. It is
// read-only while the plan is built, and taking it per drone made a big second order
// quadratic in the force's size (#122); a map of contacts makes it linear in them (#127).
let picture = self.picture_of_defences();
// 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).
let leads = self.recon.leads(self.tick);
// A smart enemy comes from where its raids got through best.
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).
@@ -290,7 +299,7 @@ impl Sim {
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();
// 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) } else { Vec::new() };
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &picture) } else { Vec::new() };
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
@@ -306,7 +315,7 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim),
None => self.choose_target(kind, object, order.aim, &picture, &leads),
};
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;
@@ -314,6 +323,20 @@ impl Sim {
// Where it starts is provisional: the site's pad, once the site is placed.
let from = centre + DVec3::new(a.sin() * dist, height + self.rng.s() * 6.0, a.cos() * dist);
let mut d = self.make_drone(kind, from, horizontal(aim - from), aim);
// The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit
// chosen for the raid is the plan's objective, anything else is a marked object.
if let Some(id) = at_sam {
let confidence = picture
.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(self.tick)));
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));
} else {
d.intent = ew::Intent::Plan;
d.aim = ew::Aim::point(self.tick);
}
let range = spec.ballistic.map_or(order.dist, |far| far.max(order.dist));
let want = sites::want_index(&mut wants, centre, side, a, sites::SiteClass::of(kind), range, order.dist.max(120.0));
let pad = wants[want].jobs;
@@ -347,6 +370,11 @@ impl Sim {
waited: 0,
mapped: !smart,
});
// The smart enemy may send a small recon flight ahead of the strike -- physically in
// the air, not a pause: the strike is planned while they fly (#135).
if smart {
self.start_recon(objects, bearing, order.dist, out);
}
// A raid without routes is ready at once.
self.plan_step(None, out);
total
@@ -445,6 +473,7 @@ impl Sim {
heights: &plan.heights,
slope: (kind.climb_pitch().tan() * 0.5) as f32,
floor: (aim.y + spec.clearance) as f32,
unknown: 0.0,
});
let (r, cost) = plan_route_on(&plan.grid, &plan.prices[&kind], relief.as_ref(), from, aim);
work += cost;
@@ -480,6 +509,11 @@ impl Sim {
}
self.queue.push((now + wait.clamp(0.0, LONGEST_WAIT) as u64, d));
}
// Keep the land this plan was worked out over (#127): a retarget later is planned over the same
// known relief, not over ground mapped since.
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.wave = Some(WaveStats {
kills: self.kills,
hits: self.hits,
@@ -500,6 +534,18 @@ impl Sim {
self.plan.is_some()
}
/// The plan's drones and the structured intent each was given (#127; tests and diagnostics).
#[cfg(test)]
pub(super) fn planned_intents(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.id, i.d.intent)).collect()).unwrap_or_default()
}
/// The plan's unit aims and their intent: the same list, keyed by what the drone goes for.
#[cfg(test)]
pub(super) fn planned_aims(&self) -> Vec<(u32, ew::Intent)> {
self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default()
}
/// 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 {
let id = self.id();
@@ -534,6 +580,8 @@ impl Sim {
smart: false,
nav: Nav::default(),
err,
intent: ew::Intent::Plan,
aim: ew::Aim::point(0),
hold: 0,
pace: Pace::default(),
}
@@ -542,11 +590,27 @@ impl Sim {
/// The strikes a smart raid sends at observed radars: for drones of `kinds` in order,
/// 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.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = self.known_units().into_iter()
.filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.alive() && s.kind == SamKind::Radar))
/// 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)>> {
// Exact disclosure contacts and recon marks of radars, best first. The order is the
// observed role, freshness and quality -- never the id: a hidden station has no id,
// and a big observed radar is worth more than a modest one (#135).
let now = self.tick;
let mut radars: Vec<(u8, u64, u32, DVec3)> = picture
.iter()
.filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable)
.map(|c| {
let seen = match c.confidence(now) {
ew::Confidence::Confirmed => 4,
ew::Confidence::Probable => 2,
ew::Confidence::Doubtful => 0,
};
(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();
radars.sort_by_key(|(id, _)| *id);
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 flat: Vec<DroneKind> = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect();
let mut jobs = vec![None; flat.len()];
if radars.is_empty() {
@@ -566,101 +630,108 @@ impl Sim {
jobs
}
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
/// point and the system's id.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim) -> (DVec3, Option<u32>) {
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
/// What a drone goes for: an object, or (by its kind and the raid's aim) a unit. Returns the
/// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a
/// 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.
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 {
return (object, None);
}
let pick = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
(!list.is_empty()).then(|| {
let s = list[(r * list.len() as f64) as usize % list.len()];
(s.pos, s.id)
})
let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> {
let c = list.get((r * list.len() as f64) as usize)?;
Some((c.at, c.id))
};
let r = self.rng.f();
let roll = self.rng.f();
if aim == Aim::ObjectsAndSams {
return if roll < 0.33 { pick(&alive, 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
// station, a radar, a system that fired).
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
// themselves away; the rest of the player's layout is not in its hands.
let known = self.known_units();
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, &known)).collect();
let pick_known = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
let s = *list.get((r * list.len() as f64) as usize)?;
known.iter().find(|(id, _)| *id == s.id).map(|(_, pos)| (*pos, s.id))
};
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.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 {
let s = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (known.iter().find(|(id, _)| *id == s.id).unwrap().1, Some(s.id));
let c = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
return (c.at, Some(c.id));
}
// Short-range systems (guns, Tor, P1-SUN) for the Lancets; long-range ones and the radars
// that feed them for the fast missiles.
let guns: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind.armed() && s.kind.range() <= 300.0).collect();
let long: Vec<&Sam> =
alive.iter().copied().filter(|s| s.kind.range() >= 450.0 || s.kind == SamKind::Radar).collect();
let guns: Vec<ew::Contact> = picture.iter().copied().filter(|c| c.kind.armed() && c.kind.range() <= 300.0).collect();
let long: Vec<ew::Contact> =
picture.iter().copied().filter(|c| c.kind.range() >= 450.0 || c.kind == SamKind::Radar).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick_known(&guns, r).or_else(|| pick_known(&alive, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick_known(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick_known(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick_known(&alive, 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::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
if let Some((p, id)) = choice {
return (p, Some(id));
}
// Nothing disclosed and nothing the kind's usual preference picked: a recon mark
// whose observed role fits is the next best reason to turn a strike off the object.
if let Some(m) = recon_pick(kind, leads, r) {
return (m.area, Some(m.id));
}
(object, None)
}
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
/// system sees it there (its radar's reach for it, the land) and can shoot it.
#[cfg(test)]
pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec<f32>, usize) {
self.price_grid_on(grid, kind, None)
}
/// The same over known land: a cell's drone flies `height` over the land there, not over the system's feet,
/// so what a radar sees and what a hill hides follow the relief.
/// The same over the picture this moment holds: a smart plan's own prices are priced on the
/// picture the plan was ordered with (#127). Later observations change nothing here.
pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec<f32>, usize) {
self.price_grid_known(grid, kind, land, &self.picture_of_defences())
}
/// The same over a picture of the defences: a retarget is priced on the picture its target was
/// chosen from, so the jobs of one adaptive tick do not each see a different world (#127). Every
/// 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.
pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, picture: &[ew::Contact]) -> (Vec<f32>, usize) {
let mut cost = 0;
let spec = kind.spec();
let height = spec.clearance.max(6.0);
let known_now = self.known_units();
let n = grid.size;
let now = self.tick;
let mut prices = vec![1.0f32; (n * n) as usize];
// Known jamming stations: drones that navigate by satellite keep away.
if kind.jammable() {
let known = self.known_units();
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known.iter().any(|k| k.0 == s.id)) {
let pos = known.iter().find(|(id, _)| *id == s.id).unwrap().1;
let (ci, cj) = grid.index(pos);
let r = (EW_RADIUS / grid.cell).ceil() as i32;
for c in picture.iter().filter(|c| c.kind == SamKind::Ew) {
let (ci, cj) = grid.index(c.at);
let r = (ew::EW_RADIUS / 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) {
if horizontal(grid.centre((i, j), pos.y) - pos).length() < EW_RADIUS {
if horizontal(grid.centre((i, j), c.at.y) - c.at).length() < ew::EW_RADIUS {
prices[(i * n + j) as usize] += 12.0;
}
}
}
}
}
// Only the systems the enemy knows of are priced in (#93): a hidden one is flown into.
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0 && Self::enemy_knows(s, &known_now)) {
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
let sp = s.kind.spec();
// Only the systems the picture holds are priced in (#93): a hidden one is flown into.
for c in picture.iter().filter(|c| c.kind.spec().roles & spec.class.bit() != 0) {
let pos = c.at;
let sp = c.kind.spec();
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
// A gun needs its own radar; a missile also flies on the tracks of any radar within data-link range.
let own = sight::reach(s, kind, height);
let net = self.sams.iter().filter_map(|r| {
let at = known_now.iter().find(|(id, _)| *id == r.id)?.1;
(r.id != s.id && at.distance(pos) <= sight::LINK).then(|| sight::reach(r, kind, height))
}).fold(0.0, f64::max);
// A gun needs its own radar; a missile also flies on the tracks of any radar the picture
// holds within data-link range of the unit's observed place. What those radars are set to
// (role, switch, damage) is not observable: a live contact of one is assumed to feed.
let own = if c.believes_own_sensor(now) { ew::published_reach(c.kind, kind, height) } else { 0.0 };
let net = picture
.iter()
.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))
.fold(0.0, f64::max);
let (hi, gun) = (hi.min(own.max(net)), gun.min(own));
let far = hi.max(gun);
let at = pos + (sight::antenna(s) - s.pos);
let horizon = (pos == s.pos).then(|| self.horizons.get(&s.id)).flatten();
// Only the cells round it.
let (ci, cj) = grid.index(pos);
let r = (far / grid.cell).ceil() as i32 + 1;
@@ -677,9 +748,6 @@ impl Sim {
if !(missile || d < gun) {
continue;
}
if horizon.is_some_and(|h| h.hides(at, p)) {
continue;
}
prices[(i * n + j) as usize] += if missile { 30.0 } else { 18.0 };
}
}
@@ -900,6 +968,11 @@ const AIR_START_WAIT: u32 = 120;
if !why.is_empty() {
out.messages.push(format!("Неудачи ПВО: {why}"));
}
// What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135).
let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count();
if marks > 0 {
out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)"));
}
// What the counter-strikes did to the raid (#101): the launches that never happened.
let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum();
if cut > 0 {
@@ -921,6 +994,21 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
len
}
/// A recon mark whose observed category fits this kind. The list is already in priority
/// order, so the first fit is the best reason.
fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option<recon::Mark> {
use recon::Category as C;
let fits = |c: C| match kind {
DroneKind::Lancet => matches!(c, C::Gun | 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),
_ => false,
};
let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect();
fits.get((r * fits.len() as f64) as usize).copied().copied()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -975,20 +1063,27 @@ mod tests {
fn sead_uses_only_unexpired_observations_at_the_last_known_position() {
let mut sim = Sim::new(121);
let old = DVec3::new(100.0, 70.0, 200.0);
let mut radar = Sam::new(1, SamKind::Radar, old, 0.0);
radar.radar_on = false;
let radar = Sam::new(1, SamKind::Radar, old, 0.0);
sim.sams.push(radar);
let kinds = [(DroneKind::Kh22, 8)];
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let none = Vec::new();
assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none));
sim.tick = 20;
sim.intel.revealed.push((1, old, sim.tick));
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.
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
sim.tick = 40;
let jobs = sim.radar_strikes(&kinds);
let picture = sim.picture_of_defences();
let jobs = sim.radar_strikes(&kinds, &picture);
assert_eq!(jobs.iter().flatten().count(), 2);
assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
// An old contact is not worth a strike either.
sim.tick = 3021;
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none), "a doubtful contact was struck");
sim.tick = 6020;
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let picture = sim.picture_of_defences();
assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none));
}
#[test]
@@ -998,9 +1093,10 @@ mod tests {
for (i, at) in [(-300.0, -200.0), (250.0, -250.0), (50.0, 300.0)].into_iter().enumerate() {
let id = sim.id();
let p = DVec3::new(at.0, 70.0, at.1);
sim.sams.push(Sam::new(id, SamKind::Radar, p, i as f64));
let sam = Sam::new(id, SamKind::Radar, p, i as f64);
sim.intel.observe(&sam, sim.tick, ew::Seen::Emission);
sim.sams.push(sam);
radars.push((id, p));
sim.intel.revealed.push((id, p, sim.tick));
}
let ew = sim.id();
sim.sams.push(Sam::new(ew, SamKind::Ew, DVec3::new(0.0, 70.0, 0.0), 0.0));
@@ -1036,7 +1132,7 @@ mod tests {
// The first strikers are the fast ones.
assert!(radars.iter().any(|(_, p)| aimed_at(&sim, *p).iter().any(|k| matches!(k, DroneKind::Kh22 | DroneKind::Zircon | DroneKind::Iskander | DroneKind::Kinzhal))));
// The enemy has learnt of the jamming station and re-aims what it can: not these.
sim.intel.revealed.push((ew, DVec3::new(0.0, 70.0, 0.0), sim.tick));
sim.intel.observe(&sim.sams.iter().find(|s| s.id == ew).unwrap(), sim.tick, ew::Seen::Jamming);
for _ in 0..160 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
@@ -1044,6 +1140,97 @@ mod tests {
check(&sim, "after adapting");
}
/// The picture the planner works from: one contact per unit, the newest observation
/// winning, the forgotten and the watched-dead out, the order deterministic — and it
/// never reads the force itself, so a contact of a unit that no longer exists stays
/// until its observations age out.
#[test]
fn picture_is_newest_per_unit_and_reads_no_truth() {
let mut sim = Sim::new(9);
let mut ids = Vec::new();
for (i, kind) in [SamKind::S400, SamKind::Ew, SamKind::Radar, SamKind::Tor, SamKind::Patriot].into_iter().enumerate() {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0));
ids.push(id);
}
sim.tick = 7000;
let (a, b, c, d, e) = (ids[0], ids[1], ids[2], ids[3], ids[4]);
// A long fight: repeated observations (newest wins), one unit watched dying, one
// never seen, one id the force does not have, and one observation that aged out.
for t in 0..200u64 {
sim.intel.observe(&sim.sams[0], 1000 + t, ew::Seen::Launch);
sim.intel.observe(&sim.sams[2], 1000 + t, ew::Seen::Emission);
if t % 7 == 0 { sim.intel.observe(&sim.sams[1], 1000 + t, ew::Seen::Jamming); }
if t % 11 == 0 { sim.intel.observe(&sim.sams[3], 1000 + t, ew::Seen::Launch); }
if t % 13 == 0 {
sim.intel.note(999_999, SamKind::Radar, DVec3::new(1.0, 70.0, 0.0), true, 1000 + t, ew::Seen::Emission);
}
}
sim.intel.note(e, SamKind::Patriot, DVec3::new(15.0, 70.0, 0.0), true, 2, ew::Seen::Launch); // aged out at tick 7000
// The EW station is watched dying by a strike: observed, and so out of the targets.
sim.intel.outcome(b, false, sim.sams[1].pos, 1349);
let picture = sim.picture_of_defences();
let got: Vec<u32> = picture.iter().map(|c| c.id).collect();
// a and c were both seen last at tick 1199 (tie: the newer id first); d at 1198; the
// fake at 1195. The watched-dead b, the never-seen e and the aged-out are out.
assert_eq!(got, vec![c, a, d, 999_999]);
assert_eq!(picture[0].at, DVec3::new(200.0, 70.0, -50.0), "the observed place is the unit's own");
assert_eq!(picture[0].seen, ew::Seen::Emission);
assert_eq!(picture[1].kind, SamKind::S400);
assert!(picture.iter().all(|c| c.id != b && c.id != e));
assert_eq!(sim.picture_of_defences(), picture, "the picture is not deterministic");
}
/// The reported Windows stop (#122): the second big order from the UI path, with a fat
/// intel log and a large surviving force, must be accepted and launched like the first.
/// (The old per-drone planner snapshot was correct but quadratic; its cost is pinned by
/// the actual-WASM fuel measurements in docs/measurements/issue-122-ui-fuel.)
#[test]
fn a_second_smart_order_with_a_fat_intel_log_is_accepted_and_launched() {
let mut sim = Sim::new(31);
let mut ids = Vec::new();
for i in 0..48 {
let id = sim.id();
sim.sams.push(Sam::new(id, [SamKind::S400, SamKind::Patriot, SamKind::Nasams, SamKind::Pantsir][i % 4], DVec3::new((i % 8 * 40) as f64, 70.0, (i / 8 * 40) as f64), 0.0));
ids.push(id);
}
// A fought-off first raid leaves a long observation history: launches, emitting
// radars, stations. Its entries sit in the past of the sim clock, like real ones.
sim.tick = 4000;
for t in 0..3000u64 {
let sam = &sim.sams[(t as usize) % ids.len()];
sim.intel.observe(sam, 1001 + t, if t % 3 == 0 { ew::Seen::Emission } else { ew::Seen::Launch });
}
sim.targets.push(DVec3::new(160.0, 70.0, 160.0));
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 mut order = RaidOrder::mix(36, 300.0);
order.aim = Aim::Smart;
order.approach = Approach::AllSides;
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
let first = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(first, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= total as usize, "the first order queued or launched every drone (queue {}, launched {})", sim.queue.len(), sim.launched);
// The second order — the path that stopped the mod on Windows — is accepted too.
let second = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(second, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= 2 * total as usize, "both orders queued or launched their drones (queue {}, launched {})", sim.queue.len(), sim.launched);
}
#[test]
fn systems_ready_together_send_one_missile_at_a_drone() {
let mut sim = Sim::new(3);
File diff suppressed because it is too large Load Diff
+122 -9
View File
@@ -1,8 +1,9 @@
//! Raids are recorded for their replays: every drone's and interceptor's
//! track (a point every other tick, falling wrecks included) and what
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
//! A recording starts with the first drone in the sky and ends when the sky
//! has been clear a while; the last few are kept.
//! A recording starts with the first strike drone in the sky and ends when the sky
//! has been clear a while; the last few are kept. A recon aircraft is a role of its own
//! and is not part of the strike's replay (#135).
use super::*;
/// A system's pose at a moment of a recording.
@@ -155,6 +156,8 @@ impl Recording {
objects: Vec::new(),
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
quiet: 0,
@@ -185,6 +188,8 @@ pub const STEP: u32 = 2;
/// The longest recording (10 minutes) and how many are kept.
const LONGEST: u32 = 12_000;
const KEPT: usize = 3;
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
const MAX_SAM_KEYS: usize = 32_768;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum What {
@@ -381,6 +386,8 @@ pub struct Recording {
/// it pointed, whether it was still whole).
pub sam_tracks: Vec<SamTrack>,
sam_index: HashMap<u32, usize>,
sam_keys: usize,
sam_step: u32,
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
/// shows the world's blocks as of this time.
ticks: Vec<(u32, u64)>,
@@ -589,14 +596,38 @@ impl Recording {
objects: sim.targets.clone(),
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
quiet: 0,
}
}
fn thin_sam_tracks(&mut self) {
for track in &mut self.sam_tracks {
let len = track.keys.len();
let mut kept = 0;
for read in (0..len).step_by(2) {
track.keys[kept] = track.keys[read];
kept += 1;
}
if len % 2 == 0 && len > 0 {
track.keys[kept] = track.keys[len - 1];
kept += 1;
}
track.keys.truncate(kept);
track.keys.shrink_to_fit();
}
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
}
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
/// the pose it held marked before it so a replay doesn't glide through the stillness.
fn note_sams(&mut self, sams: &[Sam], now: u32) {
if now % self.sam_step != 0 {
return;
}
for sam in sams {
let key = SamKey::of(sam, self.origin, now);
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
@@ -604,16 +635,21 @@ impl Recording {
self.sam_tracks.len() - 1
});
let track = &mut self.sam_tracks[i];
let before = track.keys.len();
match track.keys.last().copied() {
None => track.keys.push(key),
Some(last) if last.same(&key) => {}
Some(last) => {
if last.at + STEP < now {
track.keys.push(SamKey { at: now - STEP, ..last });
if last.at + self.sam_step < now {
track.keys.push(SamKey { at: now - self.sam_step, ..last });
}
track.keys.push(key);
}
}
self.sam_keys += track.keys.len() - before;
}
if self.sam_keys > MAX_SAM_KEYS {
self.thin_sam_tracks();
}
}
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
@@ -799,8 +835,11 @@ impl Sim {
}
/// Open before the combat update so transitions on the first active tick are not lost.
/// A recon aircraft neither opens nor holds a strike's recording (#135).
pub(super) fn begin_recording_if_active(&mut self) {
if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) {
if self.rec.is_none()
&& (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty())
{
self.recordings += 1;
self.rec = Some(Recording::new(self.recordings, self));
}
@@ -818,7 +857,13 @@ impl Sim {
pub(super) fn record(&mut self) {
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty();
// A recon flight is not part of the strike's replay: it neither opens nor holds a
// recording open. The strike's own drones and interceptors do (#135).
let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id))
|| !self.missiles.is_empty()
|| !self.queue.is_empty()
|| !self.strikes.flights.is_empty()
|| !self.strikes.pending.is_empty();
self.begin_recording_if_active();
let Some(r) = &mut self.rec else { return };
r.note_tracks(&self.sams);
@@ -832,7 +877,7 @@ impl Sim {
if r.len % STEP == 0 {
let now = r.len;
r.note_sams(&self.sams, now);
for d in &self.drones {
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
r.point(d.id, What::Drone(d.kind), d.pos);
}
for m in &self.missiles {
@@ -1043,6 +1088,8 @@ mod tests {
objects: Vec::new(),
sam_tracks: Vec::new(),
sam_index: HashMap::new(),
sam_keys: 0,
sam_step: STEP,
ticks: Vec::new(),
times: Vec::new(),
quiet: 0,
@@ -1062,6 +1109,19 @@ mod tests {
assert!(r.sam_tracks[0].ghost(r.origin, 0.0, 1).unwrap().radar_on);
}
#[test]
fn replay_preserves_a_separate_radars_profile() {
let mut r = recording();
for (at, role) in [(0, battery::RadarRole::Search), (10, battery::RadarRole::Height), (20, battery::RadarRole::Engagement)] {
let mut sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
sam.set_radar_role(role);
r.note_sams(&[sam], at);
}
assert_eq!(r.sam_tracks[0].ghost(r.origin, 1.0, 1).unwrap().radar_profile().id, "radar_search");
assert_eq!(r.sam_tracks[0].ghost(r.origin, 11.0, 1).unwrap().radar_profile().id, "radar_height");
assert_eq!(r.sam_tracks[0].ghost(r.origin, 21.0, 1).unwrap().radar_profile().id, "radar_track");
}
#[test]
fn replay_preserves_launcher_configuration_and_individual_cover_poses() {
let mut r = recording();
@@ -1169,6 +1229,29 @@ mod tests {
}
}
#[test]
fn full_recording_bounds_sam_keys_without_freezing_their_poses() {
let mut r = recording();
let mut sams: Vec<_> = (0..64)
.map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0))
.collect();
for now in (0..LONGEST).step_by(STEP as usize) {
for sam in &mut sams {
sam.dish = now as f64 * 0.01;
}
r.note_sams(&sams, now);
}
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
assert_eq!(keys, r.sam_keys);
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
let last = r.sam_tracks[0].pose(LONGEST as f64).unwrap();
assert!(last.at >= LONGEST - 64, "poses stopped at tick {}", last.at);
assert!(last.dish > 100.0, "the final radar pose was not recorded");
}
#[test]
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
let mut r = recording();
@@ -1230,7 +1313,22 @@ mod tests {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0));
let mut r = Recording::new(1, &sim);
let tr = sight::Track { id: 77, kind: DroneKind::Shahed, pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false };
let tr = sight::Track {
id: 77,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::Z * 100.0,
vel: -DVec3::Z,
tick: 1,
own_tick: 1,
source: 1,
product: battery::Measure::Fire,
quality: 80,
own_product: battery::Measure::Fire,
own_quality: 80,
ttl: 10,
hits: 1,
locked: false,
};
sim.sams[0].tracks.push(tr);
r.note_tracks(&sim.sams);
r.len = 1;
@@ -1296,7 +1394,22 @@ mod tests {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0);
for target in 1..=4 {
sam.tracks.push(sight::Track { id: target, kind: DroneKind::Shahed, pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false });
sam.tracks.push(sight::Track {
id: target,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::Z,
vel: DVec3::ZERO,
tick: 1,
own_tick: 1,
source: sam.id,
product: battery::Measure::Fire,
quality: 80,
own_product: battery::Measure::Fire,
own_quality: 80,
ttl: 1,
hits: 1,
locked: false,
});
}
sim.sams.push(sam);
}
+583 -21
View File
@@ -54,9 +54,9 @@ fn network_launcher_must_contribute_to_route_risk() {
// The planner prices only observed units; neither unit is known initially.
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
assert!(prices.iter().all(|p|*p==1.),"an unknown launcher must not be priced");
sim.intel.revealed.push((sim.sams[0].id,DVec3::new(0.,70.,0.),0));
// Both the launcher and its supporting radar have been observed.
sim.intel.revealed.push((sim.sams[1].id,DVec3::new(0.,70.,0.),0));
// The launcher is seen firing without a sensor of its own; the radar is fixed emitting.
sim.intel.observe(&sim.sams[0],0,ew::Seen::Launch);
sim.intel.observe(&sim.sams[1],0,ew::Seen::Emission);
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
assert!(prices.iter().any(|p|*p>1.),"armed launcher with a network radar is invisible to route risk");
}
@@ -131,11 +131,14 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0.0));
let goal = sim.id();
sim.sams.push(Sam::new(goal, SamKind::Ew, DVec3::new(0.0, 70.0, 1000.0), 0.0));
sim.intel.revealed.push((goal, DVec3::new(0.0, 70.0, 1000.0), 0));
// Its first target, a system that is destroyed by now.
sim.intel.observe(&sim.sams[2], 0, ew::Seen::Jamming);
// Its first target: a system the picture watched die — seen firing, then the enemy's
// munition watched the wreck. A unit destroyed unobserved would keep the drone coming.
let id = sim.id();
let mut wreck = Sam::new(id, SamKind::Patriot, DVec3::new(3000.0, 70.0, -1000.0), 0.0);
sim.intel.observe(&wreck, 0, ew::Seen::Launch);
wreck.health = 0.0;
sim.intel.outcome(wreck.id, false, wreck.pos, 0);
sim.sams.push(wreck);
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 100.0, -1000.0), DVec3::Z, DVec3::new(3000.0, 70.0, -1000.0));
sim.drones[0].pos = DVec3::new(0.0, 100.0, -1000.0);
@@ -147,6 +150,276 @@ fn retargeted_smart_drone_gets_a_route_round_the_defences() {
assert!(d.route.len() > 1, "no route after the new target: it flies straight through the defences");
}
// #127: a mass retarget works its route jobs out over the following ticks. No drone is left without a
// route by the budget, old safe routes are kept until their replacements are ready, and the queue never
// grows or repeats a drone.
#[cfg(test)]
fn mass_retarget_sim(seed: u64) -> (Sim, HashMap<u32, Vec<DVec3>>, u32) {
let mut sim = Sim::new(seed);
for i in 0..8 {
for j in 0..5 {
let at = DVec3::new(-560.0 + i as f64 * 160.0, 70.0, -320.0 + j as f64 * 160.0);
let id = sim.id();
let sam = Sam::new(id, SamKind::S400, at, 0.0);
// Every system is on the picture, its radar fixed emitting once.
sim.intel.observe(&sam, 0, ew::Seen::Emission);
sim.sams.push(sam);
}
}
let mut old = HashMap::new();
let mut empty = 0;
for i in 0..40 {
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));
d.smart = true;
d.route = vec![from, DVec3::new(1800.0, 70.0, 1800.0)];
// The last drone starts with no route at all (a drone whose route was lost): its job must wait its
// budget, not be dropped, and must give it a route in the end.
if i == 39 {
d.route.clear();
empty = d.id;
}
old.insert(d.id, d.route.clone());
sim.queue.push((0, d));
}
(sim, old, empty)
}
#[cfg(test)]
fn flight_state(sim: &Sim) -> Vec<(u32, u64, u64, u64, Vec<(u64, u64, u64)>)> {
sim.queue
.iter()
.map(|(_, d)| {
let route = d.route.iter().map(|p| (p.x.to_bits(), p.y.to_bits(), p.z.to_bits())).collect();
(d.id, d.target.x.to_bits(), d.target.y.to_bits(), d.target.z.to_bits(), route)
})
.collect()
}
#[test]
fn mass_retarget_finishes_its_route_jobs_over_the_budget() {
let (mut sim, old, empty) = mass_retarget_sim(7);
sim.tick = 40;
sim.adapt();
let pending = sim.retarget_ids();
assert!(!pending.is_empty(), "the budget planned all 40 routes: the test no longer covers the queue");
assert_eq!(pending.len(), pending.iter().collect::<std::collections::HashSet<_>>().len(), "duplicate jobs");
// Assignments are throttled too: one adaptive tick hands out a bounded number of new aims,
// and the rest of the force is sent on the following adaptive ticks (#127).
assert!(pending.len() <= super::ew::ASSIGN_PER_TICK, "one adaptive tick assigned {} drones", pending.len());
for id in &pending {
let d = &sim.queue.iter().find(|(_, d)| d.id == *id).unwrap().1;
assert_eq!(&d.route, old.get(id).unwrap(), "an old safe route was replaced before the new one was ready");
}
let mut left = pending.len();
for _ in 0..400 {
sim.tick += 1;
sim.adapt();
if sim.tick % 40 == 0 {
// A new adaptive tick: more drones may be sent, still within the throttle.
let now = sim.retarget_ids().len();
assert!(now <= left + super::ew::ASSIGN_PER_TICK, "an adaptive tick assigned more than {} drones", super::ew::ASSIGN_PER_TICK);
left = now;
} else if left > 0 {
assert!(sim.retargets.len() < left, "a budget tick made no progress: {left} jobs left");
left = sim.retargets.len();
}
let still = sim.retarget_ids();
assert!(
// A drone the throttle has not sent yet is still on its own plan's route or has none to lose;
// one already sent at a unit whose route is empty must have a job that will fill it.
sim.queue.iter().all(|(_, d)| !d.route.is_empty() || still.contains(&d.id) || d.aim.unit == 0),
"a route is still empty with no job left to fill it"
);
}
assert_eq!(sim.retargets.len(), 0, "route jobs were never finished");
// No drone is left with an empty route for ever, and every new route ends at its aim. The drone
// that started with no route at all got one too: its job waited for the budget, not for ever.
for (_, d) in &sim.queue {
assert!(!d.route.is_empty(), "a drone was left with no route");
assert!(d.route.last().is_some_and(|p| p.distance(d.target) < 1e-6), "the new route does not end at the new aim");
assert!(d.aim.unit != 0, "a drone was never sent at a unit");
}
let empty = sim.queue.iter().find(|(_, d)| d.id == empty).unwrap().1.clone();
assert!(!empty.route.is_empty(), "the drone that started with no route never got one");
}
#[test]
fn mass_retarget_is_deterministic_and_never_duplicates_a_drone() {
let (mut a, _, _) = mass_retarget_sim(11);
let (mut b, _, _) = mass_retarget_sim(11);
a.tick = 40;
b.tick = 40;
a.adapt();
b.adapt();
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the same seed left a different queue");
assert_eq!(flight_state(&a), flight_state(&b), "the same seed planned different routes");
for _ in 0..80 {
a.adapt();
b.adapt();
let ids = a.retarget_ids();
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a drone has two jobs");
assert_eq!(a.retarget_ids(), b.retarget_ids(), "the queues drifted apart");
assert_eq!(flight_state(&a), flight_state(&b), "the routes drifted apart");
if ids.is_empty() {
break;
}
a.tick += 1;
b.tick += 1;
// Another adaptive tick while the queue is still being worked: a known aim must not enqueue again.
if a.tick % 40 == 0 {
a.adapt();
b.adapt();
let ids = a.retarget_ids();
assert_eq!(ids.len(), ids.iter().collect::<std::collections::HashSet<_>>().len(), "a repeat adapt duplicated a job");
}
}
}
#[cfg(test)]
fn relief_grid() -> Grid {
Grid { min: DVec3::new(-2560.0, 0.0, -2560.0), cell: 32.0, size: 160 }
}
#[cfg(test)]
fn flat_relief() -> std::sync::Arc<super::ew::KnownRelief> {
let g = relief_grid();
std::sync::Arc::new(super::ew::KnownRelief::new(g, vec![70.0; (g.size * g.size) as usize]))
}
#[cfg(test)]
fn wall_relief() -> std::sync::Arc<super::ew::KnownRelief> {
let g = relief_grid();
let mut h = vec![70.0; (g.size * g.size) as usize];
for i in 0..g.size {
for j in 0..g.size {
let x = g.min.x + (f64::from(i) + 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 {
h[(i * g.size + j) as usize] = 1000.0;
}
}
}
std::sync::Arc::new(super::ew::KnownRelief::new(g, h))
}
#[cfg(test)]
fn finish_retargets(sim: &mut Sim) {
for _ in 0..200 {
if sim.retargets.is_empty() {
return;
}
sim.tick += 1;
sim.adapt();
}
panic!("the retarget queue did not finish");
}
#[cfg(test)]
fn retarget_route(sim: &Sim, id: u32) -> Vec<DVec3> {
sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone()
}
#[test]
fn pending_retarget_keeps_its_relief_version_after_a_new_plan() {
let flat = flat_relief();
let wall = wall_relief();
let outside = Grid { min: DVec3::new(3000.0, 0.0, 3000.0), cell: 32.0, size: 8 };
assert!(flat.sampled_on(&outside).is_none(), "land outside the plan must be Unknown");
let edge = Grid { min: DVec3::new(2500.0, 0.0, 2500.0), cell: 32.0, size: 8 };
let edge_flat = flat.sampled_on(&edge).unwrap();
assert!(edge_flat.iter().any(|h| h.is_nan()) && edge_flat.iter().any(|h| *h == 70.0));
let prepare = |relief| {
let (mut sim, _, _) = mass_retarget_sim(7);
sim.known_relief = Some(relief);
sim.tick = 40;
sim.adapt();
sim
};
let mut control = prepare(flat.clone());
let mut test = prepare(flat.clone());
let id = *test.retarget_ids().last().unwrap();
assert!(test.pending_relief(id).is_some(), "the chosen job is not waiting");
// Another smart plan finishes while the job waits: the global snapshot is the wall now.
test.known_relief = Some(wall.clone());
let bits = |v: Option<Vec<f32>>| v.map(|x| x.into_iter().map(f32::to_bits).collect::<Vec<_>>());
assert_eq!(
bits(test.pending_relief(id).unwrap().sampled_on(&edge)),
bits(flat.sampled_on(&edge)),
"a pending job's relief changed with the global snapshot"
);
finish_retargets(&mut control);
finish_retargets(&mut test);
assert_eq!(retarget_route(&control, id), retarget_route(&test, id), "the pending route used the newer relief");
let mut walled = prepare(wall);
finish_retargets(&mut walled);
assert_ne!(retarget_route(&control, id), retarget_route(&walled, id), "the test does not distinguish the relief versions");
}
#[test]
fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() {
let flat = flat_relief();
let mut sim = Sim::new(3);
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::S400, threat_at, 0.0));
let target = sim.id();
sim.sams.push(Sam::new(target, SamKind::S400, aim, 0.0));
let contact = |id: u32, at: DVec3| super::ew::Contact {
id,
kind: SamKind::S400,
at,
tick: 0,
seen: super::ew::Seen::Emission,
emission: Some(0),
destroyed: None,
launches: 0,
};
let known_all = std::sync::Arc::new(vec![contact(threat, threat_at), contact(target, aim)]);
let known_target = std::sync::Arc::new(vec![contact(target, aim)]);
// The picture holds both units: a job's unit is alive only while the picture believes in it.
for c in known_all.iter() {
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 d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim);
d.smart = true;
d.err = DVec3::ZERO;
d.target = aim;
d.route = vec![start, aim];
let id = d.id;
sim.queue.push((0, d));
sim.retargets.push_back(super::ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone())));
id
};
// Same relief, same start and aim. Version 1 knows the threat on the direct line; version 2 does not.
let first = add(known_all.clone(), 1);
let other = add(known_target, 2);
// A second job of version 1: it may reuse the first one's price grid and route.
let same = add(known_all, 1);
sim.tick = 1;
for _ in 0..10 {
if sim.retargets.is_empty() {
break;
}
sim.adapt();
sim.tick += 1;
}
assert!(sim.retargets.is_empty(), "the jobs were not finished");
let route = |id| sim.queue.iter().find(|(_, d)| d.id == id).unwrap().1.route.clone();
let (r1, r2, r3) = (route(first), route(other), route(same));
assert_ne!(r1, r2, "jobs with different known snapshots shared a route");
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
#[test]
fn big_ground_cache_is_swept_rarely() {
@@ -717,7 +990,7 @@ fn fires_start_merge_and_are_limited() {
// interceptors keep clear of it. A synthetic land (a height function) stands in for the game.
/// Land from a height function: blocks below it are solid, and the game's height map says the same.
struct Land<F: Fn(i32, i32) -> i32>(F);
pub(super) struct Land<F: Fn(i32, i32) -> i32>(F);
impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
Some(y < (self.0)(x, z))
@@ -725,7 +998,7 @@ impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
}
/// What the game answers a tick after the sim asked: land heights, and the sections it needs.
fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
pub(super) fn answer_land<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (land.0)(x, z))).collect();
ground.answer(columns, now);
let sections = ground.world.take_wanted(now);
@@ -737,7 +1010,7 @@ fn ridge(rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
ridge_at(300, rise, half)
}
fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
pub(super) fn ridge_at(crest: i32, rise: i32, half: i32) -> Land<impl Fn(i32, i32) -> i32> {
Land(move |x, _| 64 + (rise - (x - crest).abs() * rise / half).max(0))
}
@@ -830,9 +1103,23 @@ fn behind_ridge(land: &Land<impl Fn(i32, i32) -> i32>, crest: i32, kind: SamKind
// It crawls along the far side of the ridge, 20 blocks over the land.
let there = (land.0)(x as i32, 0) as f64;
sim.add_drone(DroneKind::Shahed, DVec3::new(x, there + 20.0, -100.0), DVec3::Z, DVec3::new(x, there, 3000.0));
let id = sim.drones[0].id;
for _ in 0..ticks {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
// The scenario is about the interceptor's path over the ridge, not about
// where the plot came from: give the system the crest radar's plot as its
// own confirmed fire measurement (separate authority is tested in
// `a_system_does_not_fire_at_a_target_masked_by_a_hill`).
if let Some(t) = sim.sams[1].track(id).copied() {
let mut own = t;
own.source = sim.sams[0].id;
own.own_tick = sim.tick;
own.own_product = battery::Measure::Fire;
own.own_quality = 90;
sim.sams[0].tracks.retain(|o| o.id != id);
sim.sams[0].tracks.push(own);
}
}
sim
}
@@ -858,27 +1145,25 @@ fn a_system_does_not_fire_at_a_target_masked_by_a_hill() {
answer_land(&mut ground, land, sim.tick);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(200.0, 84.0, -60.0), DVec3::Z, DVec3::new(200.0, 64.0, 3000.0));
let mut masked = 0u32;
let mut seen = false;
let mut told = false;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
seen |= sim.sams[0].seen.len() == 1;
masked += sim.sams[0].terrain.values().filter(|(_, b)| *b == terrain::MASKED).count() as u32;
// `why` names the reason while the verdict stands.
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("за рельефом"));
// The network shows the target, but the Tor has no own confirmed plot,
// so `why` must say that no launch is authorized.
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("право на пуск: нет"));
}
(sim, seen, masked, told)
(sim, seen, told)
};
let (open, seen, _, _) = shot(&flat);
let (open, seen, _) = shot(&flat);
assert!(seen && open.sams[0].fired > 0, "control: with a clear line the Tor must fire (seen {seen}, fired {})", open.sams[0].fired);
let (shut, seen, masked, told) = shot(&hill);
let (shut, seen, told) = shot(&hill);
assert!(seen, "the network must have shown the target to the Tor");
assert_eq!(shut.sams[0].fired, 0, "the Tor fired at a target behind the hill");
assert!(masked > 0, "no launch was judged and refused for the land");
assert_eq!(shut.tally.blocked + shut.tally.scrubbed, 0);
assert!(told, "`why` never named the land as the reason");
assert!(told, "`why` never named the missing own fire plot");
}
// A long-range system lofts over a low ridge (its interceptor does not hit it) but not over a mountain.
@@ -1316,7 +1601,7 @@ fn raids_have_the_same_strike_accuracy_as_manual_launches() {
let mut sim = Sim::new(3);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Ew, DVec3::new(0.0, 70.0, 900.0), 0.0));
sim.intel.revealed.push((id, DVec3::new(0.0, 70.0, 900.0), 0));
sim.intel.observe(&sim.sams[0], 0, ew::Seen::Jamming);
let order = RaidOrder { kinds: vec![(DroneKind::Zircon, 20)], approach: Approach::Sector, dist: 400.0, aim: Aim::Objects };
sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut Out::default());
// (The raid's launch sites need land the game has told of: a flat one is served.)
@@ -1969,6 +2254,8 @@ fn spent_motor_has_less_maneuver_at_low_speed() {
assert!(powered.x > coast.x && coast.x > 0.0, "{powered:?} {coast:?}");
}
// #129: the staged launch's exact speed rules: gas-drag ejection with a floor, a spooled
// departure that grows into full acceleration, full power at guidance, the coast drag after.
#[test]
fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
let kind = MissileKind::M48n6;
@@ -1984,10 +2271,285 @@ fn cold_ejection_power_and_coast_use_their_own_speed_rules() {
sim.step_missiles(&mut Ground::default(), &mut Out::default());
sim.missiles[0].vel.length()
};
assert!((fly(0, 2.0) - 2.0 * 0.97).abs() < 1e-9, "cold ejection drag");
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
assert!((fly(0, spec.eject) - (spec.eject - spec.eject_drag)).abs() < 1e-9, "cold ejection drag");
assert!((fly(spec.cold - 1, 0.1) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor near ignition");
assert!((fly(0, 0.2) - spec.eject * 0.25).abs() < 1e-9, "cold ejection floor");
let spool0 = 0.45 + 0.55 / f64::from(spec.boost);
assert!((fly(spec.cold, 2.0) - (2.0 + spec.accel * spool0)).abs() < 1e-9, "ignition spool-up");
assert!((fly(spec.cold + spec.boost - 1, 2.0) - (2.0 + spec.accel)).abs() < 1e-9, "powered acceleration");
assert!((fly(spec.cold + kind.burn_ticks(), 2.0) - 2.0 * 0.995).abs() < 1e-9, "coast drag");
assert!((fly(0, 0.2) - 0.4).abs() < 1e-9, "cold ejection minimum");
}
// ---- #129: the staged cold launch. Ejection (unlit gas throw) → ignition where the round has
// reached → departure (spool-up and course capture at a growing rate) → guidance at cold + boost.
/// Every cold-launched kind walks its stages in order; before ignition there is no motor voice,
/// no flame and no steering, the speed is continuous across ignition, and the turn each tick
/// never exceeds what the stage allows.
#[test]
fn cold_launch_stages_run_in_order_and_guidance_follows_ignition() {
for &kind in &[MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT, MissileKind::M9m338] {
let spec = kind.spec();
let mut sim = Sim::new(120);
// A still target well off the vertical: the tip-over has somewhere to turn.
let target_pos = DVec3::new(300.0, 120.0, 300.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * spec.eject, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
sim.begin_recording_if_active();
let mut previous_speed = spec.eject;
let mut previous_dir = DVec3::Y;
let mut saw_ignition = false;
for age in 1..=(spec.cold + spec.boost + 2) {
sim.tick += 1;
let mut out = Out::default();
sim.step_missiles(&mut Ground::default(), &mut out);
let m = sim.missiles.iter().find(|m| m.id == id).unwrap_or_else(|| panic!("{kind:?} age {age}"));
let speed = m.vel.length();
let dir = m.vel.normalize_or(DVec3::Y);
let voice = out.engines.iter().any(|e| e.key == (0x4000_0000 | id));
let flame = out.particles.iter().any(|p| p.kind == "minecraft:flame");
assert_eq!(voice, m.engine_lit(), "{kind:?} age {age}: the motor voice runs only when lit");
if !m.engine_lit() {
assert!(!voice && !flame, "{kind:?} age {age}: powered effects before ignition");
assert!((speed - (previous_speed - spec.eject_drag)).abs() < 1e-9, "{kind:?} age {age}: ejection drag");
assert!(dir.angle_between(DVec3::Y) < 1e-9, "{kind:?} age {age}: steering before ignition");
} else if !saw_ignition {
saw_ignition = true;
assert_eq!(m.age, spec.cold + 1, "{kind:?}: ignition one tick after the ejection ends");
assert!(speed > previous_speed - 1e-9, "{kind:?}: speed jumps down across ignition ({previous_speed} -> {speed})");
assert!(out.sounds.iter().any(|s| s.0 == sound::LAUNCH_S400 || s.0 == sound::LAUNCH_S500), "{kind:?}: ignition sound");
let events = sim.rec.as_ref().unwrap().scene.as_ref().unwrap().events();
assert!(events.iter().any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { missile, .. } if missile == id)), "{kind:?}: ignition recorded");
}
let allowed = if spec.guided(m.age) {
spec.turn
} else if m.engine_lit() {
// Departure: the rate grows into the full one; no snap at the boundary.
spec.turn * (0.2 + 0.8 * spec.departure_ramp(m.age))
} else {
0.0
};
assert!(previous_dir.angle_between(dir) <= allowed + 1e-9, "{kind:?} age {age}: turned past the stage's rate");
previous_speed = speed;
previous_dir = dir;
}
assert!(saw_ignition, "{kind:?}: never lit");
let m = sim.missiles.iter().find(|m| m.id == id).unwrap();
assert!(m.vel.normalize().angle_between(DVec3::Y) > 0.3, "{kind:?}: still vertical after guidance started");
}
}
/// The invariant the issue is about: with a longer ignition delay the old `age >= boost` guidance
/// would have switched on before the motor existed. Now guidance implies ignition, for every
/// profile and every age, and the seeker opens with guidance, not with the raw boost counter.
#[test]
fn guidance_never_starts_before_ignition_for_any_profile() {
for kind in [
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
] {
let spec = kind.spec();
for age in 0..=spec.life.min(2000) {
assert!(!spec.guided(age) || age > spec.cold, "{kind:?} age {age}: guidance before ignition (cold {})", spec.cold);
}
}
}
/// Across the whole staging the speed changes smoothly (no jumps beyond the stage's own drag or
/// full acceleration) and the per-tick turn never exceeds the profile's rate, for every kind.
/// A rocket's first powered tick is a throttled one for rail and cold launches alike (#129).
#[test]
fn launch_accel_and_turn_stay_continuous_for_every_interceptor() {
for kind in [
MissileKind::Pac3, MissileKind::M57e6, MissileKind::M48n6, MissileKind::M77n6, MissileKind::IrisT,
MissileKind::Amraam, MissileKind::M9m317, MissileKind::M9m338, MissileKind::P1sun,
] {
let spec = kind.spec();
let mut sim = Sim::new(120);
let target_pos = DVec3::new(400.0, 140.0, 400.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
sim.missiles.push(Missile { id, kind, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::Y * v0, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
let mut previous_speed = v0;
let mut previous_dir = DVec3::Y;
let mut first_power: Option<f64> = None;
for _ in 0..120 {
sim.tick += 1;
sim.step_missiles(&mut Ground::default(), &mut Out::default());
let Some(m) = sim.missiles.iter().find(|m| m.id == id) else { break };
let speed = m.vel.length();
let dir = m.vel.normalize_or(DVec3::Y);
assert!(speed - previous_speed <= spec.accel + 1e-9, "{kind:?}: speed jumped up {previous_speed} -> {speed}");
let allowed_down = spec.eject_drag + previous_speed * 0.005;
assert!(speed >= previous_speed - allowed_down - 1e-9, "{kind:?}: speed jumped down {previous_speed} -> {speed}");
assert!(previous_dir.angle_between(dir) <= spec.turn + 1e-9, "{kind:?}: turned past the profile's rate");
if m.engine_lit() && first_power.is_none() {
first_power = Some(speed - previous_speed);
}
previous_speed = speed;
previous_dir = dir;
}
if spec.flame > 0.0 {
let gain = first_power.unwrap_or_else(|| panic!("{kind:?}: the motor never lit"));
let spooled = spec.accel * (0.45 + 0.55 / f64::from(spec.boost.max(1)));
assert!(gain > 0.0 && gain <= spooled + 1e-9, "{kind:?}: the motor reached full thrust at once ({gain} > {spooled})");
}
}
}
/// The electric P1-SUN is not a rocket: it keeps no flame, no powered smoke and its own voice.
#[test]
fn p1sun_stays_a_ramming_drone_without_a_plume() {
let kind = MissileKind::P1sun;
let spec = kind.spec();
assert_eq!(spec.flame, 0.0);
assert_eq!(spec.cold, 0);
let mut sim = Sim::new(120);
let target_pos = DVec3::new(200.0, 64.0, 0.0);
sim.add_drone(DroneKind::Shahed, target_pos, DVec3::ZERO, target_pos);
let (target, id) = (sim.drones[0].id, sim.id());
sim.missiles.push(Missile { id, kind, pos: DVec3::ZERO, vel: DVec3::X * 0.8, target, sam: 999, age: 0, hold: 0,
fix: Some(Fix { pos: target_pos, vel: DVec3::ZERO, tick: 0, seeker: false }), seen: 0 });
for _ in 0..40 {
sim.tick += 1;
let mut out = Out::default();
sim.step_missiles(&mut Ground::default(), &mut out);
assert!(!out.particles.iter().any(|p| p.kind == "minecraft:flame"), "P1-SUN grew a rocket plume");
if let Some(m) = sim.missiles.iter().find(|m| m.id == id) {
assert!(m.engine_lit(), "the electric interceptor's motor state is wrong");
let (event, _, _) = kind.engine_voice();
assert!(out.engines.iter().any(|e| e.key == (0x4000_0000 | id) && e.event == event));
} else {
break;
}
}
}
/// A real S-400 launch records the ejection and the ignition `cold` ticks apart; the replay's lit
/// state follows the recorded ignition, so a seek across it shows one flame and one voice sequence.
#[test]
fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() {
let mut sim = Sim::new(0x129);
let sam = sim.id();
sim.sams.push(Sam::new(sam, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0));
sim.sams[0].cooldown = 0;
let mut out = Out::default();
sim.launch(DroneKind::Kh101, DVec3::new(0.0, 160.0, -600.0), DVec3::Z, DVec3::new(0.0, 64.0, 0.0), &mut out);
let mut ground = Ground::default();
for _ in 0..200 {
// The firing system's own measurement, fresh this tick (as `why::radar_sees` feeds it):
// the test is about the launch stages, not about the scan's chance.
let now = sim.tick;
let tracks: Vec<sight::Track> = sim.drones.iter().filter(|d| d.alive())
.map(|d| sight::Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
})
.collect();
sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id));
sim.sams[0].tracks.extend(tracks);
let wanted = ground.take_wanted();
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 64)).collect(), sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
if sim.replays.iter().chain(sim.rec.iter()).flat_map(|r| r.scene.iter().flat_map(|s| s.events())).any(|e| matches!(e.kind, record::SceneKind::MotorIgnition { .. })) {
break;
}
}
let rec = sim.rec.as_ref().or_else(|| sim.replays.last()).expect("a recording");
let scene = rec.scene.as_ref().unwrap();
let launch = scene.events().iter().find(|e| matches!(e.kind, record::SceneKind::MissileLaunch { .. })).expect("the ejection is recorded");
let missile = match launch.kind { record::SceneKind::MissileLaunch { missile, .. } => missile, _ => unreachable!() };
let spec = MissileKind::M48n6.spec();
let ignition = rec.missile_ignition(missile).expect("the ignition is recorded");
assert_eq!(ignition.at - launch.at, spec.cold, "ignition {} ticks after the ejection", spec.cold);
let track = rec.track(missile).expect("the interceptor's track");
for t in [ignition.at as f64 - 1.0, ignition.at as f64 - 0.1] {
assert!(!rec.missile_is_lit(track, t, spec.cold), "lit before the recorded ignition at {t}");
}
for t in [ignition.at as f64, ignition.at as f64 + 5.0] {
assert!(rec.missile_is_lit(track, t, spec.cold), "not lit at the recorded ignition ({t})");
}
assert!(!rec.missile_is_lit(track, ignition.at as f64 + spec.cold as f64 + f64::from(MissileKind::M48n6.burn_ticks()) + 2.0, spec.cold), "lit past the recorded burnout");
}
/// The physical RM48U strike ejects unlit and slow, then lights at `EJECT_TICKS` where it has
/// reached: no motor voice or flame before, one ignition sound at the hand-over.
#[test]
fn rm48u_strike_ejects_before_ignition_on_its_own_path() {
use super::sites::testland::{Land, serve};
use super::sites::{LaunchSite, SiteClass};
use super::strike::{Estimate, Known, SiteState};
use glam::DVec2;
let land = Land(|_, _| 64);
let mut sim = Sim::new(11);
// A fixed site the strike needs no scouting for; its launches are queued far ahead, so a wave
// boundary does not retire it while the test runs.
let id = sim.sites.add(LaunchSite {
id: 0, side: 0, sector: 0, bearing: 0.0, class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 400.0), range: 400.0, water: false,
stock: 4, planned: 4, alive: true, next_free: 0, offmap: false,
});
for i in 0..4 {
let site = sim.sites.get(id).unwrap().clone();
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
sim.sites.job(d.id, id);
sim.queue.push((20_000 + u64::from(i), d));
}
sim.strikes.known.push(Known {
site: id, class: SiteClass::Ramp, obs: Vec::new(),
est: Some(Estimate { pos: DVec2::new(0.0, 400.0), radius: 5.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
launches: 1, last: 0, state: SiteState::Active, aimed: false,
});
let carrier = sim.id();
let mut sam = Sam::new(carrier, SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0);
sam.missiles = 2;
sam.ground_rounds = 2;
sam.cooldown = 0;
sim.sams.push(sam);
let mut out = Out::default();
sim.order_strike(id, DVec3::ZERO, &mut out).unwrap();
let (mut ground, mut heard_ignition) = (Ground::default(), 0);
let mut saw_voice_before = false;
let mut saw_flame_before = false;
let mut rise = 0.0f64;
let mut all_messages = Vec::new();
for _ in 0..(launch::OPEN_TICKS as usize + strike::EJECT_TICKS as usize + 6) {
serve(&mut ground, &land, sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
all_messages.append(&mut out.messages);
if let Some(f) = sim.strikes.flights.first() {
let age = sim.tick - f.start;
if age < strike::EJECT_TICKS {
saw_voice_before |= out.engines.iter().any(|e| e.key == 0x7500_0000 + f.id * PARTS);
saw_flame_before |= out.models.iter().any(|m| m.name == "airdef:flame" && m.id == 0x7500_0000 + f.id * PARTS + 1);
rise = rise.max(f.pos.y - f.from.y);
}
if age == strike::EJECT_TICKS {
heard_ignition = out.sounds.iter().filter(|s| s.0 == sound::LAUNCH_S400).count();
}
}
}
assert!(rise > 10.0, "the ejection rose only {rise} blocks");
assert!(!saw_voice_before && !saw_flame_before, "powered effects during the unlit ejection");
assert_eq!(heard_ignition, 1, "exactly one ignition sound at the hand-over: {all_messages:?}");
}
#[test]
+529 -1
View File
@@ -1,5 +1,7 @@
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
use super::sight::{swept, FORECAST_AGE};
use super::battery::{Measure, RadarRole};
use super::regress::{answer_land, ridge_at};
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
use super::*;
fn flat() -> (Ground, Out) {
@@ -122,6 +124,9 @@ fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() {
let early = radar_at(&mut sim, SamKind::Radar, 120.0);
let id = drone_from(&mut sim, -150.0);
sim.sams[p].comps.0[Part::Sensor as usize] = 0.0;
// Hold fire: the fed track is now acted on (an unidentified contact is a candidate under the
// general rules, #133), and this test is about the feed, not about the intercept.
sim.sams[p].roles = 0;
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
}
@@ -254,3 +259,526 @@ fn the_same_seed_rolls_the_same_scan_and_damage() {
};
assert_eq!(run(), run());
}
// ---------------------------------------------------------------- #133: the class estimate
#[test]
fn the_classifier_steps_by_the_measurements_alone() {
// The same observed speeds give the same estimate whatever the contact truly is, and a
// contrary measurement replaces the hypothesis instead of being ignored.
let mut est = ClassEst::Unknown;
assert_eq!(est.step(1, 0.6), ClassEst::Unknown, "one blip says nothing of the class");
est = est.step(2, 0.6);
assert_eq!(est, ClassEst::Probable(Class::Drone));
est = est.step(3, 0.62);
assert_eq!(est, ClassEst::Firm(Class::Drone), "agreeing measurements firm the guess");
// The contact proves much faster (or the first readings misled): the hypothesis gives way,
// and one measurement is not enough to firm the new one.
est = est.step(4, 5.0);
assert_eq!(est, ClassEst::Probable(Class::Supersonic));
est = est.step(5, 5.1);
assert_eq!(est, ClassEst::Firm(Class::Supersonic));
// Whatever the true kind, the same observations read the same: a Kinzhal measured as a slow
// propeller is, to the network, a drone until its measurements say otherwise.
assert_eq!(ClassEst::Unknown.step(2, 0.5), ClassEst::Probable(Class::Drone));
}
#[test]
fn the_speed_bands_read_the_games_own_kinds_right() {
// The bands sit between the game's speed clusters: the measured speed of a kind reads as its
// class, so a slow Lancet is no jet and a Shahed no cruise missile. A fast ballistic and a
// supersonic missile fly alike (the Iskander and the Zircon): speed alone leaves that
// ambiguity, documented on `Class::of_speed`.
for kind in DroneKind::ALL {
let spec = kind.spec();
if spec.class == Class::Ballistic && spec.speed < 6.5 {
continue;
}
assert_eq!(Class::of_speed(spec.speed), spec.class, "{kind:?} at {} blocks a tick", spec.speed);
}
assert_eq!(Class::of_speed(5.0), Class::Supersonic, "a fast ballistic and a supersonic fly alike");
}
#[test]
fn the_first_blip_gives_no_class_and_no_speed() {
let mut sim = Sim::new(5);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let mut first = None;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[r].track(id) {
first = Some(*t);
break;
}
}
let t = first.expect("a track of the drone");
assert_eq!(t.hits, 1);
assert_eq!(t.class, ClassEst::Unknown, "the first measurement must not name a class");
assert_eq!(t.vel, DVec3::ZERO, "the true velocity must not leak into the track");
}
#[test]
fn tracks_of_different_kinds_one_class_firm_the_same_estimate() {
// A Shahed and a Gerbera are different machines of one class, flying alike; the picture both
// networks end up holding is the same: a firm slow drone, never a model name. (Faster kinds
// cross this little radar's reach between beam passes: too few measurements to firm anything.)
let roles = SamKind::S400.spec().roles;
let mut seen = Vec::new();
for kind in [DroneKind::Shahed, DroneKind::Gerbera] {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
// One radar: an uninterrupted chain of measurements (two early-warning radars do not
// exchange tracks — a radar is fed only when it serves fire control — so the second one
// would measure from a blank picture, its own chain apart).
radar_at(&mut sim, SamKind::Radar, 0.0);
let from = DVec3::new(-150.0, 95.0, 40.0);
sim.add_drone(kind, from, DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
let id = sim.drones.last().unwrap().id;
let mut est = None;
for _ in 0..700 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.picture().get(&id) {
est = Some(t.class);
}
}
assert_eq!(est, Some(ClassEst::Firm(Class::Drone)), "{kind:?}: {est:?}");
// The wording and the class-dependent decisions come from the estimate, not the machine.
let est = est.unwrap();
seen.push((est, est.name(), est.mark(), est.in_roles(roles)));
}
assert_eq!(seen[0], seen[1], "the same observations read differently for two kinds: {seen:?}");
}
#[test]
fn the_role_policy_keeps_the_unidentified_and_holds_fire_with_no_roles() {
let some = Class::Drone.bit() | Class::Jet.bit();
// An unidentified contact is not a block: it stays a candidate under the general rules.
assert!(ClassEst::Unknown.in_roles(some));
// No roles at all is holding fire: nothing is a candidate, the unidentified included.
assert!(!ClassEst::Unknown.in_roles(0), "hold fire must block the unidentified too");
// A probable guess is a block when its class is out of the roles, and a pass when in them.
assert!(ClassEst::Probable(Class::Drone).in_roles(some));
assert!(!ClassEst::Probable(Class::Cruise).in_roles(some));
assert!(ClassEst::Firm(Class::Jet).in_roles(some));
assert!(!ClassEst::Firm(Class::Ballistic).in_roles(0));
}
#[test]
fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() {
// The Gepard's roles are drones, jets and cruise missiles: a supersonic missile is out of them.
assert_eq!(SamKind::Gepard.spec().roles & Class::Supersonic.bit(), 0);
let mut sim = Sim::new(11);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Gepard, 0.0);
sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 95.0, -60.0), DVec3::Z, DVec3::new(0.0, 70.0, -700.0));
let id = sim.drones.last().unwrap().id;
sim.tick = 10;
let seed = |sim: &mut Sim, class| {
let d = sim.drones[0].clone();
sim.sams[p].tracks.retain(|t| t.id != d.id);
let source = sim.sams[p].id;
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
};
// Taken while the class was unknown: the general rules make it a candidate.
seed(&mut sim, ClassEst::Unknown);
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, Some(id), "an unidentified track is not its gun target");
// Classified: no longer a class the gun engages, and it is let go instead of being fired at.
seed(&mut sim, ClassEst::Firm(Class::Supersonic));
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, None, "the gun kept a track its roles do not cover");
}
#[test]
fn forecasts_and_relays_add_no_confidence() {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
let _b = radar_at(&mut sim, SamKind::Radar, 500.0);
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
let id = drone_from(&mut sim, -50.0);
// The source's own track: while no new measurement lands (the tick unchanged, the track only
// forecast onwards) the estimate must not move — a forecast is not data.
let mut prev: Option<(u64, ClassEst)> = None;
let mut relayed = 0;
for _ in 0..800 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[a].track(id).copied() {
if let Some((tick, class)) = prev {
assert!(t.tick > tick || t.class == class, "a forecast or a re-read firmed the class: {tick}->{:?} {:?}->{:?}", t.tick, class, t.class);
}
prev = Some((t.tick, t.class));
}
// The network's copy carries the estimate as it was, with its measurement's age; passing
// it on adds nothing (the receiver never measures: own_tick stays 0).
if let Some(t) = sim.sams[n].track(id).copied() {
relayed += 1;
assert_eq!(t.own_tick, 0);
let freshest = sim.sams.iter().filter(|s| s.id != sim.sams[n].id).filter_map(|s| s.track(id)).max_by_key(|t| t.tick);
assert_eq!(Some(t.class), freshest.map(|f| f.class), "a relay altered the estimate");
}
}
assert!(relayed > 100, "the network never passed the track ({relayed})");
assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact");
}
// ---------------------------------------------------------------- separate radar profiles (#134)
fn radar_with_role(sim: &mut Sim, role: RadarRole, x: f64) -> usize {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, DVec3::new(x, 70.0, 0.0), 0.0);
sam.set_radar_role(role);
sim.sams.push(sam);
sim.sams.len() - 1
}
fn bearing(from: DVec3, to: DVec3) -> f64 {
(to.x - from.x).atan2(-(to.z - from.z))
}
/// The beam of every radar is pointed at one of `targets` in turn, so a test
/// does not depend on where the initial phase happened to be.
fn sweep(sim: &mut Sim, ground: &mut Ground, radars: &[usize], targets: &[DVec3], tick: u64) {
sim.tick = tick;
for (k, &i) in radars.iter().enumerate() {
let at = targets[(tick as usize + k) % targets.len()];
sim.sams[i].beam = bearing(sim.sams[i].pos, at);
}
sim.update_sight(ground);
}
#[derive(Default, Debug, PartialEq, Eq)]
struct ProfileStats {
first_high: Option<u64>,
first_low_refined: Option<u64>,
first_close_fire: Option<u64>,
max_channels: usize,
search_or_height_authorized: bool,
}
/// A low contact at 330 blocks (above the search/engagement horizon but below
/// the mast's), a high contact at 700/430 (inside the search reach but outside
/// the mast's and engagement's local search), and two close contacts for the
/// tracked-contact channels.
fn profile_world(roles: &[RadarRole]) -> (Sim, Vec<usize>, Vec<u32>, Ground) {
let mut sim = Sim::new(134);
let radars: Vec<usize> = roles.iter().map(|role| radar_with_role(&mut sim, *role, 0.0)).collect();
sim.add_drone(DroneKind::Shahed, DVec3::new(330.0, 95.0, 0.0), DVec3::Z, DVec3::new(330.0, 95.0, 0.0));
let low = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Shahed, DVec3::new(700.0, 500.0, 0.0), DVec3::Z, DVec3::new(700.0, 500.0, 0.0));
let high = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let close1 = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 130.0, 40.0), DVec3::Z, DVec3::new(180.0, 130.0, 40.0));
let close2 = sim.drones.last().unwrap().id;
(sim, radars, vec![low, high, close1, close2], Ground::default())
}
fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec<usize>, Vec<u32>) {
let (mut sim, radars, ids, mut ground) = profile_world(roles);
let [low, high, close1, close2] = [ids[0], ids[1], ids[2], ids[3]];
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
let mut stats = ProfileStats::default();
for tick in 1..=ticks {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
for &i in &radars {
let sam = &sim.sams[i];
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
match t.id {
id if id == high && stats.first_high.is_none() => stats.first_high = Some(tick),
id if id == low && t.product == Measure::Refine && stats.first_low_refined.is_none() => stats.first_low_refined = Some(tick),
id if (id == close1 || id == close2) && t.product == Measure::Fire && t.own_authorizes(sim.tick) && stats.first_close_fire.is_none() => stats.first_close_fire = Some(tick),
_ => {}
}
}
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.max_channels = stats.max_channels.max(sam.own_channels_used());
}
}
(stats, sim, radars, ids)
}
#[test]
fn each_profile_is_useful_alone_and_the_full_set_covers_all_three_jobs() {
let search = run_profile_world(&[RadarRole::Search], 500).0;
assert!(search.first_high.is_some(), "the search radar gives no early high plot: {search:?}");
assert!(search.first_low_refined.is_none(), "search refined a low contact it does not reach: {search:?}");
assert!(search.first_close_fire.is_none(), "search authorized a launch: {search:?}");
let height = run_profile_world(&[RadarRole::Height], 500).0;
assert!(height.first_high.is_none(), "the mast radar searched beyond its local patch: {height:?}");
assert!(height.first_low_refined.is_some(), "the mast radar did not refine the low contact: {height:?}");
assert!(height.first_close_fire.is_none(), "the mast radar authorized a launch: {height:?}");
let engagement = run_profile_world(&[RadarRole::Engagement], 500).0;
assert!(engagement.first_high.is_none(), "the engagement radar searched beyond its local patch: {engagement:?}");
assert!(engagement.first_low_refined.is_none(), "the engagement radar reached a low contact below the horizon: {engagement:?}");
assert!(engagement.first_close_fire.is_some(), "the engagement radar gave no fire plot: {engagement:?}");
assert!(engagement.max_channels <= 2, "more than two tracked contacts: {engagement:?}");
let search_height = run_profile_world(&[RadarRole::Search, RadarRole::Height], 500).0;
assert!(search_height.first_high.is_some() && search_height.first_low_refined.is_some());
assert!(search_height.first_close_fire.is_none(), "a search/height pair authorized a launch: {search_height:?}");
let search_engagement = run_profile_world(&[RadarRole::Search, RadarRole::Engagement], 500).0;
assert!(search_engagement.first_high.is_some() && search_engagement.first_close_fire.is_some());
assert!(search_engagement.first_low_refined.is_none(), "the pair covered the mast's low gap: {search_engagement:?}");
let height_engagement = run_profile_world(&[RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(height_engagement.first_low_refined.is_some() && height_engagement.first_close_fire.is_some());
assert!(height_engagement.first_high.is_none(), "the pair covered the search's far picture: {height_engagement:?}");
let full = run_profile_world(&[RadarRole::Search, RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(full.first_high.is_some() && full.first_low_refined.is_some() && full.first_close_fire.is_some(), "{full:?}");
assert!(!full.search_or_height_authorized, "a non-fire radar authorized a launch");
// There is no set bonus in the profile table: a duplicated station adds no
// function, and the full set's advantage is only the union of the three jobs.
let duplicate = run_profile_world(&[RadarRole::Search, RadarRole::Search], 500).0;
assert!(duplicate.first_low_refined.is_none() && duplicate.first_close_fire.is_none(), "two search radars invented another function: {duplicate:?}");
}
#[test]
fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
let mut sim = Sim::new(1341);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let receiver = {
let id = sim.id();
let mut s400 = Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0);
// A blind receiver: only the network can give it a track.
s400.comps.0[Part::Sensor as usize] = 0.0;
s400.roles = 0xff;
sim.sams.push(s400);
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(200.0, 120.0, 0.0), DVec3::Z, DVec3::new(200.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=120 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let own = sim.sams[engagement].track(id).expect("the engagement radar measured the target");
assert_eq!(own.source, sim.sams[engagement].id);
assert_eq!(own.product, Measure::Fire);
assert!(own.quality >= FIRE_QUALITY && own.own_authorizes(sim.tick));
let relayed = sim.sams[receiver].track(id).expect("the network shared the plot");
assert_eq!(relayed.own_tick, 0, "a relay became the receiver's own measurement");
assert_eq!(relayed.tick, own.tick, "a relay refreshed the measurement's age");
assert!(relayed.product == Measure::Fire && relayed.quality == own.quality, "relay lost product/quality");
assert_eq!(relayed.source, sim.sams[engagement].id, "relay lost the measuring station");
assert!(!relayed.own_authorizes(sim.tick));
let opts = why::Opts { last_chance: false, far_shots: false };
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_none(), "a relayed plot authorized a launch");
}
// A launcher without a radar may use the supporting radar's own confirmed plot.
sim.sams[receiver].set_mode(battery::SamMode::LauncherOnly);
for tick in 121..=122 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let relayed = *sim.sams[receiver].track(id).expect("the launcher re-received the network plot");
assert!(why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick));
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, &relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_some());
}
// The search radar's plot is coarse: it does not authorize even a launcher.
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[search]], id, sim.tick));
// A broken data link ends the cue even while the radar itself still measures.
sim.sams[engagement].comps.0[Part::Comms as usize] = 0.0;
assert_eq!(sim.sams[engagement].link_range(), 0.0);
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
}
#[test]
fn the_air_picture_prefers_the_better_plot_at_one_tick() {
let mut sim = Sim::new(1345);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let track = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
for tick in 1..=5 {
sweep(&mut sim, &mut ground, &[search, track], &targets, tick);
}
let pic = sim.air_picture();
let t = pic.tracks.iter().find(|t| t.id == id).expect("the raid is on the picture");
assert_eq!(t.source, sim.sams[track].id, "a coarse plot won over the better one at the same tick");
assert_eq!(t.product, Measure::Fire);
assert!(t.own_authorizes(sim.tick));
}
#[test]
fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let mut sim = Sim::new(1344);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
for x in [100.0, 140.0, 180.0, 220.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let mut ground = Ground::default();
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
for tick in 1..=40 {
sweep(&mut sim, &mut ground, &[engagement], &targets, tick);
}
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();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
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)));
}
#[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 20.0);
sim.add_drone(DroneKind::Gerbera, 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 mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=80 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[engagement].track(id).is_some_and(|t| t.own_authorizes(sim.tick)));
let healthy = sim.sams[engagement].track(id).unwrap().own_quality;
// Off: the station emits nothing, its own plots stop, the neighbour still feeds the network.
sim.sams[engagement].radar_on = false;
let before = sim.sams[engagement].track(id).map(|t| t.own_tick);
for tick in 81..=110 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(!sim.sams[engagement].radar_up());
assert_eq!(sim.sams[engagement].track(id).map(|t| t.own_tick), before, "a silent radar renewed its own plot");
assert!(sim.sams[search].track(id).is_some_and(|t| t.own_tick > 0));
// Damage: a worn sensor still measures, with worse quality and no launch right.
sim.sams[engagement].radar_on = true;
sim.sams[engagement].comps.0[Part::Sensor as usize] = 0.2;
for tick in 111..=180 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let worn = sim.sams[engagement].track(id).expect("a worn radar still measures");
assert!(worn.own_quality < healthy, "damage did not lower quality: {worn:?}");
assert!(!worn.own_authorizes(sim.tick), "a worn sensor still authorized a launch");
}
#[test]
fn multifunction_and_embedded_radars_keep_their_fire_authority() {
let mut sim = Sim::new(1343);
let multi = radar_with_role(&mut sim, RadarRole::Multifunction, 0.0);
let pantsir = radar_at(&mut sim, SamKind::Pantsir, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [multi, pantsir];
for tick in 1..=100 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[multi].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "the universal profile lost its own fire plot");
assert!(sim.sams[pantsir].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "an embedded radar lost its own fire plot");
}
#[test]
fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
// One seed and one ridge: the low contact hides behind it, the high one flies over it,
// and two close contacts compete for the engagement channels on the far side.
let targets = [
DVec3::new(250.0, 84.0, 0.0),
DVec3::new(700.0, 500.0, 0.0),
DVec3::new(240.0, 90.0, 30.0),
DVec3::new(260.0, 95.0, -20.0),
];
#[derive(Default, Debug)]
struct RidgeStats {
low_marked: bool,
low_refined: bool,
low_fire: bool,
high_marked: bool,
track_channels: usize,
nonfire_authorized: bool,
}
let run = |stations: &[(RadarRole, DVec3)], land| -> RidgeStats {
let mut sim = Sim::new(134);
let radars: Vec<usize> = stations
.iter()
.map(|(role, pos)| {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, *pos, 0.0);
sam.set_radar_role(*role);
sim.sams.push(sam);
sim.sams.len() - 1
})
.collect();
for (k, pos) in targets.iter().enumerate() {
let kind = if k < 2 { DroneKind::Shahed } else { DroneKind::Gerbera };
sim.add_drone(kind, *pos, DVec3::Z, *pos);
}
let ids: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
let mut ground = Ground::default();
// Unknown land hides nothing: let the heights answer before any measurement counts.
for tick in 1..=60 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
answer_land(&mut ground, land, tick);
}
for i in &radars {
sim.sams[*i].tracks.clear();
}
let mut stats = RidgeStats::default();
for tick in 61..=560 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
answer_land(&mut ground, land, tick);
for &i in &radars {
let sam = &sim.sams[i];
let profile = sam.radar_profile();
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
if t.id == ids[0] {
stats.low_marked = true;
stats.low_refined |= t.product == Measure::Refine;
stats.low_fire |= t.own_authorizes(sim.tick);
}
stats.high_marked |= t.id == ids[1];
}
if profile.id == "radar_track" {
stats.track_channels = stats.track_channels.max(sam.own_channels_used());
}
if profile.id == "radar_search" || profile.id == "radar_height" {
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
}
}
stats
};
let near = DVec3::new(0.0, 64.0, 0.0);
let far = DVec3::new(220.0, 64.0, 0.0);
let ridge = ridge_at(150, 100, 60);
let search = run(&[(RadarRole::Search, near)], &ridge);
assert!(search.high_marked, "the search radar lost the high contact over the ridge: {search:?}");
assert!(!search.low_marked, "the search radar saw through the ridge: {search:?}");
// The same station on flat land does mark the low contact: the ridge is what hides it.
let flat = ridge_at(150, 0, 60);
let control = run(&[(RadarRole::Search, near)], &flat);
assert!(control.low_marked, "the control lost the low contact on flat land: {control:?}");
let height = run(&[(RadarRole::Height, far)], &ridge);
assert!(height.low_refined, "the mast did not refine the low contact behind the ridge: {height:?}");
assert!(!height.high_marked && !height.low_fire, "the mast left its patch or authorized a launch: {height:?}");
let engagement = run(&[(RadarRole::Engagement, far)], &ridge);
assert!(engagement.low_fire, "the engagement radar gave no fire plot on the low contact: {engagement:?}");
assert!(!engagement.high_marked, "the engagement radar searched beyond its patch: {engagement:?}");
assert!(engagement.track_channels <= 2, "more than two tracked contacts: {engagement:?}");
let full = run(&[(RadarRole::Search, near), (RadarRole::Height, far), (RadarRole::Engagement, far)], &ridge);
assert!(full.high_marked && full.low_refined && full.low_fire, "the full set lost a job on the ridge: {full:?}");
assert!(!full.nonfire_authorized, "a non-fire radar authorized a launch: {full:?}");
assert!(full.track_channels <= 2, "the engagement radar exceeded its channels: {full:?}");
}
+225 -36
View File
@@ -8,12 +8,15 @@
//! (a period by the kind of radar; an electronic one also revisits what it holds
//! more often), a target is measured when the beam passes it, with a chance that
//! falls with range and size, and the measurement is kept as a *track*: where it
//! was and how fast it went then, and when. Between measurements the track is
//! was measured, how fast it then seemed to go (from the measured places, never
//! the target's own figures), and when. Between measurements the track is
//! carried on by that velocity (a forecast, shown as one), and after three missed
//! scans it is dropped. A fire-control lock on a target the system is engaging is
//! a dedicated channel: it measures every tick while the target is in reach and in
//! sight. The network passes tracks with the age of their measurement; relaying
//! makes none of them fresher.
//! sight. The track also carries what the measurements say of the contact's class,
//! the estimate growing only on real measurements: a forecast, a relayed copy adds
//! nothing to it. The network passes tracks with the age of their measurement;
//! relaying makes none of them fresher.
use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
@@ -24,14 +27,16 @@ 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`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
/// A fire plot below this quality is not confirmed enough to authorize a launch.
pub const FIRE_QUALITY: u8 = 50;
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
const HORIZON: f64 = 35.0;
pub(super) const HORIZON: f64 = 35.0;
/// Anything this near is seen (and heard), whatever hides it.
const NEAR: f64 = 24.0;
pub(super) const NEAR: f64 = 24.0;
pub(super) struct Horizon {
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
@@ -87,7 +92,7 @@ pub(super) fn antenna(sam: &Sam) -> DVec3 {
}
fn sensor_span(sam: &Sam) -> f64 {
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
sam.kind.spec().sensor * sam.radar_profile().reach
}
/// How far a system's search radar reaches for this kind at `height` over the land:
@@ -97,7 +102,7 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.radar_fit() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25);
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
@@ -142,7 +147,7 @@ impl Sim {
let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit());
let height = LOW_KIND.spec().clearance;
let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach);
let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25);
let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR);
let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s)));
@@ -243,17 +248,31 @@ impl Ident {
}
/// What a system knows of one target: the last measurement, not the target itself.
///
/// The track never carries the target's type or its true velocity (#133): `class` is what the
/// radars inferred from the measurements so far, `vel` the speed those measurements showed —
/// none from the first blip, then the change of the measured places between real measurements,
/// smoothed a little. The forecast and the guns live with that.
#[derive(Clone, Copy, Debug)]
pub struct Track {
pub id: u32,
/// What the radar made of it when it measured (the class the picture shows).
pub kind: DroneKind,
/// Where it was and how it went when last measured (blocks, blocks a tick).
/// What the radars make of it from the measurements (never the target's own type).
pub class: ClassEst,
/// Where it was measured and how fast it seemed to go then (blocks, blocks a tick).
pub pos: DVec3,
pub vel: DVec3,
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
pub tick: u64,
pub own_tick: u64,
/// The station that measured the latest plot, and what it is good for.
pub source: u32,
pub product: battery::Measure,
/// Measurement quality (0..100), separate from identification (`hits`).
pub quality: u8,
/// This system's own measurement provenance. A fresher relay may replace
/// the published plot without granting or erasing the station's own right.
pub own_product: battery::Measure,
pub own_quality: u8,
/// Ticks the track lives without a new measurement.
pub ttl: u32,
pub hits: u8,
@@ -294,6 +313,25 @@ impl Track {
pub fn own_within(&self, now: u64, age: u64) -> bool {
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
}
/// The station's own measurement was a confirmed fire plot, fresh enough.
/// A relayed plot has `own_tick == 0` and never passes this test.
pub fn own_fire_within(&self, now: u64, age: u64) -> bool {
self.own_within(now, age) && self.own_product.allows_fire() && self.own_quality >= FIRE_QUALITY
}
/// Own plot good enough for a launcher's ordinary shot.
pub fn own_authorizes(&self, now: u64) -> bool {
self.own_fire_within(now, MISSILE_AGE)
}
/// Who measured the latest plot, as an ID (`0`: no station).
pub fn measured_by(&self) -> Option<u32> {
(self.source != 0).then_some(self.source)
}
/// One passive optical look at this contact (#136): refines the class alone. The plot, its
/// age, source, quality and the station's own fire rights are untouched — optics never
/// authorize a shot and never make a track fresher.
pub fn refine_class_optical(&mut self, class: Class, uncertainty: f64) {
self.class = self.class.step_optical(class, uncertainty);
}
pub fn ident(&self) -> Ident {
match self.hits {
0 | 1 => Ident::Unknown,
@@ -310,16 +348,12 @@ impl Track {
impl Sam {
/// Fictional antenna height and scan characteristics for gameplay roles.
pub(super) fn sensor_mast(&self) -> f64 {
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
self.kind.spec().mast + self.radar_profile().mast
}
pub(super) fn scan_profile(&self) -> Scan {
if self.kind != SamKind::Radar { return self.kind.scan(); }
match self.radar_role {
battery::RadarRole::Multifunction => self.kind.scan(),
battery::RadarRole::Search => Scan { period: 170, agile: false },
battery::RadarRole::Engagement => Scan { period: 70, agile: true },
battery::RadarRole::Height => Scan { period: 140, agile: false },
}
let profile = self.radar_profile();
Scan { period: profile.cycle, agile: profile.agile }
}
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
@@ -332,6 +366,10 @@ impl Sam {
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
/// Refined/fire channels this station is currently using.
pub fn own_channels_used(&self) -> usize {
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count()
}
}
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
@@ -345,10 +383,18 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
match index.get(&t.id) {
Some(&k) => {
let mine = &mut tracks[k];
if t.tick > mine.tick {
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
// Prefer the fresher plot; at the same tick the better one (a fire plot
// over a coarse search plot), without making anything newer.
if t.tick > mine.tick || (t.tick == mine.tick && t.quality > mine.quality) {
// A relayed plot is published with its source/quality, but it
// neither refreshes nor erases this station's own measurement and its right.
let (own_tick, own_product, own_quality, locked) = if t.own_tick > 0 {
(t.own_tick, t.own_product, t.own_quality, t.locked)
} else {
(mine.own_tick, mine.own_product, mine.own_quality, mine.locked)
};
let hits = mine.hits.max(t.hits);
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t };
}
}
None => {
@@ -358,6 +404,23 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
}
}
/// A plot's quality (0..100). It uses only the measured geometry and the
/// 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 {
let ratio = ratio.clamp(0.0, 1.0);
let base = match profile.id {
"radar_search" => 46.0 - 14.0 * ratio,
"radar_height" => 74.0 - 12.0 * ratio + if height < 120.0 { 8.0 } else if height < 200.0 { 3.0 } else { 0.0 },
"radar_track" => 88.0 - 12.0 * ratio,
"radar_multi" => 72.0 - 14.0 * ratio,
_ => 78.0 - 14.0 * ratio,
};
// A search plot is coarse whatever the profile; only a matched refinement or
// a fire plot gets the profile's accuracy.
let base = if product == battery::Measure::Search { base.min(48.0) } else { base };
(base * sam.radar_fit()).round().clamp(5.0, 99.0) as u8
}
impl Sim {
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
/// into the tracks, old tracks out, and the network's tracks shared.
@@ -401,6 +464,7 @@ impl Sim {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let profile = sam.radar_profile();
let scan = sam.scan_profile();
let period = sam.scan_ticks();
let w = TAU / period;
@@ -408,6 +472,9 @@ impl Sim {
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let local = spec.sensor * profile.local;
// Channels already refining or holding fire plots. Search plots do not use one.
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count();
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
@@ -415,7 +482,7 @@ impl Sim {
}
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
if dist > spec.sensor * profile.reach.max(1.0) * 1.2 {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
@@ -423,13 +490,36 @@ impl Sim {
// 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 revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
// A search radar's network track cues this fictional tracking radar to look, but is
// never itself a measurement: reach, terrain, probability and noise still apply.
let cue = sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement
// A network plot cues a fire-quality radar to look, but is never itself a
// measurement: reach, terrain, probability and noise still apply.
let cue = profile.allows(battery::Measure::Fire)
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
if !(in_beam || locked || revisit || cue) {
continue;
}
// The separate stations search their own patch; a cue or an already held
// contact may be followed beyond it, never an arbitrary target of the map.
if profile.local < 1.0 && dist > local && !locked && !(cue || held.is_some_and(|t| t.own_tick > 0)) {
continue;
}
// The tracked-contact channels are a hard limit: work per tick stays bounded
// 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
// 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 = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
let mut product = if profile.allows(battery::Measure::Fire) {
battery::Measure::Fire
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
// Refinement only applies to a contact already matched, own or network.
battery::Measure::Refine
} else {
battery::Measure::Search
};
let wants_channel = product != battery::Measure::Search && !holds_channel;
if profile.channels > 0 && wants_channel && used >= profile.channels as usize {
product = battery::Measure::Search;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
let reach = reach(sam, d.kind, height);
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
@@ -446,17 +536,40 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
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 measured = d.pos + noise;
let quality = plot_quality(sam, profile, product, dist / reach.max(1.0), height);
if profile.channels > 0 && wants_channel && product != battery::Measure::Search {
used += 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
// 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 => {
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)) };
(vel, p.class.step(hits, vel.length()))
}
_ => (DVec3::ZERO, ClassEst::Unknown),
};
fresh.push(Track {
id: d.id,
kind: d.kind,
pos: d.pos + noise,
vel: d.vel,
class,
pos: measured,
vel,
tick: now,
own_tick: now,
source: sam.id,
product,
quality,
own_product: product,
own_quality: quality,
ttl,
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
hits,
locked,
});
}
@@ -471,7 +584,7 @@ impl Sim {
if now % 20 == 0 {
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) {
self.intel.revealed.push((s.id, s.pos, now));
self.intel.observe(s, now, ew::Seen::Emission);
}
}
}
@@ -482,7 +595,37 @@ impl Sim {
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick > 0 && t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
// One freshest track per radar is all a cue needs: the posts never walk every contact.
let cues: Vec<(u32, DVec3, f64, Track)> = if self.sams.iter().any(|s| s.kind == SamKind::Optical) {
shared
.iter()
.filter_map(|(id, at, range, tracks)| tracks.iter().max_by_key(|t| t.tick).map(|t| (*id, *at, *range, *t)))
.collect()
} else {
Vec::new()
};
for sam in &mut self.sams {
if sam.kind == SamKind::Optical {
// An optical post receives a cue, not a track: the freshest network measurement within
// link range only points its head, and none of it enters `tracks`, `seen` or `own`.
sam.seen.clear();
sam.own.clear();
if sam.alive() && !sam.moving() && sam.link_range() > 0.0 {
let mine = sam.link_range();
let mut best: Option<Track> = None;
for (id, at, range, t) in &cues {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine)
&& best.is_none_or(|b: Track| t.tick > b.tick)
{
best = Some(*t);
}
}
if let Some(t) = best {
sam.optical.offer_cue(t);
}
}
continue;
}
if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
@@ -490,7 +633,7 @@ impl Sim {
for (id, at, range, tracks) in &shared {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
for t in tracks {
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t });
}
}
}
@@ -504,6 +647,9 @@ impl Sim {
}
}
}
// Passive optics (#136) look after the network has spoken: a cue is only a cue, and every
// observation it makes is its own, never a track and never an emission.
self.update_optics(ground);
}
/// Whether any system's radar holds this drone (the player's radar shows only those).
@@ -520,8 +666,25 @@ impl Sim {
let mut tracks: Vec<Track> = if unaided {
self.drones
.iter()
// No system is deployed: no estimation happens, the fallback is the sky as it is
// (the screens have always had it), with the figures a system would show.
.filter(|d| d.alive())
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
.map(|d| Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 0,
product: battery::Measure::Fire,
quality: 100,
own_product: battery::Measure::Fire,
own_quality: 100,
ttl: 1,
hits: 3,
locked: false,
})
.collect()
} else {
self.picture().into_values().collect()
@@ -530,11 +693,12 @@ impl Sim {
AirPicture { now, tracks, unaided }
}
/// The freshest track of each drone any system holds: the air picture.
/// The freshest track of each drone any system holds: the air picture. At one
/// tick the better plot (quality, then product) is the one the player sees.
pub fn picture(&self) -> HashMap<u32, Track> {
let mut best: HashMap<u32, Track> = HashMap::new();
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) {
best.insert(t.id, *t);
}
}
@@ -612,3 +776,28 @@ mod low_view_tests {
assert!(seen > 0 && tint.as_millis() < 100, "{tint:?}");
}
}
#[cfg(test)]
mod relay_tests {
use super::*;
/// 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).
#[test]
fn a_repeated_relay_adds_no_confidence_and_stays_foreign() {
let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 400, hits: 1, locked: false };
let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, source: 2, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 2, locked: false };
let mut tracks = vec![ours];
let mut index: HashMap<u32, usize> = HashMap::from([(7, 0)]);
merge(&mut tracks, &mut index, relay);
assert_eq!(tracks[0].own_tick, 90, "a relayed track is not the receiver's own measurement");
for _ in 0..5 {
merge(&mut tracks, &mut index, relay);
}
assert_eq!(tracks.len(), 1, "a relay of a held measurement is one track");
assert_eq!(tracks[0].hits, 2, "a repeated relay added confidence");
assert_eq!(tracks[0].class, ClassEst::Probable(Class::Drone), "a relay altered the estimate");
assert_eq!(tracks[0].tick, 100, "a relay refreshed the measurement");
assert_eq!(tracks[0].own_tick, 90, "a relay became the receiver's own");
}
}
+542
View File
@@ -0,0 +1,542 @@
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
// Game-scale values, not real weapon data; the catalog is the only copy.
/// Share of the old slew speed a launcher keeps when it has no rate of its own.
const DRIVE_SCALE: f64 = 0.4;
/// Ticks a drive takes to reach its top speed (and to stop from it).
const DRIVE_RAMP: f64 = 8.0;
const DRIVE_TRAINABLE: (f64, f64) = (0.12, 0.0);
const DRIVE_VERTICAL: (f64, f64) = (0.15, 0.0);
const DRIVE_OTHER: (f64, f64) = (0.05, 0.05);
/// Ballistic flight's gravity, blocks a tick².
const GRAVITY: f64 = 0.05;
/// Height over the target where the Oreshnik's blocks release their submunitions.
const BLOCK_SPLIT: f64 = 300.0;
/// How near a depot a system reloads straight from it.
const DEPOT_REACH: f64 = 60.0;
/// How near a truck must come to hand a reload over, or to load up at a depot.
const HANDOVER: f64 = 10.0;
/// What a truck carries.
const TRUCK_LOAD: u32 = 2;
const STOCK_LIMIT: u32 = 1000000;
const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec {
name: "Шахед-136",
key: "shahed",
model: "airdef:shahed",
speed: 0.6,
turn: 0.035,
cruise: 45.0,
clearance: 18.0,
dive: 32.0,
warhead: 3,
scale: 1.3,
engine: Engine::Prop(1.34, 1.0),
decoy: false,
stealth: 1.0,
rcs: 0.3,
sound: (sound::DRONE_SHAHED, 1.0, 48),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_GERAN3: DroneSpec = DroneSpec {
name: "Герань-3",
key: "geran3",
model: "airdef:geran3",
speed: 1.6,
turn: 0.03,
cruise: 60.0,
clearance: 18.0,
dive: 50.0,
warhead: 2,
scale: 1.15,
engine: Engine::Jet(0.34, 1.55, 1.0),
decoy: false,
stealth: 1.1,
rcs: 0.4,
sound: (sound::DRONE_GERAN3, 1.0, 40),
class: Class::Jet,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_LANCET: DroneSpec = DroneSpec {
name: "Ланцет-3",
key: "lancet",
model: "airdef:lancet",
speed: 1.1,
turn: 0.07,
cruise: 25.0,
clearance: 10.0,
dive: 38.0,
warhead: 1,
scale: 0.9,
engine: Engine::Prop(0.93, 0.55),
decoy: false,
stealth: 1.4,
rcs: 0.08,
sound: (sound::DRONE_LANCET, 1.0, 32),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_GERBERA: DroneSpec = DroneSpec {
name: "Гербера",
key: "gerbera",
model: "airdef:gerbera",
speed: 0.5,
turn: 0.04,
cruise: 40.0,
clearance: 15.0,
dive: 30.0,
warhead: 0,
scale: 1.1,
engine: Engine::Prop(1.03, 0.9),
decoy: true,
stealth: 0.9,
rcs: 0.4,
sound: (sound::DRONE_SHAHED, 1.3, 40),
class: Class::Drone,
ballistic: None,
launch_sound: sound::LAUNCH_S400_EJECT,
};
const DRONE_SPEC_KH101: DroneSpec = DroneSpec {
name: "Х-101",
key: "kh101",
model: "airdef:kh101",
speed: 2.4,
turn: 0.025,
cruise: 0.0,
clearance: 12.0,
dive: 26.0,
warhead: 6,
scale: 1.6,
engine: Engine::Jet(-0.27, 1.4, 0.6),
decoy: false,
stealth: 1.5,
rcs: 0.05,
sound: (sound::DRONE_CRUISE, 1.0, 50),
class: Class::Cruise,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_KALIBR: DroneSpec = DroneSpec {
name: "Калибр",
key: "kalibr",
model: "airdef:kalibr",
speed: 2.1,
turn: 0.025,
cruise: 0.0,
clearance: 15.0,
dive: 26.0,
warhead: 5,
scale: 1.5,
engine: Engine::Jet(-0.2, 1.5, 0.6),
decoy: false,
stealth: 1.3,
rcs: 0.15,
sound: (sound::DRONE_CRUISE, 1.2, 50),
class: Class::Cruise,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_KH22: DroneSpec = DroneSpec {
name: "Х-22",
key: "kh22",
model: "airdef:kh22",
speed: 4.0,
turn: 0.03,
cruise: 140.0,
clearance: 40.0,
dive: 150.0,
warhead: 7,
scale: 1.8,
engine: Engine::Rocket(1.5, 1.3),
decoy: false,
stealth: 1.4,
rcs: 1.0,
sound: (sound::DRONE_ROCKET, 0.8, 46),
class: Class::Supersonic,
ballistic: None,
launch_sound: sound::LAUNCH_PATRIOT,
};
const DRONE_SPEC_ZIRCON: DroneSpec = DroneSpec {
name: "Циркон",
key: "zircon",
model: "airdef:zircon",
speed: 5.5,
turn: 0.025,
cruise: 90.0,
clearance: 30.0,
dive: 110.0,
warhead: 6,
scale: 1.4,
engine: Engine::Rocket(1.5, 1.1),
decoy: false,
stealth: 2.0,
rcs: 0.4,
sound: (sound::DRONE_ROCKET, 1.35, 46),
class: Class::Supersonic,
ballistic: None,
launch_sound: sound::LAUNCH_S400,
};
const DRONE_SPEC_ISKANDER: DroneSpec = DroneSpec {
name: "Искандер-М",
key: "iskander",
model: "airdef:iskander",
speed: 5.0,
turn: 0.04,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 8,
scale: 1.8,
engine: Engine::Rocket(1.5, 1.6),
decoy: false,
stealth: 1.6,
rcs: 0.6,
sound: (sound::DRONE_ROCKET, 0.7, 46),
class: Class::Ballistic,
ballistic: Some(1000.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_KINZHAL: DroneSpec = DroneSpec {
name: "Кинжал",
key: "kinzhal",
model: "airdef:kinzhal",
speed: 7.5,
turn: 0.03,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 8,
scale: 1.7,
engine: Engine::Rocket(1.5, 1.5),
decoy: false,
stealth: 2.2,
rcs: 0.5,
sound: (sound::DRONE_ROCKET, 0.6, 46),
class: Class::Ballistic,
ballistic: Some(1500.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIK: DroneSpec = DroneSpec {
name: "Орешник",
key: "oreshnik",
model: "airdef:iskander",
speed: 9.0,
turn: 0.0,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 0,
scale: 2.6,
engine: Engine::Rocket(1.5, 2.4),
decoy: false,
stealth: 3.0,
rcs: 2.0,
sound: (sound::DRONE_ROCKET, 0.5, 46),
class: Class::Ballistic,
ballistic: Some(2600.0),
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIKBLOCK: DroneSpec = DroneSpec {
name: "Орешник: блок",
key: "oreshnik_block",
model: "airdef:reentry",
speed: 9.0,
turn: 0.0,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 4,
scale: 1.6,
engine: Engine::Rocket(1.0, 1.0),
decoy: false,
stealth: 3.5,
rcs: 0.4,
sound: (sound::DRONE_BALLISTIC, 0.8, 9999),
class: Class::Ballistic,
ballistic: None,
launch_sound: sound::LAUNCH_S500,
};
const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec {
name: "Орешник: суббоеприпас",
key: "oreshnik_sub",
model: "airdef:reentry",
speed: 9.0,
turn: 0.05,
cruise: 0.0,
clearance: 0.0,
dive: 0.0,
warhead: 3,
scale: 1.1,
engine: Engine::Rocket(1.0, 1.0),
decoy: false,
stealth: 4.0,
rcs: 0.08,
sound: (sound::DRONE_BALLISTIC, 1.0, 9999),
class: Class::Ballistic,
ballistic: None,
launch_sound: sound::LAUNCH_S500,
};
const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec {
model: "airdef:pac3",
speed: 5.5,
accel: 0.35,
turn: 0.3,
boost: 8,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.9,
fuse: 4.0,
life: 240,
scale: 1.0,
flame: 1.0,
rear: 28.0,
seeker: 110.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.0),
};
const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec {
model: "airdef:m57e6",
speed: 5.0,
accel: 0.5,
turn: 0.32,
boost: 5,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.82,
fuse: 3.0,
life: 160,
scale: 0.85,
flame: 0.65,
rear: 28.0,
seeker: 0.0,
launch_sound: sound::LAUNCH_PANTSIR,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.12),
};
const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec {
model: "airdef:m48n6",
speed: 7.0,
accel: 0.5,
turn: 0.22,
boost: 8,
cold: 20,
eject: 2.4,
eject_drag: 0.07,
pk: 0.9,
fuse: 5.0,
life: 300,
scale: 1.5,
flame: 1.4,
rear: 30.0,
seeker: 120.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.88),
};
const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec {
model: "airdef:m77n6",
speed: 9.0,
accel: 0.6,
turn: 0.22,
boost: 8,
cold: 24,
eject: 2.6,
eject_drag: 0.07,
pk: 0.95,
fuse: 6.0,
life: 320,
scale: 1.7,
flame: 1.6,
rear: 32.0,
seeker: 120.0,
launch_sound: sound::LAUNCH_S500_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.8),
};
const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec {
model: "airdef:irist_missile",
speed: 7.0,
accel: 0.5,
turn: 0.35,
boost: 6,
cold: 8,
eject: 1.8,
eject_drag: 0.1,
pk: 0.9,
fuse: 4.0,
life: 260,
scale: 0.95,
flame: 0.9,
rear: 28.0,
seeker: 90.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
};
const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec {
model: "airdef:amraam_missile",
speed: 6.0,
accel: 0.45,
turn: 0.3,
boost: 6,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.85,
fuse: 4.0,
life: 260,
scale: 0.9,
flame: 0.9,
rear: 28.0,
seeker: 130.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.05),
};
const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec {
model: "airdef:m48n6",
speed: 6.5,
accel: 0.5,
turn: 0.25,
boost: 8,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.85,
fuse: 5.0,
life: 300,
scale: 1.1,
flame: 1.2,
rear: 32.0,
seeker: 90.0,
launch_sound: sound::LAUNCH_PATRIOT,
voice: (sound::MISSILE_FLIGHT, 1.0, 0.9),
};
const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec {
model: "airdef:m57e6",
speed: 5.5,
accel: 0.6,
turn: 0.4,
boost: 4,
cold: 8,
eject: 1.6,
eject_drag: 0.1,
pk: 0.9,
fuse: 3.0,
life: 160,
scale: 1.0,
flame: 0.8,
rear: 28.0,
seeker: 70.0,
launch_sound: sound::LAUNCH_S400_EJECT,
voice: (sound::MISSILE_FLIGHT, 1.0, 1.15),
};
const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec {
model: "airdef:p1sun",
speed: 2.8,
accel: 0.12,
turn: 0.3,
boost: 4,
cold: 0,
eject: 0.0,
eject_drag: 0.0,
pk: 0.8,
fuse: 3.0,
life: 900,
scale: 0.8,
flame: 0.0,
rear: 10.0,
seeker: 60.0,
launch_sound: sound::DRONE_LANCET,
voice: (sound::DRONE_LANCET, 0.8, 1.6),
};
impl DroneKind {
/// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static DroneSpec {
match self {
DroneKind::Shahed => &DRONE_SPEC_SHAHED,
DroneKind::Geran3 => &DRONE_SPEC_GERAN3,
DroneKind::Lancet => &DRONE_SPEC_LANCET,
DroneKind::Gerbera => &DRONE_SPEC_GERBERA,
DroneKind::Kh101 => &DRONE_SPEC_KH101,
DroneKind::Kalibr => &DRONE_SPEC_KALIBR,
DroneKind::Kh22 => &DRONE_SPEC_KH22,
DroneKind::Zircon => &DRONE_SPEC_ZIRCON,
DroneKind::Iskander => &DRONE_SPEC_ISKANDER,
DroneKind::Kinzhal => &DRONE_SPEC_KINZHAL,
DroneKind::Oreshnik => &DRONE_SPEC_ORESHNIK,
DroneKind::OreshnikBlock => &DRONE_SPEC_ORESHNIKBLOCK,
DroneKind::OreshnikSub => &DRONE_SPEC_ORESHNIKSUB,
}
}
}
impl MissileKind {
fn spec(self) -> &'static MissileSpec {
match self {
MissileKind::Pac3 => &MISSILE_SPEC_PAC3,
MissileKind::M57e6 => &MISSILE_SPEC_M57E6,
MissileKind::M48n6 => &MISSILE_SPEC_M48N6,
MissileKind::M77n6 => &MISSILE_SPEC_M77N6,
MissileKind::IrisT => &MISSILE_SPEC_IRIST,
MissileKind::Amraam => &MISSILE_SPEC_AMRAAM,
MissileKind::M9m317 => &MISSILE_SPEC_M9M317,
MissileKind::M9m338 => &MISSILE_SPEC_M9M338,
MissileKind::P1sun => &MISSILE_SPEC_P1SUN,
}
}
}
/// Save keys by kind; a rename needs an explicit migration.
#[cfg(test)]
pub(super) const DRONE_SPEC_KEYS: [(DroneKind, &str); 13] = [
(DroneKind::Shahed, "shahed"),
(DroneKind::Geran3, "geran3"),
(DroneKind::Lancet, "lancet"),
(DroneKind::Gerbera, "gerbera"),
(DroneKind::Kh101, "kh101"),
(DroneKind::Kalibr, "kalibr"),
(DroneKind::Kh22, "kh22"),
(DroneKind::Zircon, "zircon"),
(DroneKind::Iskander, "iskander"),
(DroneKind::Kinzhal, "kinzhal"),
(DroneKind::Oreshnik, "oreshnik"),
(DroneKind::OreshnikBlock, "oreshnik_block"),
(DroneKind::OreshnikSub, "oreshnik_sub"),
];
#[cfg(test)]
pub(super) const MISSILE_SPEC_MODELS: [(MissileKind, &str); 9] = [
(MissileKind::Pac3, "airdef:pac3"),
(MissileKind::M57e6, "airdef:m57e6"),
(MissileKind::M48n6, "airdef:m48n6"),
(MissileKind::M77n6, "airdef:m77n6"),
(MissileKind::IrisT, "airdef:irist_missile"),
(MissileKind::Amraam, "airdef:amraam_missile"),
(MissileKind::M9m317, "airdef:m48n6"),
(MissileKind::M9m338, "airdef:m57e6"),
(MissileKind::P1sun, "airdef:p1sun"),
];
+49 -9
View File
@@ -25,7 +25,16 @@ use glam::DVec2;
/// Minecraft presentation profile; neither dimensions nor timing reproduce a real weapon.
pub const ROUND_MODEL: &str = "airdef:rm48u";
pub const ROUND_SCALE: f64 = 1.5;
pub const EJECT_TICKS: u64 = 5;
/// Ticks the gas throw takes before the motor lights: the same staged cold launch as the
/// interceptor's `cold` (#129), so a physical strike shows the unlit ejection too.
pub const EJECT_TICKS: u64 = 20;
/// The unlit ejection's height at flight age `age`: a gas throw of 2.2 blocks a tick with a
/// linear drag of 0.09 a tick², integrated (game scale, like the interceptor's `eject`).
fn eject_rise(age: u64) -> f64 {
let a = age as f64;
(2.2 * a - 0.045 * a * a).max(0.0)
}
/// Shared live/replay appearance, including the unlit cold-ejection phase.
pub(super) fn round_visual(out: &mut Out, id: u32, pos: DVec3, rot: DQuat, lit: bool) {
@@ -581,10 +590,18 @@ impl Sim {
let end = DVec3::new(f.land.x, below.unwrap_or(f.from.y), f.land.y);
let t = ((now - f.start) as f64 / (f.arrive - f.start).max(1) as f64).clamp(0.0, 1.0);
let age = now.saturating_sub(f.start);
let arc = |t: f64| TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt();
let planned = if f.carrier.is_some() && age < EJECT_TICKS {
f.from + DVec3::Y * (age as f64 * 0.7)
// The unlit gas throw: it rises and slows, no motor yet (#129).
f.from + DVec3::Y * eject_rise(age)
} else if f.carrier.is_some() {
// From where the ejection reached, onto the cruise arc: the plan is continuous
// at ignition, and the flight time counted at the order includes the ejection.
let top = f.from + DVec3::Y * eject_rise(EJECT_TICKS);
let t = ((age - EJECT_TICKS) as f64 / (f.arrive - f.start).saturating_sub(EJECT_TICKS).max(1) as f64).clamp(0.0, 1.0);
top.lerp(end, t) + DVec3::Y * arc(t)
} else {
f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt())
f.from.lerp(end, t) + DVec3::Y * arc(t)
};
let from = f.pos;
// Time spent waiting for world data must not accumulate into a faster step.
@@ -750,10 +767,13 @@ impl Sim {
sam.launched = 12;
sam.fired += 1;
let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length();
self.intel.revealed.push((p.carrier, sam.pos, self.tick));
// The launch betrays the carrier: the enemy saw it fire, no more than that.
self.intel.observe(&self.sams[i], self.tick, ew::Seen::Launch);
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
// The counted flight includes the unlit ejection: the missile is honest about
// arriving a second later (#129).
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, p.site as u64, 7), gauss(self.seed, self.strikes.next as u64, p.site as u64, 8));
self.strikes.flights.push(Flight { id: self.strikes.next, site: p.site, carrier: Some(p.carrier), from: start, pos: start, aim: p.aim,
land: p.aim + DVec2::new(gx, gz) * TUNE.cep, start: self.tick, arrive: self.tick + ticks, snap, hold: 0 });
@@ -790,7 +810,8 @@ impl Sim {
self.strikes.stock -= 1;
self.strikes.fired += 1;
self.strikes.next += 1;
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
// The counted flight includes the unlit ejection (#129).
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64 + EJECT_TICKS;
let start = from + DVec3::Y * 1.5;
// Its own scatter at the aim, rolled once here: the flight and its outcome name one point.
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
@@ -1062,7 +1083,22 @@ mod tests {
sim.drones.push(d);
sim.tick = hidden_launch_tick;
sim.scout_launch(drone, id, DroneKind::Shahed, DVec3::new(hidden_x, 70.0, 700.0));
let track = sight::Track { id: drone, kind: DroneKind::Shahed, pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false };
let track = sight::Track {
id: drone,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::new(0.0, 100.0, 1000.0),
vel: -DVec3::Z * 5.0,
tick: 100,
own_tick: 100,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 100,
hits: 3,
locked: false,
};
sim.sams[0].tracks.push(track);
sim.tick = 100;
sim.step_strikes(&mut ground, None, &mut out);
@@ -1408,10 +1444,14 @@ mod tests {
fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() {
let mut sim = Sim::new(5);
// Two radars apart watch the start of an off-map site's drones.
// Two radars apart watch the start of an off-map site's drones. They hold fire: this test
// is about the sighting and the strike, not about intercepting drones flown at 2 blocks a
// tick (which measure as cruise missiles, #133, and would be engaged on the roles).
for x in [-150.0, 150.0] {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0));
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0);
sam.roles = 0;
sim.sams.push(sam);
}
let id = sim.sites.add(LaunchSite {
id: 0,
+451
View File
@@ -0,0 +1,451 @@
// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.
// Game-scale values, not real weapon data; the catalog is the only copy.
const NAMED_BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
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 UNIT_SPEC_PATRIOT: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
rest_pitch: 0.66,
roles: 30,
family: Family::Trainable,
parts: Parts {
body: "airdef:patriot_trailer",
launcher: Some("airdef:patriot_launcher"),
pack: None,
dish: None,
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
spinner: None,
},
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 585.0,
mast: 5.0,
};
const UNIT_SPEC_GEPARD: SamSpec = SamSpec {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
roles: 7,
family: Family::Gun,
parts: Parts {
body: "airdef:gepard_hull",
launcher: Some("airdef:gepard_turret"),
pack: Some("airdef:gepard_guns"),
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
fixed: &[],
spinner: None,
},
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 255.0,
mast: 3.0,
};
const UNIT_SPEC_PANTSIR: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Turret,
parts: Parts {
body: "airdef:pantsir_truck",
launcher: Some("airdef:pantsir_turret"),
pack: Some("airdef:pantsir_pack"),
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
fixed: &[],
spinner: None,
},
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 292.0,
mast: 4.0,
};
const UNIT_SPEC_S400: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
rest_pitch: HALF_PI - 0.02,
roles: 30,
family: Family::Vertical,
parts: Parts {
body: "airdef:s400_chassis",
launcher: Some("airdef:s400_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 936.0,
mast: 5.0,
};
const UNIT_SPEC_S500: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
rest_pitch: HALF_PI - 0.02,
roles: 24,
family: Family::Vertical,
parts: Parts {
body: "airdef:s500_chassis",
launcher: Some("airdef:s500_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 1365.0,
mast: 5.0,
};
const UNIT_SPEC_IRIST: SamSpec = SamSpec {
name: "IRIS-T SLM",
key: "irist",
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
gun: None,
reload: 300,
scale: 1.4,
rest_pitch: HALF_PI - 0.02,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:irist_chassis",
launcher: Some("airdef:irist_tubes"),
pack: None,
dish: None,
fixed: NAMED_BATTERY_RADAR,
spinner: NAMED_BATTERY_SPINNER,
},
mount: (0.7, 1.45),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 4.0),
sensor: 780.0,
mast: 5.0,
};
const UNIT_SPEC_NASAMS: SamSpec = SamSpec {
name: "NASAMS",
key: "nasams",
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
gun: None,
reload: 260,
scale: 1.3,
rest_pitch: 0.5,
roles: 14,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:nasams_launcher"),
pack: None,
dish: None,
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
},
mount: (0.62, 0.4),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(3, 2, 4.0),
sensor: 585.0,
mast: 5.0,
};
const UNIT_SPEC_BUK: SamSpec = SamSpec {
name: "Бук-М2",
key: "buk",
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
gun: None,
reload: 400,
scale: 1.4,
rest_pitch: 0.0,
roles: 14,
family: Family::Turret,
parts: Parts {
body: "airdef:buk_chassis",
launcher: Some("airdef:buk_turret"),
pack: Some("airdef:buk_rails"),
dish: None,
fixed: &[],
spinner: None,
},
mount: (1.55, 0.2),
pivot: DVec3::ZERO,
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
sensor: 878.0,
mast: 4.0,
};
const UNIT_SPEC_TOR: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:tor_chassis",
launcher: Some("airdef:tor_turret"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 315.0,
mast: 3.5,
};
const UNIT_SPEC_P1SUN: SamSpec = SamSpec {
name: "P1-SUN",
key: "p1sun",
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
gun: None,
reload: 240,
scale: 1.1,
rest_pitch: 0.35,
roles: 1,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:p1sun_launcher"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.6, 0.3),
pivot: NAMED_TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 3.0),
sensor: 0.0,
mast: 2.0,
};
const UNIT_SPEC_RADAR: SamSpec = SamSpec {
name: "РЛС дальнего обнаружения",
key: "radar",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: Some(("airdef:radar_panel", 1.2, 1.2, 1.5, -0.25)),
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 2550.0,
mast: 16.0,
};
const UNIT_SPEC_DEPOT: SamSpec = SamSpec {
name: "Склад боеприпасов",
key: "depot",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:depot",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.0,
};
const UNIT_SPEC_TZM: SamSpec = SamSpec {
name: "ТЗМ",
key: "tzm",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Truck,
parts: Parts {
body: "airdef:tzm_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.0,
};
const UNIT_SPEC_EW: SamSpec = SamSpec {
name: "Станция РЭБ",
key: "ew",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:ew_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 3.0,
};
const UNIT_SPEC_LIGHT: SamSpec = SamSpec {
name: "Прожектор",
key: "light",
missile: None,
gun: None,
reload: 0,
scale: 1.2,
rest_pitch: 0.6,
roles: 0,
family: Family::Light,
parts: Parts {
body: "airdef:searchlight",
launcher: Some("airdef:searchlight_head"),
pack: None,
dish: None,
fixed: &[],
spinner: None,
},
mount: (0.85, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.5,
};
const UNIT_SPEC_OPTICAL: SamSpec = SamSpec {
name: "Оптический пост",
key: "optical",
missile: None,
gun: None,
reload: 0,
scale: 1.0,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
launcher: None,
pack: None,
dish: None,
fixed: &[],
spinner: Some(("airdef:radar_panel", 1.2, 0.0, 0.6, -0.2)),
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.5,
};
impl SamKind {
/// Its row of numbers from `catalog/specs.json`.
pub fn spec(self) -> &'static SamSpec {
match self {
SamKind::Patriot => &UNIT_SPEC_PATRIOT,
SamKind::Gepard => &UNIT_SPEC_GEPARD,
SamKind::Pantsir => &UNIT_SPEC_PANTSIR,
SamKind::S400 => &UNIT_SPEC_S400,
SamKind::S500 => &UNIT_SPEC_S500,
SamKind::IrisT => &UNIT_SPEC_IRIST,
SamKind::Nasams => &UNIT_SPEC_NASAMS,
SamKind::Buk => &UNIT_SPEC_BUK,
SamKind::Tor => &UNIT_SPEC_TOR,
SamKind::P1sun => &UNIT_SPEC_P1SUN,
SamKind::Radar => &UNIT_SPEC_RADAR,
SamKind::Depot => &UNIT_SPEC_DEPOT,
SamKind::Tzm => &UNIT_SPEC_TZM,
SamKind::Ew => &UNIT_SPEC_EW,
SamKind::Light => &UNIT_SPEC_LIGHT,
SamKind::Optical => &UNIT_SPEC_OPTICAL,
}
}
}
/// Save keys by kind; a rename needs an explicit migration.
#[cfg(test)]
pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 16] = [
(SamKind::Patriot, "patriot"),
(SamKind::Gepard, "gepard"),
(SamKind::Pantsir, "pantsir"),
(SamKind::S400, "s400"),
(SamKind::S500, "s500"),
(SamKind::IrisT, "irist"),
(SamKind::Nasams, "nasams"),
(SamKind::Buk, "buk"),
(SamKind::Tor, "tor"),
(SamKind::P1sun, "p1sun"),
(SamKind::Radar, "radar"),
(SamKind::Depot, "depot"),
(SamKind::Tzm, "tzm"),
(SamKind::Ew, "ew"),
(SamKind::Light, "light"),
(SamKind::Optical, "optical"),
];
@@ -0,0 +1,8 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const VARIANTS: &[UnitVariant] = &[
UnitVariant { id: "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: "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_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
];
+15 -369
View File
@@ -27,6 +27,8 @@ pub enum SamKind {
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.
@@ -107,11 +109,6 @@ pub(super) struct Drive {
pub pitch: (f64, f64),
}
/// The drives are this share of the speeds they had before they had a speed of their own.
const DRIVE_SCALE: f64 = 0.4;
/// Ticks a drive takes to reach its top speed (and to stop from it).
const DRIVE_RAMP: f64 = 8.0;
pub struct SamSpec {
pub name: &'static str,
pub key: &'static str,
@@ -140,20 +137,16 @@ impl SamSpec {
pub(super) fn drive(&self) -> Drive {
let (yaw, pitch) = match (&self.gun, self.family) {
(Some(g), _) => g.slew,
(None, Family::Trainable) => (0.12, 0.0),
(None, Family::Vertical) => (0.15, 0.0),
(None, _) => (0.05, 0.05),
(None, Family::Trainable) => DRIVE_TRAINABLE,
(None, Family::Vertical) => DRIVE_VERTICAL,
(None, _) => DRIVE_OTHER,
};
let axis = |speed: f64| (speed * DRIVE_SCALE, speed * DRIVE_SCALE / DRIVE_RAMP);
Drive { yaw: axis(yaw), pitch: axis(pitch) }
}
}
const NO_PARTS: Parts = Parts { body: "", launcher: None, pack: None, dish: None, fixed: &[], spinner: None };
/// The battery radar trailer behind a vertical launcher.
const BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, 4.2)];
const BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3));
const TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5);
include!("unit_specs_generated.rs");
impl SamKind {
pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS;
@@ -170,361 +163,6 @@ impl SamKind {
SamKind::Tor,
SamKind::P1sun,
];
pub fn spec(self) -> &'static SamSpec {
match self {
SamKind::Patriot => {
const S: SamSpec = SamSpec {
name: "Patriot",
key: "patriot",
missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 450.0, interval: 16 }),
gun: None,
reload: 220,
scale: 1.3,
rest_pitch: 0.66,
roles: 30,
family: Family::Trainable,
parts: Parts {
body: "airdef:patriot_trailer",
launcher: Some("airdef:patriot_launcher"),
fixed: &[("airdef:patriot_truck", 0.0, -3.0), ("airdef:patriot_radar", 0.0, 3.6)],
..NO_PARTS
},
mount: (0.69, 1.2),
pivot: DVec3::new(0.0, -0.5, 1.375),
muzzle: Muzzle::Patriot,
sensor: 585.0,
mast: 5.0,
};
&S
}
SamKind::Gepard => {
const S: SamSpec = SamSpec {
name: "Гепард",
key: "gepard",
missile: None,
gun: Some(GunSpec { range: 135.0, track: 195.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }),
reload: 160,
scale: 1.25,
rest_pitch: 0.0,
roles: 7,
family: Family::Gun,
parts: Parts {
body: "airdef:gepard_hull",
launcher: Some("airdef:gepard_turret"),
pack: Some("airdef:gepard_guns"),
dish: Some(("airdef:gepard_dish", 0.95, 0.6, 0.0)),
..NO_PARTS
},
mount: (1.55, 0.25),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 255.0,
mast: 3.0,
};
&S
}
SamKind::Pantsir => {
const S: SamSpec = SamSpec {
name: "Панцирь-С1",
key: "pantsir",
missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 225.0, interval: 14 }),
gun: Some(GunSpec { range: 90.0, track: 135.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }),
reload: 280,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Turret,
parts: Parts {
body: "airdef:pantsir_truck",
launcher: Some("airdef:pantsir_turret"),
pack: Some("airdef:pantsir_pack"),
dish: Some(("airdef:pantsir_dish", 0.85, 0.3, 0.3)),
..NO_PARTS
},
mount: (1.35, 0.69),
pivot: DVec3::ZERO,
muzzle: Muzzle::Pantsir,
sensor: 292.0,
mast: 4.0,
};
&S
}
SamKind::S400 => {
const S: SamSpec = SamSpec {
name: "С-400",
key: "s400",
missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 720.0, interval: 20 }),
gun: None,
reload: 420,
scale: 1.5,
rest_pitch: HALF_PI - 0.02,
roles: 30,
family: Family::Vertical,
parts: Parts {
body: "airdef:s400_chassis",
launcher: Some("airdef:s400_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 2, 7.0),
sensor: 936.0,
mast: 5.0,
};
&S
}
SamKind::S500 => {
const S: SamSpec = SamSpec {
name: "С-500",
key: "s500",
missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1050.0, interval: 20 }),
gun: None,
reload: 520,
scale: 1.6,
rest_pitch: HALF_PI - 0.02,
roles: 24,
family: Family::Vertical,
parts: Parts {
body: "airdef:s500_chassis",
launcher: Some("airdef:s500_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(2, 1, 9.5),
sensor: 1365.0,
mast: 5.0,
};
&S
}
SamKind::IrisT => {
const S: SamSpec = SamSpec {
name: "IRIS-T SLM",
key: "irist",
missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }),
gun: None,
reload: 300,
scale: 1.4,
rest_pitch: HALF_PI - 0.02,
roles: 15,
family: Family::Vertical,
parts: Parts {
body: "airdef:irist_chassis",
launcher: Some("airdef:irist_tubes"),
fixed: BATTERY_RADAR,
spinner: BATTERY_SPINNER,
..NO_PARTS
},
mount: (0.7, 1.45),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 4.0),
sensor: 780.0,
mast: 5.0,
};
&S
}
SamKind::Nasams => {
const S: SamSpec = SamSpec {
name: "NASAMS",
key: "nasams",
missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }),
gun: None,
reload: 260,
scale: 1.3,
rest_pitch: 0.5,
roles: 14,
family: Family::Trainable,
parts: Parts {
body: "airdef:nasams_trailer",
launcher: Some("airdef:nasams_launcher"),
fixed: &[("airdef:radar_trailer", 0.0, 3.4)],
spinner: Some(("airdef:radar_panel", 0.9, 3.4, 0.6, -0.3)),
..NO_PARTS
},
mount: (0.62, 0.4),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(3, 2, 4.0),
sensor: 585.0,
mast: 5.0,
};
&S
}
SamKind::Buk => {
const S: SamSpec = SamSpec {
name: "Бук-М2",
key: "buk",
missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }),
gun: None,
reload: 400,
scale: 1.4,
rest_pitch: 0.0,
roles: 14,
family: Family::Turret,
parts: Parts {
body: "airdef:buk_chassis",
launcher: Some("airdef:buk_turret"),
pack: Some("airdef:buk_rails"),
..NO_PARTS
},
mount: (1.55, 0.2),
pivot: DVec3::ZERO,
muzzle: Muzzle::Rails(&[-9.0, -3.0, 13.0, 19.0]),
sensor: 878.0,
mast: 4.0,
};
&S
}
SamKind::Tor => {
const S: SamSpec = SamSpec {
name: "Тор-М2",
key: "tor",
missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 240.0, interval: 8 }),
gun: None,
reload: 300,
scale: 1.3,
rest_pitch: 0.0,
roles: 15,
family: Family::Vertical,
parts: Parts { body: "airdef:tor_chassis", launcher: Some("airdef:tor_turret"), ..NO_PARTS },
mount: (1.5, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::Cells,
sensor: 315.0,
mast: 3.5,
};
&S
}
SamKind::P1sun => {
const S: SamSpec = SamSpec {
name: "P1-SUN",
key: "p1sun",
missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }),
gun: None,
reload: 240,
scale: 1.1,
rest_pitch: 0.35,
roles: 1,
family: Family::Trainable,
parts: Parts { body: "airdef:nasams_trailer", launcher: Some("airdef:p1sun_launcher"), ..NO_PARTS },
mount: (0.6, 0.3),
pivot: TUBE_PIVOT,
muzzle: Muzzle::Grid(4, 2, 3.0),
// No radar of its own: it fires on the network's tracks.
sensor: 0.0,
mast: 2.0,
};
&S
}
SamKind::Radar => {
const S: SamSpec = SamSpec {
name: "РЛС дальнего обнаружения",
key: "radar",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts {
body: "airdef:radar_truck",
spinner: Some(("airdef:radar_panel", 1.2, 1.2, 1.5, -0.25)),
..NO_PARTS
},
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 2550.0,
mast: 16.0,
};
&S
}
SamKind::Depot => {
const S: SamSpec = SamSpec {
name: "Склад боеприпасов",
key: "depot",
missile: None,
gun: None,
reload: 0,
scale: 1.5,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts { body: "airdef:depot", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.0,
};
&S
}
SamKind::Tzm => {
const S: SamSpec = SamSpec {
name: "ТЗМ",
key: "tzm",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Truck,
parts: Parts { body: "airdef:tzm_truck", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 2.0,
};
&S
}
SamKind::Ew => {
const S: SamSpec = SamSpec {
name: "Станция РЭБ",
key: "ew",
missile: None,
gun: None,
reload: 0,
scale: 1.3,
rest_pitch: 0.0,
roles: 0,
family: Family::Static,
parts: Parts { body: "airdef:ew_truck", ..NO_PARTS },
mount: (0.0, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 3.0,
};
&S
}
SamKind::Light => {
const S: SamSpec = SamSpec {
name: "Прожектор",
key: "light",
missile: None,
gun: None,
reload: 0,
scale: 1.2,
rest_pitch: 0.6,
roles: 0,
family: Family::Light,
parts: Parts { body: "airdef:searchlight", launcher: Some("airdef:searchlight_head"), ..NO_PARTS },
mount: (0.85, 0.0),
pivot: DVec3::ZERO,
muzzle: Muzzle::None,
sensor: 0.0,
mast: 1.5,
};
&S
}
}
}
pub fn name(self) -> &'static str {
self.spec().name
}
@@ -543,6 +181,14 @@ impl SamKind {
let s = self.spec();
s.missile.is_some() || s.gun.is_some()
}
/// Missiles its launcher's magazine holds; `None` without a launcher.
pub fn missile_magazine(self) -> Option<u32> {
self.spec().missile.as_ref().map(|m| m.magazine)
}
/// Whether it has a gun (its bursts are read by the status line).
pub fn has_gun(self) -> bool {
self.spec().gun.is_some()
}
}
impl Sam {
@@ -689,7 +335,7 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
part(out, model, sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s), base, s);
}
if let Some((model, h, back, size, tilt)) = parts.spinner {
let extra = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
let extra = if sam.kind == SamKind::Radar { sam.radar_profile().mast } else { 0.0 };
let foot = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
for segment in 0..(extra as u32 / 2) {
part(out, "airdef:radar_mast", foot + DVec3::Y * (segment as f64 * 2.0 + 0.5), base, 1.0);
+15 -14
View File
@@ -18,23 +18,24 @@ impl MissileKind {
/// The sound of its motor, its gain and its pitch: a rocket's roar, or the electric whine of
/// a motor without a flame.
pub fn engine_voice(self) -> (&'static str, f32, f32) {
if self.spec().flame == 0.0 {
return (super::catalog::sound::DRONE_LANCET, 0.8, 1.6);
}
let pitch = match self {
MissileKind::Pac3 => 1.0,
MissileKind::M57e6 => 1.12,
MissileKind::M48n6 => 0.88,
MissileKind::M77n6 => 0.8,
MissileKind::IrisT | MissileKind::Amraam => 1.05,
MissileKind::M9m317 => 0.9,
MissileKind::M9m338 => 1.15,
MissileKind::P1sun => 1.7,
};
(super::catalog::sound::MISSILE_FLIGHT, 1.0, pitch)
self.spec().voice
}
/// Ticks from the launch until the motor lights (a cold launch throws it out of the tube first).
pub fn lit_after(self) -> u32 {
self.spec().cold
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::catalog::sound;
/// The catalog holds the voice that is actually played. P1-SUN has no flame, so it uses the
/// Lancet voice at 1.6; its old `P1sun => 1.7` match arm was unreachable behind `flame == 0`.
#[test]
fn missile_engine_voices_keep_their_played_values() {
assert_eq!(MissileKind::P1sun.engine_voice(), (sound::DRONE_LANCET, 0.8, 1.6));
assert_eq!(MissileKind::M48n6.engine_voice(), (sound::MISSILE_FLIGHT, 1.0, 0.88));
}
}
+269 -47
View File
@@ -14,14 +14,20 @@ pub(super) const UNSEEN: u8 = 4;
/// Its track is older than a launcher fires on.
pub(super) const STALE: u8 = 8;
/// Why a drone is not a candidate for a system at all. The role is checked against the track's
/// *estimated* class, never the target's own (#133): an unidentified track is not blocked — the
/// explicit policy is that it stays a candidate under the general rules (a system with no roles
/// is holding its fire: nothing is a candidate for it) — and a probable or firm class out of the
/// roles is, with the reason named in `why`.
pub(super) fn target_blocks(roles: u8, track: Option<&Track>, now: u64, d: &Drone) -> u8 {
(if d.alive() { 0 } else { DEAD })
| (if roles & d.kind.spec().class.bit() != 0 { 0 } else { ROLE })
| (if track.is_some_and(|t| t.class.in_roles(roles)) { 0 } else { ROLE })
| (if track.is_some() { 0 } else { UNSEEN })
| (if track.is_some_and(|t| t.age(now) > sight::MISSILE_AGE) { STALE } else { 0 })
}
/// Alive, of a class the system engages, and on its picture (own radar or the network's), fresh enough.
/// Alive, of a class the system engages (or not yet classified), and on its picture (own radar
/// or the network's), fresh enough.
pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool {
target_blocks(roles, Some(track), now, d) == 0
}
@@ -50,14 +56,15 @@ pub(super) fn arrival(d: &Drone) -> f64 {
d.pos.distance(d.target) / d.vel.length().max(0.1)
}
/// Shoot-look-shoot that grows with urgency: ballistic missiles get a pair, anything else one; a target
/// Shoot-look-shoot that grows with urgency: a ballistic missile gets a pair, anything else one; a target
/// this close to its aim (ticks) has one more interceptor allowed on it at once, closer still another, and in the last seconds a fourth.
/// The class is the track's estimate (#133): an unidentified contact is treated as not ballistic.
pub(super) const URGENT: f64 = 240.0;
pub(super) const DESPERATE: f64 = 110.0;
pub(super) const FINAL: f64 = 60.0;
pub(super) fn needed(d: &Drone) -> u32 {
let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 };
pub(super) fn needed(d: &Drone, class: ClassEst) -> u32 {
let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 };
let t = arrival(d);
base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL)
}
@@ -68,12 +75,14 @@ pub(super) const SHY_TICKS: u64 = 120;
// ---------------------------------------------------------------- the grounds to launch on
/// Last chance (`/airdef lastchance`): a target of a class the system does not engage that is about to
/// hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire (no roles) keeps to it.
/// Last chance (`/airdef lastchance`): a track of a *known* class the system does not engage that
/// is about to hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire
/// (no roles) keeps to it. An unidentified track is no last-chance case: it is already a candidate
/// under the general rules (#133).
pub(super) const LAST_CHANCE_TICKS: f64 = 200.0;
pub(super) fn last_chance(on: bool, roles: u8, d: &Drone, claimed: u32) -> bool {
on && roles != 0 && roles & d.kind.spec().class.bit() == 0 && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS
pub(super) fn last_chance(on: bool, roles: u8, class: ClassEst, d: &Drone, claimed: u32) -> bool {
on && roles != 0 && !class.in_roles(roles) && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS
}
/// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds.
@@ -92,14 +101,17 @@ impl SamKind {
/// A live big radar in data-link reach of `sam` that measured `id` recently.
pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool {
radars.iter().any(|r| {
r.radar_role.authorizes()
r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
&& r.link_range() > 0.0
&& sam.link_range() > 0.0
&& r.alive()
&& !r.moving()
&& r.radar_up()
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())
&& r.track(id).is_some_and(|t| t.own_tick > 0 && now.saturating_sub(t.own_tick) <= if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE })
&& r.track(id).is_some_and(|t| {
let age = if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE };
t.own_fire_within(now, age)
})
})
}
@@ -137,25 +149,37 @@ pub(super) struct Opts {
/// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then).
#[allow(clippy::too_many_arguments)]
pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option<Basis> {
if sam.mode == battery::SamMode::LauncherOnly && !cued { return None; }
// A launch rests on the battery's own confirmed fire plot. A launcher
// without its own radar may use a supporting radar's own fire plot; a
// relayed plot, a search plot or a height refinement never authorizes an
// ordinary shot. A heavy system's *far* shot is the exception it already
// had: it may use the cue radar's own confirmed fire plot beyond its reach.
let own = track.own_authorizes(now);
if sam.mode == battery::SamMode::LauncherOnly {
if !cued { return None; }
} else if !own && !cued {
return None;
}
let blocks = target_blocks(sam.roles, Some(track), now, d);
if blocks & !ROLE != 0 {
return None;
}
let est = track.est(now);
let reach = reach_blocks(load.min, load.max, k, sam.pos, est);
let est = track.class;
let reach = reach_blocks(load.min, load.max, k, sam.pos, track.est(now));
if blocks & ROLE == 0 {
// The doctrine (sector, protected objects, reserve) rules over the role's shots and the long ones; the last chance is past it.
if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d) != 0 {
if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 {
return None;
}
if reach == 0 {
return Some(Basis::Role);
// A normal shot belongs to the battery's own confirmed measurement;
// a launcher-only battery uses its supporting radar's (checked above).
return (own || sam.mode == battery::SamMode::LauncherOnly).then_some(Basis::Role);
}
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0;
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
}
(reach == 0 && last_chance(opts.last_chance, sam.roles, d, claimed)).then_some(Basis::LastChance)
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
}
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
@@ -308,6 +332,37 @@ impl Sim {
return v;
}
if !sam.kind.armed() {
if sam.kind == SamKind::Radar {
let profile = sam.radar_profile();
v.push(check(true, format!(
"профиль {} [{}]: {}, оборот {:.1} с, каналы {}, локальный поиск {}",
profile.name,
profile.id,
profile.products_text(),
profile.cycle as f64 / 20.0,
profile.channels,
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
)));
v.push(check(true, format!("ограничение: {}", profile.limit)));
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(), profile.channels)));
let now = self.tick;
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
for t in tracks.into_iter().take(4) {
v.push(check(
t.own_authorizes(now),
format!(
"цель {}: {} ({}), качество {}, возраст {:.1} с{}",
t.id,
t.own_product.name(),
if t.own_authorizes(now) { "право на пуск" } else { "пуск не разрешает" },
t.own_quality,
now.saturating_sub(t.own_tick) as f64 / 20.0,
if t.own_authorizes(now) { "" } else { "; нужно подтверждённое измерение станции" },
),
));
}
}
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
return v;
}
@@ -352,7 +407,10 @@ impl Sim {
let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| {
self.drones
.iter()
.filter(|d| d.alive() && (sam.roles & d.kind.spec().class.bit() != 0 || last_chance(self.last_chance, sam.roles, d, claimed(d, &missile_on, sam.target))))
// Of what the system's picture holds: a track of its roles' classes (or not yet
// classified), or a known out-of-role one about to hit (the last chance) — never
// the target's own class (#133).
.filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target))))
.max_by(|a, b| {
// What the doctrine lets the system shoot at comes first; then the most threatening.
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0);
@@ -360,44 +418,61 @@ impl Sim {
})
});
let Some(t) = subject else {
v.push(check(false, format!("нет целей классов [{}]", roles_text(sam.roles))));
// Nothing to look at: either the sky holds nothing for this system, or it holds only
// tracks whose estimated class is out of the roles — the reasons differ and are named (#133).
let held = self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id));
// No roles is holding fire: a reason of its own, not an empty class filter.
let text = if sam.roles == 0 {
"роль: система не ведёт огонь (роли не заданы) — ни одна цель не выбирается".to_string()
} else if held {
format!("цели на картине есть, но не в ролях [{}] (классы по оценке)", roles_text(sam.roles))
} else {
format!("нет целей классов [{}]", roles_text(sam.roles))
};
v.push(check(false, text));
return v;
};
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
let dist = sam.track(t.id).map_or(t.pos, |tr| tr.est(self.tick)).distance(sam.pos);
let track = sam.track(t.id);
v.push(check(
true,
format!("цель: {} {}, {}", t.kind.spec().name, if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)),
));
let track = sam.track(t.id);
let est = track.map_or(ClassEst::Unknown, |tr| tr.class);
let blocks = target_blocks(sam.roles, track, now, t);
// Where the system believes the target is: its track's forecast (the true place only when it has no track).
let est = track.map_or(t.pos, |tr| tr.est(now));
let est_at = track.map_or(t.pos, |tr| tr.est(now));
let evel = track.map_or(t.vel, |tr| tr.vel);
let first_claim = claimed(t, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, t, first_claim);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, first_claim);
let role_text = if blocks & ROLE == 0 {
format!("роль: {} в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
match est {
ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(),
_ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)),
}
} else if chance {
format!(
"последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет",
t.kind.spec().class.name(),
est.name(),
roles_text(sam.roles),
arrival(t) / 20.0
)
} else if sam.roles == 0 {
"роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string()
} else {
format!("роль: {} не в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles))
format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles))
};
v.push(check(blocks & ROLE == 0 || chance, role_text));
// The doctrine: which of its settings let the shot through or stopped it. The last chance is past them.
let doc = &sam.doctrine;
let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now));
let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t) } else { 0 };
let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t, est) } else { 0 };
if !doc.is_default() {
v.push(check(true, format!("доктрина: {}", doc.text(&self.targets))));
}
if area & doctrine::OUT_SECTOR != 0 {
let bearing = heading_of(est - sam.pos).to_degrees().rem_euclid(360.0);
let bearing = heading_of(est_at - sam.pos).to_degrees().rem_euclid(360.0);
v.push(check(chance, format!("вне сектора {}: цель на {bearing:.0}°{}", doc.sector_text(), if chance { " — последний шанс сильнее" } else { "" })));
} else if doc.sector.is_some() {
v.push(check(true, format!("в секторе {}", doc.sector_text())));
@@ -418,7 +493,15 @@ impl Sim {
let age = tr.age(now) as f64 / 20.0;
let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" };
let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() };
format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}", tr.ident().name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" })
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let authority = tr.own_authorizes(now) || (sam.mode == battery::SamMode::LauncherOnly && radar_cue(sam, &radars, t.id, now));
format!(
"трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}; право на пуск: {}",
tr.ident().name(),
tr.class.name(),
if blocks & STALE != 0 { "устарел" } else { "годен" },
if authority { "своё подтверждённое измерение" } else { "нет (сеть или обзор не дают права)" }
)
}
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
};
@@ -456,19 +539,19 @@ impl Sim {
v.push(check(sam.reloading == 0 && !sam.empty && (sam.missiles > 0 || sam.bursts > 0), format!("{rounds}— {supply}")));
let mount = sam.mount().0;
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
let (_, want_yaw, want_pitch) = aim_wants(mount, est, evel, lead_speed);
let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, evel, lead_speed);
let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch);
let vertical = spec.family == Family::Vertical;
let mut fires = false;
if let Some(load) = &spec.missile {
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est);
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at);
// Beyond the normal reach, a heavy system may fire on a big radar's cue.
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let cued = radar_cue(sam, &radars, t.id, now);
let role_in_reach = self.drones.iter().any(|o| {
sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o))
sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class))
});
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0;
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0;
let far_ok = far && track.is_some_and(|tr| basis(sam, load, tr, t, now, 0, 1.0, Opts { last_chance: self.last_chance, far_shots: self.far_shots }, cued, role_in_reach) == Some(Basis::FarShot));
if far {
let fb = far_blocks(self.far_shots, sam, load, cued, role_in_reach);
@@ -487,7 +570,7 @@ impl Sim {
v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", super::distance(dist), super::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) }));
}
let free = first_claim;
let need = sam.doctrine.needed(t);
let need = sam.doctrine.needed(t, est);
v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need} (залп {}){}", doc.salvo.name(), if free < need { "" } else { " — другие уже на ней" })));
let mb = missile_blocks(sam);
let mut why = Vec::new();
@@ -504,7 +587,7 @@ impl Sim {
why.push("пусковая отказала".to_string());
}
v.push(check(mb == 0, if mb == 0 { "пусковая готова".to_string() } else { format!("пусковая не готова: {}", why.join(", ")) }));
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est), t.id, t.id, err);
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est_at), t.id, t.id, err);
let turn = if vertical { "вертикальный старт" } else { "доворот" };
v.push(check(aligned, format!("{turn}: ошибка наведения {:.0}°{}", err.to_degrees(), if aligned { "" } else { " — ещё доворачивается" })));
// The land: the verdict the launch decision gave this target (`terrain::launch_blocks`) a moment ago.
@@ -520,7 +603,9 @@ impl Sim {
));
}
let doc_ok = chance || area | held_back == 0;
let grounds = (sam.mode != battery::SamMode::LauncherOnly || cued) && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
let own = track.is_some_and(|tr| tr.own_authorizes(now));
let authorized = own || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok;
let grounds = authorized && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
fires |= grounds && free < need && mb == 0 && aligned && land == 0;
}
if let Some(gun) = &spec.gun {
@@ -535,7 +620,7 @@ impl Sim {
if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" }
),
));
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est), gun.range, now);
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est_at), gun.range, now);
let mut why = Vec::new();
for (bit, name) in [
(AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())),
@@ -581,7 +666,7 @@ mod tests {
}
let w = sim.why(0);
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().contains("нет целей классов")));
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
sim.sams[0].roles = 0xFF;
assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль")));
}
@@ -612,23 +697,45 @@ mod tests {
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -80.0 - blocks), DVec3::Z, DVec3::new(0.0, 70.0, -80.0));
}
/// The system's picture holds the drone as a contact whose class is already estimated — as if
/// the network had passed enough measurements (#133). The sim's own radar then keeps the
/// estimate up from its measurements alone.
fn seed_classified(sim: &mut Sim, class: ClassEst) {
let now = sim.tick;
let d = sim.drones[0].clone();
sim.sams[0].tracks.retain(|t| t.id != d.id);
let source = sim.sams[0].id;
sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
}
#[test]
fn last_chance_fires_at_a_class_out_of_roles_only_when_it_is_about_to_hit() {
// The S-400 does not engage drones by default.
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0);
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 60.0);
// Classified as a drone by the picture: the roles block it, the last chance is what fires.
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
let at = until_fired(&mut sim, &mut ground, &land, &mut out, 140).expect("the S-400 never fired on a Shahed about to hit");
assert!(at < LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go");
// The diagnostic names why: the last chance.
// The diagnostic names why: first the role block, then the last chance.
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 100.0);
for _ in 0..30 {
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
let mut saw_block = false;
let mut saw_chance = false;
for _ in 0..220 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
let w = sim.why(0);
saw_block |= w.iter().any(|c| c.legacy_text().contains("не в ролях"));
saw_chance |= w.iter().any(|c| c.legacy_text().starts_with("последний шанс"));
if saw_chance || sim.sams[0].fired > 0 {
break;
}
}
let w = sim.why(0);
assert!(w.iter().any(|c| c.ok && c.legacy_text().starts_with("последний шанс")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(saw_block, "the role block was never named");
assert!(saw_chance, "the last chance was never named");
}
#[test]
@@ -636,10 +743,12 @@ mod tests {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
// In plain view 120 blocks off, but flying away from its aim, 480 blocks (800 ticks) ahead.
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0));
// Classified as a drone: out of the S-400's roles, and not about to hit: nothing fires.
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim");
let w = sim.why(0);
// Still named as the role block it was: no target of its classes.
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("нет целей классов")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
// Still named as what it was: a contact on the picture, out of the roles.
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
}
@@ -650,6 +759,7 @@ mod tests {
sim.last_chance = !off;
sim.sams[0].roles = roles;
shahed_at(&mut sim, 60.0);
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 140).is_none(), "fired with last chance off={off}, roles {roles}");
}
}
@@ -658,12 +768,109 @@ mod tests {
fn last_chance_leaves_a_target_that_already_has_an_interceptor_on_it() {
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
shahed_at(&mut sim, 60.0);
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
// Another system's interceptor is on it.
let id = sim.drones[0].id;
sim.drones[0].engaged = 1;
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 40).is_none(), "fired at {id} that is claimed");
}
#[test]
fn a_probable_class_out_of_roles_is_blocked_and_named() {
// The S-400 does not engage drones. A track only *probably* a drone is already a block:
// the guess is a class, not an unidentified contact.
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0);
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0));
seed_classified(&mut sim, ClassEst::Probable(Class::Drone));
// A target taken before the class was estimated: the diagnostic names the probable class.
sim.sams[0].target = Some(sim.drones[0].id);
let want = format!("роль: вероятно дрон не в ролях [{}]", roles_text(SamKind::S400.spec().roles));
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text() == want), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
// And nothing fires at it while it is far from its aim.
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a probable drone far from its aim");
}
#[test]
fn hold_fire_blocks_an_unclassified_contact_and_says_so() {
// No roles: nothing is a candidate, the unidentified included. Running the sim must not
// turn it into a target.
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.sams[0].roles = 0;
shahed_at(&mut sim, 60.0);
seed_classified(&mut sim, ClassEst::Unknown);
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 200).is_none(), "fired while holding fire");
let w = sim.why(0);
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
}
#[test]
fn a_held_unknown_target_on_a_system_holding_fire_is_explained_without_a_panic() {
// The target was taken before the roles were emptied: the diagnostic must name the hold,
// not unwrap a class the estimate does not have.
let (mut sim, _, _, _) = setup(SamKind::S400);
shahed_at(&mut sim, 60.0);
seed_classified(&mut sim, ClassEst::Unknown);
sim.sams[0].target = Some(sim.drones[0].id);
sim.sams[0].roles = 0;
let w = sim.why(0);
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
}
#[test]
fn roles_read_the_estimate_an_unidentified_track_is_not_blocked() {
// #133: the role filter reads the track's estimated class, never the target's own. While
// the contact is unidentified the S-400 (its roles exclude drones) keeps it as a candidate
// under the general rules — the explicit policy, named in why; once the estimate firms as
// a drone, the block applies and why names that instead.
assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0, "the S-400 does not engage drones");
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.last_chance = false;
shahed_at(&mut sim, 60.0);
let id = sim.drones[0].id;
let roles = sim.sams[0].roles;
let mut saw_open = false;
for _ in 0..300 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
let Some(t) = sim.sams[0].track(id).copied() else { continue };
if t.class != ClassEst::Unknown {
break;
}
saw_open = true;
assert_eq!(why::target_blocks(roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "an unidentified contact must not be role-blocked");
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
break;
}
assert!(saw_open, "the contact was never seen unidentified");
// Classified as a drone, out of the roles: blocked, and the diagnostic says so.
let (mut sim, mut ground, land, mut out) = setup(SamKind::S400);
sim.last_chance = false;
shahed_at(&mut sim, 60.0);
seed_classified(&mut sim, ClassEst::Firm(Class::Drone));
let id = sim.drones[0].id;
for _ in 0..40 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
if sim.sams[0].track(id).is_some_and(|t| t.class == ClassEst::Firm(Class::Drone)) {
break;
}
}
let t = *sim.sams[0].track(id).expect("the track");
assert_ne!(why::target_blocks(sim.sams[0].roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "a classified out-of-role contact must be blocked");
let w = sim.why(0);
assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
// Holding fire (no roles at all): nothing is a candidate, the unidentified either.
let d = sim.drones[0].clone();
let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: battery::Measure::Search, quality: 40, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 1, locked: false };
assert_ne!(why::target_blocks(0, Some(&unknown), 0, &d) & why::ROLE, 0, "with no roles (hold fire) even the unknown is blocked");
}
/// A Kh101 `dist` from the origin on the far side, at height, coming in along z; a radar beside the system.
fn far_setup(radar: bool, dist: f64) -> (Sim, Ground, Land<fn(i32, i32) -> i32>, Out) {
let (mut sim, ground, land, out) = setup(SamKind::S400);
@@ -682,12 +889,27 @@ mod tests {
.drones
.iter()
.filter(|d| d.alive())
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
.map(|d| Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 0,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
})
.collect();
for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) {
for t in &tracks {
r.tracks.retain(|o| o.id != t.id);
r.tracks.push(*t);
r.tracks.push(Track { source: r.id, ..*t });
}
}
}
+8 -6
View File
@@ -608,13 +608,15 @@ mod tests {
#[test]
fn recorded_physical_strike_trail_starts_at_ignition_not_at_the_muzzle() {
use crate::sim::record::{Recording, What};
let mut rec = Recording::blank(40);
rec.straight(1, What::StrikeCarrier(77), 10, 30, DVec3::ZERO, DVec3::Z * 20.0);
let ignite = 10.0 + crate::sim::strike::EJECT_TICKS as f64;
let mut rec = Recording::blank(120);
rec.straight(1, What::StrikeCarrier(77), 10, 90, DVec3::ZERO, DVec3::Z * 80.0);
assert!(replay_smoke(&rec, 14.0).is_empty());
let segments = replay_smoke(&rec, 18.0);
assert_eq!(segments.len(), 1);
assert!((segments[0].az - 5.0).abs() < 1e-6);
assert!((segments[0].bz - 8.0).abs() < 1e-6);
assert!(replay_smoke(&rec, (ignite - 2.0).max(30.0)).is_empty(), "no trail before the ignition");
let segments = replay_smoke(&rec, ignite + 12.0);
assert_eq!(segments.len(), 2);
assert!((segments[0].az - 20.0).abs() < 1e-6 && (segments[0].bz - 24.0).abs() < 1e-6, "the trail begins at the recorded ignition");
assert!((segments[1].az - 24.0).abs() < 1e-6 && (segments[1].bz - 32.0).abs() < 1e-6);
}
#[test]
+10 -3
View File
@@ -179,14 +179,21 @@ mod catalog_tests {
}
fn item_exists(item: &str) {
let name = item.strip_prefix("airdef:").expect("item namespace");
for path in [format!("items/{name}.json"), format!("models/item/{name}.json"), format!("textures/item/{name}.png")] {
for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] {
assert!(assets().join(&path).is_file(), "{item}: missing {path}");
}
let definition = std::fs::read_to_string(assets().join(format!("items/{name}.json"))).unwrap();
assert!(definition.contains(&format!("airdef:item/{name}")), "{item}: wrong item model");
let model = std::fs::read_to_string(assets().join(format!("models/item/{name}.json"))).unwrap();
assert!(model.contains(&format!("airdef:item/{name}")), "{item}: wrong icon reference");
let png = std::fs::read(assets().join(format!("textures/item/{name}.png"))).unwrap();
// The icon reference may be an alias of an existing texture (the optical post uses the
// radar icon until its own asset lands, #136); what matters is that the PNG it names exists.
let layer = model
.split("\"layer0\": \"")
.nth(1)
.and_then(|s| s.split('"').next())
.unwrap_or_else(|| panic!("{item}: no icon reference"));
let texture = layer.strip_prefix("airdef:item/").unwrap_or_else(|| panic!("{item}: bad icon reference {layer}"));
let png = std::fs::read(assets().join(format!("textures/item/{texture}.png"))).unwrap();
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature");
}
fn model_exists(model: &str) {
+40 -5
View File
@@ -1,13 +1,34 @@
//! Text for diagnostics produced by the simulation.
use crate::sim::why::{CheckReason, PartEffect};
use crate::sim::{Comps, Part, SamKind};
fn part_value(part: Part, value: f64) -> String {
if value <= 0.0 { format!("{} отказ", part.short()) }
else { format!("{} {:.0}%", part.short(), value * 100.0) }
}
fn part_value_on(part: Part, value: f64, kind: SamKind) -> String {
if value <= 0.0 { format!("{} отказ", part.short_on(kind)) }
else { format!("{} {:.0}%", part.short_on(kind), value * 100.0) }
}
/// Every worn or failed part of a system, as the monitor and the status line read it.
pub fn parts(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.map(|p| part_value_on(*p, comps.get(*p), kind)).collect::<Vec<_>>().join(", ")
}
/// The weakest worn or failed part alone, for a one-line status.
pub fn worst(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.min_by(|a, b| comps.get(**a).total_cmp(&comps.get(**b)))
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
}
pub fn reason(reason: &CheckReason) -> String {
match reason {
CheckReason::Text(text) => text.clone(),
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| {
if *value <= 0.0 { format!("{} отказ", part.short()) }
else { format!("{} {:.0}%", part.short(), value * 100.0) }
}).collect::<Vec<_>>().join(", ")),
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
CheckReason::PartEffect(effect) => match effect {
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
PartEffect::SensorDamaged { fit } => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", fit * 100.0),
@@ -28,7 +49,21 @@ pub fn reason(reason: &CheckReason) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::Part;
use crate::sim::{Comps, Part, SamKind};
#[test]
fn renders_worn_parts_without_the_reason_prefix() {
let mut comps = Comps([1.0; 6]);
comps.0[Part::Sensor as usize] = 0.4;
comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(parts(&comps, SamKind::Pantsir), "РЛС 40%, Ход отказ");
assert_eq!(worst(&comps, SamKind::Pantsir), "Ход отказ");
// A passive post's sensor is optics; only its sensor is fitted.
let mut optics = Comps([1.0; 6]);
optics.0[Part::Sensor as usize] = 0.4;
assert_eq!(parts(&optics, SamKind::Optical), "Опт 40%");
}
#[test]
fn damaged_simulation_produces_player_diagnostics_in_order() {
use crate::sim::{Sam, SamKind, Sim};
@@ -1017,3 +1017,48 @@ frames = 10
[[step]]
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"
# 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.
[[step]]
command = "airdef deploy ew"
[[step]]
command = "airdef deploy ew"
[[step]]
command = "airdef deploy ew"
[[step]]
command = "airdef deploy ew"
[[step]]
command = "airdef ew on"
[[step]]
command = "airdef preset 1"
expect.feedback = "Готовый: Массированный удар"
[[step]]
command = "airdef raid"
expect.chat = []
[[step]]
ticks = 400
frames = 50
[[step]]
command = "airdef preset 1"
expect.feedback = "Готовый: Массированный удар"
[[step]]
command = "airdef raid"
expect.chat = []
[[step]]
ticks = 800
frames = 100
[[step]]
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"
+16 -2
View File
@@ -50,13 +50,14 @@ expect.feedback = "№2 С-400: режим launcher"
[[step]]
command = "airdef deploy radar_track"
# A deployed radar keeps its equipment profile; only its emissions can be switched.
[[step]]
command = "airdef radar 4 search"
expect.feedback = "№4 РЛС: роль search"
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
[[step]]
command = "airdef radar 4 engagement"
expect.feedback = "№4 РЛС: роль engagement"
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
[[step]]
command = "airdef radar 4 off"
@@ -73,6 +74,19 @@ expect.error = "У комплекса нет активной РЛС"
[[step]]
command = "airdef deploy s500_launcher"
# The wave screen's preset button through the command boundary; an empty wave cannot launch.
[[step]]
command = "airdef preset 0"
expect.feedback = "Готовый: Рой Шахедов"
[[step]]
command = "airdef preset 6"
expect.feedback = "Готовый: Пусто"
[[step]]
command = "airdef raid"
expect.error = "Налёт пуст: выберите типы и число"
[[step]]
command = "airdef wave mix 40 1500"
+55
View File
@@ -126,6 +126,52 @@
{
"kind": "Light",
"item": "deploy_light"
},
{
"kind": "Optical",
"item": "deploy_optical"
}
],
"variants": [
{
"id": "s400_launcher",
"kind": "S400",
"mode": "launcher",
"role": "multi",
"label": "С-400 — отдельная пусковая",
"description": "Пусковая С-400 без своей РЛС: работает по данным сети."
},
{
"id": "s500_launcher",
"kind": "S500",
"mode": "launcher",
"role": "multi",
"label": "С-500 — отдельная пусковая",
"description": "Пусковая С-500 без своей РЛС: работает по данным сети."
},
{
"id": "radar_search",
"kind": "Radar",
"mode": "integrated",
"role": "search",
"label": "РЛС обзора",
"description": "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт."
},
{
"id": "radar_track",
"kind": "Radar",
"mode": "integrated",
"role": "engagement",
"label": "РЛС сопровождения",
"description": "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск."
},
{
"id": "radar_height",
"kind": "Radar",
"mode": "integrated",
"role": "height",
"label": "Мачтовая РЛС",
"description": "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт."
}
],
"items": [
@@ -363,6 +409,15 @@
52
]
},
{
"id": "deploy_optical",
"title": "Развернуть оптический пост",
"color": [
70,
110,
90
]
},
{
"id": "mover",
"title": "Пульт перемещения",
+894
View File
@@ -0,0 +1,894 @@
{
"shared": {
"mobility": {
"drive_scale": 0.4,
"drive_ramp": 8.0,
"trainable": [0.12, 0.0],
"vertical": [0.15, 0.0],
"other": [0.05, 0.05]
},
"flight": {
"gravity": 0.05,
"block_split": 300.0
},
"logistics": {
"depot_reach": 60.0,
"handover": 10.0,
"truck_load": 2,
"stock_limit": 1000000
}
},
"drones": [
{
"kind": "Shahed",
"key": "shahed",
"name": "Шахед-136",
"model": "airdef:shahed",
"speed": 0.6,
"turn": 0.035,
"cruise": 45.0,
"clearance": 18.0,
"dive": 32.0,
"warhead": 3,
"scale": 1.3,
"engine": {"type": "prop", "back": 1.34, "size": 1.0},
"decoy": false,
"stealth": 1.0,
"sound": {"event": "drone.shahed", "pitch": 1.0, "interval": 48},
"class": "drone",
"ballistic": null,
"rcs": 0.3,
"launch_sound": "launch.s400_eject"
},
{
"kind": "Geran3",
"key": "geran3",
"name": "Герань-3",
"model": "airdef:geran3",
"speed": 1.6,
"turn": 0.03,
"cruise": 60.0,
"clearance": 18.0,
"dive": 50.0,
"warhead": 2,
"scale": 1.15,
"engine": {"type": "jet", "up": 0.34, "back": 1.55, "size": 1.0},
"decoy": false,
"stealth": 1.1,
"sound": {"event": "drone.geran3", "pitch": 1.0, "interval": 40},
"class": "jet",
"ballistic": null,
"rcs": 0.4,
"launch_sound": "launch.s400_eject"
},
{
"kind": "Lancet",
"key": "lancet",
"name": "Ланцет-3",
"model": "airdef:lancet",
"speed": 1.1,
"turn": 0.07,
"cruise": 25.0,
"clearance": 10.0,
"dive": 38.0,
"warhead": 1,
"scale": 0.9,
"engine": {"type": "prop", "back": 0.93, "size": 0.55},
"decoy": false,
"stealth": 1.4,
"sound": {"event": "drone.lancet", "pitch": 1.0, "interval": 32},
"class": "drone",
"ballistic": null,
"rcs": 0.08,
"launch_sound": "launch.s400_eject"
},
{
"kind": "Gerbera",
"key": "gerbera",
"name": "Гербера",
"model": "airdef:gerbera",
"speed": 0.5,
"turn": 0.04,
"cruise": 40.0,
"clearance": 15.0,
"dive": 30.0,
"warhead": 0,
"scale": 1.1,
"engine": {"type": "prop", "back": 1.03, "size": 0.9},
"decoy": true,
"stealth": 0.9,
"sound": {"event": "drone.shahed", "pitch": 1.3, "interval": 40},
"class": "drone",
"ballistic": null,
"rcs": 0.4,
"launch_sound": "launch.s400_eject"
},
{
"kind": "Kh101",
"key": "kh101",
"name": "Х-101",
"model": "airdef:kh101",
"speed": 2.4,
"turn": 0.025,
"cruise": 0.0,
"clearance": 12.0,
"dive": 26.0,
"warhead": 6,
"scale": 1.6,
"engine": {"type": "jet", "up": -0.27, "back": 1.4, "size": 0.6},
"decoy": false,
"stealth": 1.5,
"sound": {"event": "drone.cruise", "pitch": 1.0, "interval": 50},
"class": "cruise",
"ballistic": null,
"rcs": 0.05,
"launch_sound": "launch.patriot"
},
{
"kind": "Kalibr",
"key": "kalibr",
"name": "Калибр",
"model": "airdef:kalibr",
"speed": 2.1,
"turn": 0.025,
"cruise": 0.0,
"clearance": 15.0,
"dive": 26.0,
"warhead": 5,
"scale": 1.5,
"engine": {"type": "jet", "up": -0.2, "back": 1.5, "size": 0.6},
"decoy": false,
"stealth": 1.3,
"sound": {"event": "drone.cruise", "pitch": 1.2, "interval": 50},
"class": "cruise",
"ballistic": null,
"rcs": 0.15,
"launch_sound": "launch.patriot"
},
{
"kind": "Kh22",
"key": "kh22",
"name": "Х-22",
"model": "airdef:kh22",
"speed": 4.0,
"turn": 0.03,
"cruise": 140.0,
"clearance": 40.0,
"dive": 150.0,
"warhead": 7,
"scale": 1.8,
"engine": {"type": "rocket", "back": 1.5, "size": 1.3},
"decoy": false,
"stealth": 1.4,
"sound": {"event": "drone.rocket", "pitch": 0.8, "interval": 46},
"class": "supersonic",
"ballistic": null,
"rcs": 1.0,
"launch_sound": "launch.patriot"
},
{
"kind": "Zircon",
"key": "zircon",
"name": "Циркон",
"model": "airdef:zircon",
"speed": 5.5,
"turn": 0.025,
"cruise": 90.0,
"clearance": 30.0,
"dive": 110.0,
"warhead": 6,
"scale": 1.4,
"engine": {"type": "rocket", "back": 1.5, "size": 1.1},
"decoy": false,
"stealth": 2.0,
"sound": {"event": "drone.rocket", "pitch": 1.35, "interval": 46},
"class": "supersonic",
"ballistic": null,
"rcs": 0.4,
"launch_sound": "launch.s400"
},
{
"kind": "Iskander",
"key": "iskander",
"name": "Искандер-М",
"model": "airdef:iskander",
"speed": 5.0,
"turn": 0.04,
"cruise": 0.0,
"clearance": 0.0,
"dive": 0.0,
"warhead": 8,
"scale": 1.8,
"engine": {"type": "rocket", "back": 1.5, "size": 1.6},
"decoy": false,
"stealth": 1.6,
"sound": {"event": "drone.rocket", "pitch": 0.7, "interval": 46},
"class": "ballistic",
"ballistic": 1000.0,
"rcs": 0.6,
"launch_sound": "launch.s500"
},
{
"kind": "Kinzhal",
"key": "kinzhal",
"name": "Кинжал",
"model": "airdef:kinzhal",
"speed": 7.5,
"turn": 0.03,
"cruise": 0.0,
"clearance": 0.0,
"dive": 0.0,
"warhead": 8,
"scale": 1.7,
"engine": {"type": "rocket", "back": 1.5, "size": 1.5},
"decoy": false,
"stealth": 2.2,
"sound": {"event": "drone.rocket", "pitch": 0.6, "interval": 46},
"class": "ballistic",
"ballistic": 1500.0,
"rcs": 0.5,
"launch_sound": "launch.s500"
},
{
"kind": "Oreshnik",
"key": "oreshnik",
"name": "Орешник",
"model": "airdef:iskander",
"speed": 9.0,
"turn": 0.0,
"cruise": 0.0,
"clearance": 0.0,
"dive": 0.0,
"warhead": 0,
"scale": 2.6,
"engine": {"type": "rocket", "back": 1.5, "size": 2.4},
"decoy": false,
"stealth": 3.0,
"sound": {"event": "drone.rocket", "pitch": 0.5, "interval": 46},
"class": "ballistic",
"ballistic": 2600.0,
"rcs": 2.0,
"launch_sound": "launch.s500"
},
{
"kind": "OreshnikBlock",
"key": "oreshnik_block",
"name": "Орешник: блок",
"model": "airdef:reentry",
"speed": 9.0,
"turn": 0.0,
"cruise": 0.0,
"clearance": 0.0,
"dive": 0.0,
"warhead": 4,
"scale": 1.6,
"engine": {"type": "rocket", "back": 1.0, "size": 1.0},
"decoy": false,
"stealth": 3.5,
"sound": {"event": "drone.ballistic", "pitch": 0.8, "interval": 9999},
"class": "ballistic",
"ballistic": null,
"rcs": 0.4,
"launch_sound": "launch.s500"
},
{
"kind": "OreshnikSub",
"key": "oreshnik_sub",
"name": "Орешник: суббоеприпас",
"model": "airdef:reentry",
"speed": 9.0,
"turn": 0.05,
"cruise": 0.0,
"clearance": 0.0,
"dive": 0.0,
"warhead": 3,
"scale": 1.1,
"engine": {"type": "rocket", "back": 1.0, "size": 1.0},
"decoy": false,
"stealth": 4.0,
"sound": {"event": "drone.ballistic", "pitch": 1.0, "interval": 9999},
"class": "ballistic",
"ballistic": null,
"rcs": 0.08,
"launch_sound": "launch.s500"
}
],
"units": [
{
"kind": "Patriot",
"key": "patriot",
"name": "Patriot",
"missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 450.0, "interval": 16},
"gun": null,
"reload": 220,
"scale": 1.3,
"rest_pitch": 0.66,
"roles": 30,
"family": "trainable",
"parts": {
"body": "airdef:patriot_trailer",
"launcher": "airdef:patriot_launcher",
"pack": null,
"dish": null,
"fixed": [["airdef:patriot_truck", 0.0, -3.0], ["airdef:patriot_radar", 0.0, 3.6]],
"spinner": null
},
"mount": [0.69, 1.2],
"pivot": [0.0, -0.5, 1.375],
"muzzle": {"type": "patriot"},
"sensor": 585.0,
"mast": 5.0
},
{
"kind": "Gepard",
"key": "gepard",
"name": "Гепард",
"missile": null,
"gun": {"range": 135.0, "track": 195.0, "p": 0.3, "bursts": 160, "shell": 10.0, "slew": [0.22, 0.16]},
"reload": 160,
"scale": 1.25,
"rest_pitch": 0.0,
"roles": 7,
"family": "gun",
"parts": {
"body": "airdef:gepard_hull",
"launcher": "airdef:gepard_turret",
"pack": "airdef:gepard_guns",
"dish": ["airdef:gepard_dish", 0.95, 0.6, 0.0],
"fixed": [],
"spinner": null
},
"mount": [1.55, 0.25],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 255.0,
"mast": 3.0
},
{
"kind": "Pantsir",
"key": "pantsir",
"name": "Панцирь-С1",
"missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 225.0, "interval": 14},
"gun": {"range": 90.0, "track": 135.0, "p": 0.25, "bursts": 140, "shell": 9.0, "slew": [0.25, 0.18]},
"reload": 280,
"scale": 1.3,
"rest_pitch": 0.0,
"roles": 15,
"family": "turret",
"parts": {
"body": "airdef:pantsir_truck",
"launcher": "airdef:pantsir_turret",
"pack": "airdef:pantsir_pack",
"dish": ["airdef:pantsir_dish", 0.85, 0.3, 0.3],
"fixed": [],
"spinner": null
},
"mount": [1.35, 0.69],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "pantsir"},
"sensor": 292.0,
"mast": 4.0
},
{
"kind": "S400",
"key": "s400",
"name": "С-400",
"missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 720.0, "interval": 20},
"gun": null,
"reload": 420,
"scale": 1.5,
"rest_pitch": {"half_pi": -0.02},
"roles": 30,
"family": "vertical",
"parts": {
"body": "airdef:s400_chassis",
"launcher": "airdef:s400_tubes",
"pack": null,
"dish": null,
"fixed": {"ref": "battery_radar"},
"spinner": {"ref": "battery_spinner"}
},
"mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 2, "size": 7.0},
"sensor": 936.0,
"mast": 5.0
},
{
"kind": "S500",
"key": "s500",
"name": "С-500",
"missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1050.0, "interval": 20},
"gun": null,
"reload": 520,
"scale": 1.6,
"rest_pitch": {"half_pi": -0.02},
"roles": 24,
"family": "vertical",
"parts": {
"body": "airdef:s500_chassis",
"launcher": "airdef:s500_tubes",
"pack": null,
"dish": null,
"fixed": {"ref": "battery_radar"},
"spinner": {"ref": "battery_spinner"}
},
"mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 2, "rows": 1, "size": 9.5},
"sensor": 1365.0,
"mast": 5.0
},
{
"kind": "IrisT",
"key": "irist",
"name": "IRIS-T SLM",
"missile": {"kind": "IrisT", "magazine": 8, "min": 15.0, "max": 600.0, "interval": 10},
"gun": null,
"reload": 300,
"scale": 1.4,
"rest_pitch": {"half_pi": -0.02},
"roles": 15,
"family": "vertical",
"parts": {
"body": "airdef:irist_chassis",
"launcher": "airdef:irist_tubes",
"pack": null,
"dish": null,
"fixed": {"ref": "battery_radar"},
"spinner": {"ref": "battery_spinner"}
},
"mount": [0.7, 1.45],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 4, "rows": 2, "size": 4.0},
"sensor": 780.0,
"mast": 5.0
},
{
"kind": "Nasams",
"key": "nasams",
"name": "NASAMS",
"missile": {"kind": "Amraam", "magazine": 6, "min": 10.0, "max": 450.0, "interval": 14},
"gun": null,
"reload": 260,
"scale": 1.3,
"rest_pitch": 0.5,
"roles": 14,
"family": "trainable",
"parts": {
"body": "airdef:nasams_trailer",
"launcher": "airdef:nasams_launcher",
"pack": null,
"dish": null,
"fixed": [["airdef:radar_trailer", 0.0, 3.4]],
"spinner": ["airdef:radar_panel", 0.9, 3.4, 0.6, -0.3]
},
"mount": [0.62, 0.4],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 3, "rows": 2, "size": 4.0},
"sensor": 585.0,
"mast": 5.0
},
{
"kind": "Buk",
"key": "buk",
"name": "Бук-М2",
"missile": {"kind": "M9m317", "magazine": 4, "min": 20.0, "max": 675.0, "interval": 18},
"gun": null,
"reload": 400,
"scale": 1.4,
"rest_pitch": 0.0,
"roles": 14,
"family": "turret",
"parts": {
"body": "airdef:buk_chassis",
"launcher": "airdef:buk_turret",
"pack": "airdef:buk_rails",
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [1.55, 0.2],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "rails", "xs": [-9.0, -3.0, 13.0, 19.0]},
"sensor": 878.0,
"mast": 4.0
},
{
"kind": "Tor",
"key": "tor",
"name": "Тор-М2",
"missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 240.0, "interval": 8},
"gun": null,
"reload": 300,
"scale": 1.3,
"rest_pitch": 0.0,
"roles": 15,
"family": "vertical",
"parts": {
"body": "airdef:tor_chassis",
"launcher": "airdef:tor_turret",
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [1.5, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "cells"},
"sensor": 315.0,
"mast": 3.5
},
{
"kind": "P1sun",
"key": "p1sun",
"name": "P1-SUN",
"missile": {"kind": "P1sun", "magazine": 8, "min": 5.0, "max": 675.0, "interval": 12},
"gun": null,
"reload": 240,
"scale": 1.1,
"rest_pitch": 0.35,
"roles": 1,
"family": "trainable",
"parts": {
"body": "airdef:nasams_trailer",
"launcher": "airdef:p1sun_launcher",
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [0.6, 0.3],
"pivot": {"ref": "tube_pivot"},
"muzzle": {"type": "grid", "cols": 4, "rows": 2, "size": 3.0},
"sensor": 0.0,
"mast": 2.0
},
{
"kind": "Radar",
"key": "radar",
"name": "РЛС дальнего обнаружения",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.5,
"rest_pitch": 0.0,
"roles": 0,
"family": "static",
"parts": {
"body": "airdef:radar_truck",
"launcher": null,
"pack": null,
"dish": null,
"fixed": [],
"spinner": ["airdef:radar_panel", 1.2, 1.2, 1.5, -0.25]
},
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 2550.0,
"mast": 16.0
},
{
"kind": "Depot",
"key": "depot",
"name": "Склад боеприпасов",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.5,
"rest_pitch": 0.0,
"roles": 0,
"family": "static",
"parts": {
"body": "airdef:depot",
"launcher": null,
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 0.0,
"mast": 1.0
},
{
"kind": "Tzm",
"key": "tzm",
"name": "ТЗМ",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.3,
"rest_pitch": 0.0,
"roles": 0,
"family": "truck",
"parts": {
"body": "airdef:tzm_truck",
"launcher": null,
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 0.0,
"mast": 2.0
},
{
"kind": "Ew",
"key": "ew",
"name": "Станция РЭБ",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.3,
"rest_pitch": 0.0,
"roles": 0,
"family": "static",
"parts": {
"body": "airdef:ew_truck",
"launcher": null,
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 0.0,
"mast": 3.0
},
{
"kind": "Light",
"key": "light",
"name": "Прожектор",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.2,
"rest_pitch": 0.6,
"roles": 0,
"family": "light",
"parts": {
"body": "airdef:searchlight",
"launcher": "airdef:searchlight_head",
"pack": null,
"dish": null,
"fixed": [],
"spinner": null
},
"mount": [0.85, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 0.0,
"mast": 1.5
},
{
"kind": "Optical",
"key": "optical",
"name": "Оптический пост",
"missile": null,
"gun": null,
"reload": 0,
"scale": 1.0,
"rest_pitch": 0.0,
"roles": 0,
"family": "static",
"parts": {
"body": "airdef:radar_truck",
"launcher": null,
"pack": null,
"dish": null,
"fixed": [],
"spinner": ["airdef:radar_panel", 1.2, 0.0, 0.6, -0.2]
},
"mount": [0.0, 0.0],
"pivot": [0.0, 0.0, 0.0],
"muzzle": {"type": "none"},
"sensor": 0.0,
"mast": 2.5
}
],
"missiles": [
{
"kind": "Pac3",
"model": "airdef:pac3",
"speed": 5.5,
"accel": 0.35,
"turn": 0.3,
"boost": 8,
"cold": 0,
"eject": 0.0,
"eject_drag": 0.0,
"pk": 0.9,
"fuse": 4.0,
"life": 240,
"scale": 1.0,
"flame": 1.0,
"rear": 28.0,
"seeker": 110.0,
"launch_sound": "launch.patriot",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.0}
},
{
"kind": "M57e6",
"model": "airdef:m57e6",
"speed": 5.0,
"accel": 0.5,
"turn": 0.32,
"boost": 5,
"cold": 0,
"eject": 0.0,
"eject_drag": 0.0,
"pk": 0.82,
"fuse": 3.0,
"life": 160,
"scale": 0.85,
"flame": 0.65,
"rear": 28.0,
"seeker": 0.0,
"launch_sound": "launch.pantsir",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.12}
},
{
"kind": "M48n6",
"model": "airdef:m48n6",
"speed": 7.0,
"accel": 0.5,
"turn": 0.22,
"boost": 8,
"cold": 20,
"eject": 2.4,
"eject_drag": 0.07,
"pk": 0.9,
"fuse": 5.0,
"life": 300,
"scale": 1.5,
"flame": 1.4,
"rear": 30.0,
"seeker": 120.0,
"launch_sound": "launch.s400_eject",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.88}
},
{
"kind": "M77n6",
"model": "airdef:m77n6",
"speed": 9.0,
"accel": 0.6,
"turn": 0.22,
"boost": 8,
"cold": 24,
"eject": 2.6,
"eject_drag": 0.07,
"pk": 0.95,
"fuse": 6.0,
"life": 320,
"scale": 1.7,
"flame": 1.6,
"rear": 32.0,
"seeker": 120.0,
"launch_sound": "launch.s500_eject",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.8}
},
{
"kind": "IrisT",
"model": "airdef:irist_missile",
"speed": 7.0,
"accel": 0.5,
"turn": 0.35,
"boost": 6,
"cold": 8,
"eject": 1.8,
"eject_drag": 0.1,
"pk": 0.9,
"fuse": 4.0,
"life": 260,
"scale": 0.95,
"flame": 0.9,
"rear": 28.0,
"seeker": 90.0,
"launch_sound": "launch.s400_eject",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.05}
},
{
"kind": "Amraam",
"model": "airdef:amraam_missile",
"speed": 6.0,
"accel": 0.45,
"turn": 0.3,
"boost": 6,
"cold": 0,
"eject": 0.0,
"eject_drag": 0.0,
"pk": 0.85,
"fuse": 4.0,
"life": 260,
"scale": 0.9,
"flame": 0.9,
"rear": 28.0,
"seeker": 130.0,
"launch_sound": "launch.patriot",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.05}
},
{
"kind": "M9m317",
"model": "airdef:m48n6",
"speed": 6.5,
"accel": 0.5,
"turn": 0.25,
"boost": 8,
"cold": 0,
"eject": 0.0,
"eject_drag": 0.0,
"pk": 0.85,
"fuse": 5.0,
"life": 300,
"scale": 1.1,
"flame": 1.2,
"rear": 32.0,
"seeker": 90.0,
"launch_sound": "launch.patriot",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 0.9}
},
{
"kind": "M9m338",
"model": "airdef:m57e6",
"speed": 5.5,
"accel": 0.6,
"turn": 0.4,
"boost": 4,
"cold": 8,
"eject": 1.6,
"eject_drag": 0.1,
"pk": 0.9,
"fuse": 3.0,
"life": 160,
"scale": 1.0,
"flame": 0.8,
"rear": 28.0,
"seeker": 70.0,
"launch_sound": "launch.s400_eject",
"voice": {"event": "missile.flight", "gain": 1.0, "pitch": 1.15}
},
{
"kind": "P1sun",
"model": "airdef:p1sun",
"speed": 2.8,
"accel": 0.12,
"turn": 0.3,
"boost": 4,
"cold": 0,
"eject": 0.0,
"eject_drag": 0.0,
"pk": 0.8,
"fuse": 3.0,
"life": 900,
"scale": 0.8,
"flame": 0.0,
"rear": 10.0,
"seeker": 60.0,
"launch_sound": "drone.lancet",
"voice": {"event": "drone.lancet", "gain": 0.8, "pitch": 1.6}
}
],
"named": {
"battery_radar": {
"kind": "fixed",
"value": [["airdef:radar_trailer", 0.0, 4.2]]
},
"battery_spinner": {
"kind": "spinner",
"value": ["airdef:radar_panel", 0.9, 4.2, 0.9, -0.3]
},
"tube_pivot": {
"kind": "pivot",
"value": [0.0, -0.5, 1.5]
}
}
}
+10
View File
@@ -0,0 +1,10 @@
@echo off
rem Run AirDef with DLSS SR and GPU pass timing. Same game home and mod as play.bat.
chcp 65001 >nul
setlocal
set "HORIZON_DLSS=1"
rem Empty means the DLSS default of 2/3 render resolution.
set "HORIZON_HD_SCALE="
set "HORIZON_HD_DEBUG_MOTION="
set "HORIZON_SHADER_PACK_TIMING=1"
call "%~dp0play.bat" %*
+9
View File
@@ -0,0 +1,9 @@
@echo off
rem Run the same scene with native TAAU at the same 2/3 render scale and timing.
chcp 65001 >nul
setlocal
set "HORIZON_DLSS=0"
set "HORIZON_HD_SCALE=0.67"
set "HORIZON_HD_DEBUG_MOTION="
set "HORIZON_SHADER_PACK_TIMING=1"
call "%~dp0play.bat" %*
+44
View File
@@ -1,5 +1,12 @@
# Акустика AirDef: реализация, проверки и разбор Sound Physics Remastered (#96)
4 ноября добавлен opt-in массовый offline capture fixture: 100 движущихся двигателей и до
16 импульсных источников, настоящие `Audio::tick_acoustics`/`film_mix`, две одинаковые дорожки,
сброс хвоста при новом capture. Release на Apple M5: p50 3.55 мс, p95 4.30 мс, max 5.57 мс
на 50 мс аудио. Геометрия и сэмплы синтетические; это не полный игровой CPU/GPU/FPS и не MP4.
[Команда, результат и оставшаяся приёмка](CONTINUATION-2026-11-04.md),
[JSON и SHA дорожки](measurements/mass-acoustics-2026-11-04.json).
Сначала приведён текущий статус реализации. Разбор SPR и первоначальный план ниже сохранены как
история решений; формулировки будущего времени в плане не заменяют текущий статус. При расхождении прав код.
@@ -48,6 +55,43 @@ GPL-файлы три: `acoustics/spr_occlusion.rs`, (стадия 2) `acoustics
выстрел 1.5 с на 60 блоках, стена камня в 2 блока: ниже 300 Гц -5.2 дБ (SPR: gain 0.55), 300-1500 -7.4, 1500-5000 -19.7, выше 5000 -40.0 дБ.
Тесты: `cargo test -p horizon-client --lib acoustics` (формулы, неизвестное, щель, кеш, инвалидация, детерминизм, рабочий поток) и `audio`.
### Настоящий MP4 с включённой акустикой (4 ноября, pin `73b9d3070`, API 29)
Пары настоящих экспортов одного и того же повтора, с акустикой и без: кнопка мода «Акустика
(преграды, эхо)», затем тот же `/airdef replay export` (640×360, 30 fps, crf 20), offscreen Metal,
ffmpeg 9.0.1, scratch `HORIZON_HOME`/мир (не сохранения игрока). `HORIZON_ACOUSTICS=1` без
`HORIZON_NO_AUDIO`. В сохранённом мире значение акустики хранится в состоянии мода, поэтому env
задаёт только начальное значение: в проверке её включали и выключали кнопкой.
Статусы в игре во время и после экспорта: `Акустика: API=true, включено=true, запрос=true,
подготовлено=true, ready`; `Захват этого мода: запрос=true, подготовлено=true, ready`. Контроль
`HORIZON_ACOUSTICS=1` + `HORIZON_NO_AUDIO=1`: `включено=true, запрос=true, подготовлено=false,
awaiting-backend` — ожидаемое отсутствие offline-микшера, не замена звуковому MP4.
| Сцена | ON: кадры/с | OFF: кадры/с | RMS ON/OFF | пик ON/OFF | L/R corr ON/OFF | centroid ON/OFF | HF>4k ON/OFF |
|---|---|---|---|---|---|---|---|
| поле, 3 события, `sec=4` | 123/4.100 | 124/4.133 | −23.53/−23.26 | −7.18/−5.60 | 0.675/0.627 | 1089/1382 Гц | 0.071/0.095 |
| поле, 1 событие, весь фильм | 351/11.700 | 352/11.733 | −32.18/−16.19 | −12.41/−2.65 | 0.829/0.963 | 1157/1862 Гц | 0.075/0.138 |
| каменный двор 80×100×30 (стены), весь фильм | 430/14.333 | 430/14.333 | −22.06/−20.09 | −5.97/−5.76 | 0.915/0.985 | 232/652 Гц | 0.005/0.039 |
Все пары — `h264` + AAC 48 кГц stereo, без обрезки звука; файлы `airdef-films/{ac,one,court}_{on,off}.mp4`
в scratch. Уже это показывает, что акустика реально обрабатывает дорожку фильма: в каменном дворе
OFF почти моно (L/R 0.985–1.000), ON декоррелирован (0.915); centroid и доля >4 кГц падают, как и
ожидается от окклюзии/воздушного поглощения; в поле ON тише OFF до 16 дБ по RMS за рельефом.
Реверб/эхо: в каменном дворе отрезок 9–14 с (после склейки) описывается ON ≈ g·OFF, g = −2.03 дБ
(лучшее совмещение −32 сэмпла = 0.67 мс). Остаток −25.18 dBFS при сигнале −17.61 dBFS (на 7.6 дБ
ниже), centroid 546 Гц, доля >4 кГц 0.009, L/R corr 0.495: низкочастотный диффузный
декоррелированный компонент — это wet-путь (реверб/эхо), а не масштаб сухого сигнала. В открытом
поле send реверба равен нулю по построению (`acoustics/room.rs`: `a field has no send`), поэтому
поле показывает только окклюзию/поглощение, а реверб — только в замкнутой геометрии.
Ограничения: чистый хвост/RT60 в настоящем MP4 не выделен — в замкнутом зале ON-дорожка была на
30–40 дБ тише (сильная окклюзия), а в открытом дворе длинный сэмпл взрыва (`blast_big`, 15 с; его
21 Гц тон виден в дорожке) маскирует хвост; камеру в комнате с источником и тишиной после него в
этом проходе получить не удалось. Ранние отражения отдельно не измерены. Субъективного
прослушивания не было; 10-минутный экспорт, Windows/Linux и полный бой не проверялись.
### Стадия 2: эхо (сделано)
Что игрок получает: взрыв в ущелье или между домами отвечает настоящим эхо от тех стен, что там есть, с задержкой по
+21 -1
View File
@@ -9,6 +9,26 @@
Дополнительные ракурсы: [Ланцет до](media/aircraft-pass/lancet-before-nose.png), [Ланцет после](media/aircraft-pass/lancet-after-nose.png), [Х-101 до](media/aircraft-pass/kh101-before-nose.png), [Х-101 после](media/aircraft-pass/kh101-after-nose.png).
Снимки сделаны в изолированных мирах Horizon, offscreen, без звука, при времени 6000 и ясной погоде, со светящейся платформой и одинаковыми координатами камеры. В пакетах одинаковы код и остальные ресурсы; для варианта «до» заменены два JSON модели на версии d410e2c. Оба блока после установки проверены через `block`. Ландшафт и состояние подгрузки различаются; снимки не ретушированы. На кадрах видна геометрия обоих силуэтов, но повёрнутые поверхности «Ланцета» остаются почти чёрными даже рядом со светом, как и в исходной модели: это не позволяет уверенно оценить их материал. Полёт, анимация, ночное освещение и массовая производительность не проверены; художественная приёмка остаётся открытой.
## Проверка игрового инстанса
| До | После |
|---|---|
| ![Инстанс до](media/aircraft-pass/lancet-instance-before-nose.png) | ![Инстанс после](media/aircraft-pass/lancet-instance-after-nose.png) |
[Ракурс сверху до](media/aircraft-pass/lancet-instance-before-top.png) · [ракурс сверху после](media/aircraft-pass/lancet-instance-after-top.png).
Проверочный мод `tools/model-preview` выставляет модель через игровой `render.set-models` с `glow=false` и HD-освещением в открытом воздухе. На этих кадрах видны цвет, крылья и нос; это статичный инстанс, полёт и анимация не проверены. Различия яркости наклонных сегментов на старых кадрах исправлены в #123.
## Исправление нормалей (#123)
| До | После |
|---|---|
| ![Осевые нормали](media/aircraft-pass/lancet-instance-normal-before.png) | ![Геометрические нормали](media/aircraft-pass/lancet-instance-normal-fix.png) |
[Сверху после исправления](media/aircraft-pass/lancet-instance-normal-fix-top.png) · [ночь после исправления](media/aircraft-pass/lancet-instance-normal-fix-night.png).
Пара «до/после» снята в одном scratch-мире, с одинаковыми координатами камеры, временем и погодой на Apple M5/Metal. Динамический block-model путь теперь вычисляет нормаль из неколлинеарных вершин квада и использует прежний осевой fallback только для вырожденной геометрии. Unit-тест покрывает оба знака наклона 45°, другие углы, осевые и вырожденные квады. Массовая производительность и полёт этой проверкой не измерялись.
Остальные снимки выше показывают модели как установленные блоки в изолированных мирах Horizon, offscreen, без звука, при времени 6000 и ясной погоде, со светящейся платформой и одинаковыми координатами камеры. В пакетах одинаковы код и остальные ресурсы; для варианта «до» заменены два JSON модели на версии d410e2c. Оба блока после установки проверены через `block`. Ландшафт и состояние подгрузки различаются; снимки не ретушированы. Непрозрачный установленный блок местами выглядит почти чёрным, поэтому его снимки нельзя использовать для оценки освещения игровых инстансов. В исходной серии ночное освещение не проверялось; ночной кадр Lancet после #123 представлен выше. Массовая производительность не проверена; художественная приёмка остаётся открытой.
Редактируемые источники — `airdef-mod/source-assets/assets/airdef/models/block/{lancet,kh101}.json`. Для переэкспорта запустите `python3 tools/aircraft_models.py`, затем `python3 tools/gen_models.py` для установки ресурсов и пересчёта габаритов.
+119 -27
View File
@@ -42,24 +42,36 @@
/airdef battery
```
Нумерацию существующей техники показывает `/airdef battery`. Чтобы переоборудовать её:
Нумерацию существующей техники показывает `/airdef battery`:
```text
/airdef battery <номер С-400 или С-500> launcher
/airdef radar <номер РЛС> search
/airdef radar <номер другой РЛС> engagement
/airdef battery <номер С-400 или С-500> integrated
/airdef radar <номер РЛС> on|off
```
Можно оставить одну многофункциональную РЛС (`multi`) и несколько пусковых.
Поисковая/мачтовая РЛС даёт подсказку, но не разрешает огонь сама. РЛС сопровождения принимает
подсказку и должна **сама измерить** цель в своей игровой досягаемости и с учётом рельефа.
Чужой трек не превращается в собственное измерение. После этого связанные пусковые используют
общую картину и существующее распределение целей. Если РЛС сопровождения уничтожена, свёрнута,
Профиль РЛС задаётся при размещении (`radar_search`, `radar_track`, `radar_height`) и не
переключается на ходу: `radar <номер> search|engagement|height` больше не меняет оборудование.
Можно оставить одну многофункциональную РЛС (`multi`, старые сохранения) и несколько пусковых.
- **Обзорная** (`radar_search`): широкая дальность и ранние грубые отметки, медленный оборот,
без каналов уточнения. Права на пуск не даёт.
- **Мачтовая** (`radar_height`): поднятая антенна и лучшее вертикальное измерение уточняют низкие
контакты в локальной зоне; рельеф по-прежнему скрывает цель. Права на пуск не даёт.
- **Сопровождения** (`radar_track`): локальный поиск, электронный оборот, два канала точных
треков. Сеть может подсказать, но станция должна **сама измерить** цель; только собственное
подтверждённое измерение разрешает пуск.
- **Многофункциональная** (`multi`): совместимый универсальный вариант, но не лучший во всём.
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
продолжают штатную игровую логику связи/памяти/самонаведения.
Старые миры и обычные `/airdef deploy s400` / `s500` сохраняют сборную конфигурацию `integrated`.
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями.
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями; новые
сохранения пишут устойчивый ID профиля, старые строки только с ролью читаются как те же профили.
У прежнего игрового С-500 был магазин на четыре ракеты при двух нарисованных ТПК;
теперь он согласован с двумя физическими ячейками. При загрузке старой расстановки
его загруженный остаток ограничивается новой вместимостью, как при обычном восстановлении боезапаса.
@@ -69,13 +81,26 @@
1. Подготовка резервирует конкретную ячейку. Отдельная крышка ТПК открывается; ракета ещё не расходуется.
2. При потере цели или неисправности/сворачивании носителя до выброса подготовка отменяется.
3. Ракета выбрасывается из фактического muzzle. Боекомплект уменьшается один раз; использованный ТПК остаётся открытым.
4. В фазе выброса отсутствуют факел, непрерывный звук двигателя и его дымовой след.
5. После зажигания включаются эффекты, ракета разгоняется и начинает поворот по существующей игровой логике.
4. Выброс идёт без двигателя: ракета поднимается и линейно теряет скорость под газовым сопротивлением.
Длительность считается от выброса, а не от открытия крышки: у С-400 (`M48n6`) 20 тиков — 1,00 с,
у С-500 (`M77n6`) 24 тика — 1,20 с, у IRIS-T и Тора (`IrisT`/`M9m338`) 8 тиков — 0,40 с.
В этой фазе нет факела, непрерывного звука двигателя, моторного света и powered smoke; остаётся
только отдельный газовый хлопок/клуб.
5. Зажигание — отдельное событие в текущей точке ракеты, а не у оставленной ПУ: там же появляются
вспышка, факел, звук и запись `MotorIgnition`. Оно наступает после `cold` тиков выброса.
6. После зажигания начинается departure: тяга плавно нарастает от 45% к 100%, а допустимый темп
поворота — от 20% к полному за `boost` тиков. Полное наведение (включая самонаведение и облёт
рельефа) включается только при `age >= cold + boost`; при увеличении `cold` оно не может
включиться раньше мотора. Максимальная скорость, `pk`, `turn` и правила столкновений не менялись.
Это действует для зенитных С-400/С-500 и подготовленного ударного RM48U у С-400.
У ручного удара носитель и ячейка резервируются до пуска; изменение состояния отменяет подготовку
без расхода. Для RM48U добавлен плавный разгон после выброса. Задержанный ручной приказ
не возобновляется после загрузки мира: незапущенный боеприпас остаётся в носителе.
без расхода. RM48U использует ту же 20-тиковую хореографию: неосвещённый выброс, зажигание в текущей
точке, затем разгон; насчитанное время полёта включает выброс, а записанный дым начинается у точки
зажигания. Задержанный ручной приказ не возобновляется после загрузки мира: незапущенный боеприпас
остаётся в носителе. Ракеты с рельсовым (горячим) пуском тоже получили плавное нарастание тяги за
свой `boost`, но не холодный выброс; электрический P1-SUN сохраняет постоянный разгон и не получает
ракетную струю.
В записи сохраняются конфигурация машины, использованные ячейки и положение крышки;
повтор восстанавливает их по своей временной шкале. Записанный дым начинается у точки зажигания,
@@ -83,26 +108,39 @@
## Ограничения
Роли РЛС и мачта пока используют общую модель машины, с разным поведением/отображением антенны.
Отдельные точные модели 91Н6/92Н6/96Л6, машина КП, ручная принадлежность к батарее, отдельные
каналы сопровождения и кабельное снабжение пока не добавлены. Подробные режимы и параметры реальных
Все три профиля пока используют общий силуэт машины и антенны (отдельная художественная зона
владельца): различаются поведение, цикл, точность, каналы и подпись. Точные модели 91Н6/92Н6/96Л6,
машина КП, ручная принадлежность к батарее и кабельное снабжение не добавлены. Подробные режимы и параметры реальных
комплексов не моделируются. В следующей серии добавлены конечная работа двигателя/coast (#120),
доставка RM48U через ТЗМ (#118), переключение излучения (#121) и укрытия от непрямого blast (#119).
Текущий объём и ограничения описаны в [техническом журнале](CODEX-HANDOFF.md).
## Проверка в игре и тестами
Исходный код батареи и команды опубликованы в `966b52f`. Для этой контрольной точки прошли
169 тестов ядра и 4 сценария (7 отдельных тестов помечены ignored), а также 53 теста адаптера,
проверка границы с ядром и ещё 4 сценария. Настоящий собранный WASM-пакет прошёл 21 шаг
`wasm_contract.toml`, включая конфигурацию батареи и развёртывание новых пресетов.
Генератор моделей не обнаружил различий с исходниками.
Историческая контрольная точка батареи и команд — `966b52f`: 169 тестов ядра и 4 сценария
(7 ignored), 53 теста адаптера, проверка границы с ядром и ещё 4 сценария; настоящий WASM-пакет
прошёл 21 шаг `wasm_contract.toml`, генератор моделей не нашёл различий.
Отдельный тест симуляции проверяет открытие до расхода, отмену при повреждении,
однократное списание при выбросе, отсутствие голоса двигателя до зажигания и последующий рост скорости.
Тест повтора проверяет перемотку состояния крышек и конфигурации пусковой туда и обратно.
Контрольная точка #129 — `4b013fb7f30dbaa87a266b27a31911937fc523b4` (ветка
`agent/issue-129-cold-launch`): core release **206 + 8 сценариев** (8 ignored), адаптер
**67 + 1 boundary + 5 сценариев**, настоящий WASM **30 шагов**, `gen_catalog.py --check` без
расхождений, `gen_models.py --check` без различий, `test_gen_assets.py` — 10 тестов.
Ниже — исходные кадры из изолированного тестового мира Horizon, Metal, 2560×1440.
Отдельные тесты проверяют открытие до расхода, отмену при повреждении, однократное списание при
выбросе, отсутствие голоса/факела до зажигания, записанное зажигание через `cold` тиков после
выброса, плавные ограничения скорости и поворота для всех профилей, а также RM48U без powered
эффектов до зажигания. Тест повтора проверяет перемотку состояния крышек и конфигурации ПУ туда и
обратно и отсутствие дыма до записанного зажигания.
Сравнительная выборка #129 (те же seed, что у сетки #120; 6 вариантов × 8 seed, 2208 целей на
сторону): сбито 1988 → 1939, прорывов 216 → 258, ракет 3461 → 3467; `energy_lost` 0 → 0,
`expired` 1 → 0, сорванных о рельеф 2 → 4. Близкие (`near200`) 318 → 311 сбитых, дальние
(`far1500`) 338 → 334, холмы (`hills20`) 334 → 319. Отдельные 12 seed `SAMS=20 SIZE=12`:
203 → 201 сбитых, 1 → 3 прорыва, 355 → 360 ракет. Это ожидаемое следствие более длинного старта,
а не скрытая компенсация: `pk`, максимальные скорости и столкновения не менялись. Данные:
[сетка](measurements/issue-129-grid.csv), [рейды](measurements/issue-129-balance.csv).
Ниже — исходные кадры крышек из изолированного тестового мира Horizon, Metal, 2560×1440.
На первом четыре малые крышки ТПК закрыты; на втором одна поднята, остальные закрыты.
Большая прямоугольная панель позади труб — навесная РЛС конфигурации `integrated`.
@@ -114,5 +152,59 @@
`3fae616902563b01e6463a32687c062d5983c4e94bd357f8f8129744d859f4d7`;
геометрия крышек и их преобразования совпадают с опубликованной версией.
Сохранение после пуска содержит 3 оставшиеся ракеты С-400 и маску использованной ячейки `1`.
Эти кадры подтверждают положение крышек, но не являются видеопроверкой всех стадий полёта:
сам выброс и момент зажигания крупным планом снять не удалось.
### Парная съёмка #129: до и после
Оба ролика сняты на одном и том же scratch-мире `ColdLaunch129` (плоский тестовый рельеф,
`--creative`), одном сохранении мира, одном сценарии `pair129` и одном seed
`965460218386186365`. Сценарий: С-400 в точке `1.5 72 8.5`, роли `31`, один Х-22, налёт с 900.
Оба прогона — один и тот же клиент/движок `278f356aa` (API30), одни ресурсы, Metal/offscreen,
`HORIZON_NO_AUDIO=1`, одна команда режиссёра
`/airdef replay export <имя> best fps=30 size=1280x720 crf=16 sec=24`.
| | До (`dc36d67`) | После (`4b013fb`; hmod `00f0209`) |
|---|---|---|
| `.hmod` SHA-256 | `2d828aa8…` | `ca3bdd30…` |
| исходный MP4 | 17 268 968 Б, 403 кадра | 17 832 718 Б, 412 кадров |
| длительность | 13,433 с | 13,733 с |
| поток | h264 1280×720 30 fps + AAC 48 кГц | то же |
| план «Пуск» | кадры 94–151 | кадры 94–160 |
| первое освещение центра | кадр 101 = 0,233 с | кадр 121 = 0,900 с |
| `cold` профиля | 5 тиков = 0,25 с | 20 тиков = 1,00 с |
«Первое освещение» — прокси зажигания/факела: первый кадр, где средняя яркость центрального
окна 100×120 px (`x 590..689`, `y 300..419`) превышает 100/255. До (`dc36d67`) это кадр 101, через 7 кадров
после начала плана «Пуск» (кадр 94) — 0,233 с при `cold=5` (0,25 с). После — кадр 121, через
27 кадров — 0,900 с при `cold=20` (1,00 с); к кадру 124 окно выходит на устойчивую яркость
≈198. Разница 0,667 с совпадает с разницей `cold` 15 тиков = 0,75 с в пределах 2–3 кадров
(30 fps). Аудиодорожка даёт тот же сдвиг: RMS (окно 50 мс) впервые превышает 0,03 на 3,45 с
до и 4,15 с после при старте плана 3,10 с, то есть через 0,35 и 1,05 с; это атака звука, а не
кадр зажигания. Полные числа и хэши:
[issue-129-pair.json](measurements/issue-129-pair.json).
Оба MP4 лежат в `docs/media/cold-launch`: [до](media/cold-launch/cold-launch-129-before.mp4) и
[после](media/cold-launch/cold-launch-129-after.mp4), в перекодировке h264 CRF26 для хранения;
число кадров, 30 fps, длительность и AAC сохранены. Исходные файлы с CRF16 и их SHA-256
записаны в JSON.
Это **replay/export**, не live-видео: живые кадры в MP4 не писались (`--offscreen` не даёт окна
для сторонней записи, встроенной live-записи у мода нет). Звук сведён офлайн, живое
прослушивание не выполнялось.
Парные кадры (слева — до, справа — после), один и тот же кадр фильма:
![Общий план перед пуском, кадр 60](media/cold-launch/cold-launch-129-pair-general.png)
![0,53 с после начала плана «Пуск»: до уже с факелом, после ещё без него](media/cold-launch/cold-launch-129-pair-0.5s.png)
![1,0 с: у «после» факел уже горит (начало — кадр 121)](media/cold-launch/cold-launch-129-pair-1.0s.png)
![1,53 с: обе ракеты под тягой](media/cold-launch/cold-launch-129-pair-1.5s.png)
**Ограничение приёмки.** Агент, выполнивший прогон, не имеет ввода изображений и не может сам
оценить композицию, читаемость и красоту кадров. Проверены факт и параметры съёмки, одинаковый
старт плана «Пуск» (кадр 94), яркость центра и её сдвиг по времени; парные кадры приложены для
человеческого просмотра. Кадры до/после не пиксельно идентичны: это два отдельных живых прогона,
камера общего плана движется, листва/трава анимированы, поэтому в предпусковых кадрах остаётся
разница в несколько уровней яркости. Совпадают мир, сохранение, сценарий, seed, метод камеры и
команда экспорта, а не каждый пиксель. Отдельный очень крупный статичный план выброса у самой ПУ
не снят; план «Пуск» — боковой с 46 блоков. Это не полная визуальная приёмка #129.
+349 -4
View File
@@ -4,7 +4,131 @@
Рабочая ветка `kimi-work`; issues не закрывать, публиковать комментарии с коммитом и проверками.
Движок — отдельный `chexit/horizon-airdef`, ветка `airdef`, подключён точным gitlink `horizon/`.
## Текущее состояние: 3 ноября 2026
## #91: типизированные варианты комплексов — первый slice (20 ноября 2026)
Ветка `agent/91-variants` (worktree `/tmp/airdef-issue91`), база `60f1bf0fd`
(рабочая ветка `kimi-work`), движок `ed751714e` не менялся. Минимальный вариант,
который требует текущий код: развёртывание «элементов батареи» (`s400_launcher`,
`s500_launcher`, `radar_search/track/height`) описывалось тремя разрозненными
ручными списками — таблица меню `BATTERY_DEPLOY` и `match` конфигурации в `lib.rs`
и цепочка ids в `commands.rs`. Они сведены в каталог: `catalog/content.json → variants`
(ключи `mode`/`role` переиспользуют существовавшие ключи сохранений `SamMode`/`RadarRole`),
`gen_catalog.py` генерирует `unit_variants_generated.rs` → `catalog::UnitVariant`
(`id/kind/mode/role/label`), Python-валидация отвергает дубли, чужие kinds/modes,
совпадение с ключами/предметами. Меню батареи, клик по строке и Tab-дополнение
`deploy` читают таблицу; генерация порядка строк прежняя, тексты прежние. **Профили
боезапаса по вариантам не заводились**: для «разных ракет/профилей по батареям» требуется
согласованный профиль и явно подписанная игровая абстракция (замечание ревью по
PAC-3 в комментарии #91) — следующий slice, не этот. Save/replay/тексты не менялись:
вариант — только ключ развёртывания поверх тех же полей `sam`, сейв-формат, порядок
и `durable mark` без изменений. То же видно и в `airdef-core` (общая симуляция).
Остаток #91: профили боезапаса по вариантам, объединение Python-генераторов и других списков,
игровая приёмка.
## Текущее состояние: 4 ноября 2026
Последнее продолжение пяти задач: [CONTINUATION-2026-11-04.md](CONTINUATION-2026-11-04.md).
Движок `57f8b2853c4443f7e3ff5701600cbb262b53118f`, API29. В этом файле ниже сохранён
исторический журнал предыдущих серий; старые SHA и числа тестов не заменяют новую контрольную точку.
След #91 продолжен: `catalog/specs.json` — единственная копия числовых строк дронов, ракет и
комплексов; `python3 tools/gen_catalog.py` генерирует `specs_generated.rs` и
`unit_specs_generated.rs`, `--check` (CI) валит расхождение. Числа не менялись; сверка с литералами
подтвердила 1.6 как фактический голос P1-SUN (недостижимый `P1sun => 1.7` в старом match не в счёт);
на это добавлена Rust-регрессия. Остаток: варианты комплексов и игровая приёмка.
### Продолжение #129: стадии холодного пуска и разгон (6 ноября 2026)
Ветка `agent/issue-129-cold-launch`, кодовый коммит `4b013fb7f30dbaa87a266b27a31911937fc523b4`
(документация, измерения и кадры — следующим коммитом этой же ветки).
Игра/движок не менялись: pin `278f356aa604fa21c2d15d0081823bbe0f891df2`, API30. Push не выполнялся,
issues не закрывались.
**Контракт стадий.** У `MissileSpec` появились `eject` и `eject_drag`; `cold` — тики физического
выброса, `boost` — тики departure. `guided(age) = age >= cold + boost`; основная ветка наведения,
самонаведение и облёт рельефа больше не могут включиться до зажигания (раньше было `age >= boost`,
что при большом `cold` включало наведение до мотора). Зажигание — по-прежнему `age > cold`;
событие `MotorIgnition`, звук, факел и голос используют текущую позицию ракеты. `departure_ramp`
растёт 0→1 за `boost`; темп поворота в departure — `turn·(0.2 + 0.8·ramp)`. Тяга ракетных
профилей — `accel·(0.45 + 0.55·ramp)`, на guidance — полная. P1-SUN (`flame=0`) сохраняет
полный разгон без ракетной струи.
**Профили.** `M48n6`: `cold=20`, `eject=2.4`, `eject_drag=0.07` — 1,00 с; `M77n6`: `cold=24`,
`eject=2.6`, `eject_drag=0.07` — 1,20 с; `IrisT`/`M9m338`: `cold=8`, `eject=1.8/1.6`,
`eject_drag=0.1` — 0,40 с. Рельсовые профили (`cold=0`) получили только spool тяги; ранний
поворот на рельсовом пуске был проверен и отменён: он уводил Pac3 в землю на холмах и валил
`an_interceptor_over_rolling_land_does_not_hit_the_ground`. `speed`, `accel`, `turn`, `pk`,
`fuse` и правила столкновений не менялись.
**RM48U.** `EJECT_TICKS` 5 → 20. Выброс неосвещённый и замедляется; зажигание на `EJECT_TICKS`,
факел/звук/голос с этого момента; насчитанное время полёта включает выброс; дым в записи
начинается от точки зажигания, а не от горловины. Live, repeat и export читают одно и то же
состояние `lit`/записанное `MotorIgnition`.
**Проверки.** core release **206 + 8 сценариев**, 8 ignored; адаптер **67 + 1 boundary +
5 сценариев**; настоящий `.hmod` — **30 шагов** `wasm_contract.toml`; `gen_catalog.py --check` и
`gen_models.py --check` без расхождений; `test_gen_assets.py` — 10 тестов; `git diff --check` чист.
Новые регрессии: стадии по порядку и отсутствие powered-эффектов до зажигания; `guided` не раньше
`cold` для всех профилей; непрерывность скорости/поворота и throttled первый powered тик; P1-SUN
без факела; записанное зажигание через `cold` тиков и `missile_is_lit` по нему; RM48U без
голоса/факела до зажигания и ровно один звук зажигания.
**Баланс.** Сетка #120 (6 вариантов × 8 seed, 2208 целей на сторону, baseline `dc36d67`):
сбито 1988 → 1939, прорывов 216 → 258, ракет 3461 → 3467; `near200` 318 → 311, `far1500`
338 → 334, `hills20` 334 → 319; `energy_lost` 0 → 0, `expired` 1 → 0, scrub 2 → 4.
`SAMS=20 SIZE=12`, 12 seed: 203 → 201 сбитых, 1 → 3 прорыва, 355 → 360 ракет. Отдельные CSV:
[сетка](measurements/issue-129-grid.csv), [рейды](measurements/issue-129-balance.csv).
Это намеренное следствие более длинного старта; скрытого повышения `pk` или максимальной скорости нет.
**Парная съёмка.** Один scratch-мир `ColdLaunch129`, одно сохранение, сценарий `pair129`,
seed `965460218386186365`, один клиент/движок API30, один режиссёр
(`/airdef replay export … best fps=30 size=1280x720 crf=16 sec=24`), Metal/offscreen.
Сценарий: С-400 `1.5 72 8.5`, роли `31`, один Х-22 с 900; мод до — `dc36d67`, после — `4b013fb`.
Оба MP4: h264 1280×720 30 fps + AAC 48 кГц; до — 403 кадра/13,433 с, после — 412/13,733 с.
План «Пуск» стартует на кадре 94 в обоих; первое освещение центра (окно 100×120, порог 100)
до — кадр 101 (0,233 с после старта, `cold=5` = 0,25 с), после — кадр 121 (0,900 с,
`cold=20` = 1,00 с); к 124 кадру устойчиво ≈198. Это подтверждает сдвиг холодной паузы на
≈0,67 с между сборками. MP4 в `docs/media/cold-launch` перекодированы в CRF26 для хранения;
исходные файлы, их SHA-256, ffprobe и логика измерения — в
[issue-129-pair.json](measurements/issue-129-pair.json). **Ограничение:** у агента нет ввода
изображений; проверены параметры, старт плана, яркость центра и парные кадры, но композицию и
красоту кадров человеком ещё нужно оценить. Предпусковые кадры не пиксельно идентичны (живой
прогон, движение камеры, анимация листвы); совпадают мир/сейв/сценарий/seed/метод камеры.
Отдельный very-close статичный план и live-MP4 не сняты (`--offscreen` без окна). Это не полная
визуальная приёмка.
### Продолжение #122 (второй налёт из UI)
Точный лог Windows: `stopped in UI event (fuel budget 1000000000, remaining Some(0))`,
backtrace `known_units ← order_raid ← launch_wave ← ui_select` — другой класс, чем тик
`1f28f83`. Причина: `order_raid` пересчитывал снимок известных комплексов на каждом дроне,
а сам снимок был квадратичен по журналу и группировке. Исправление: один снимок на приказ
(+ O(журнал+группировка) через множества, `price_grid_on` переиспользует свой снимок);
семантика целеуказания и выбора носителей не менялась, сверка с прежним предикатом в
нативном тесте, `/stats` в WASM совпал побайтово. Лимиты не трогали, HD/запись не отключали,
размер волны не ограничивали.
Воспроизведение в настоящем WASM (измеренный fuel): до — второй приказ 111 дронов исчерпывает
ровно 1e9 в событии (failures=1), тот же приказ 11 дронов — 247805865; после — тот же сценарий
целиком: max command 32946177/1e9, tick 236581288/300M, ошибок 0. Диагностический гость
(`trigger.patch` вызывает обработчик `ui_select(BTN_LAUNCH)`) и точный сценарий:
[issue-122-ui-fuel](measurements/issue-122-ui-fuel/summary.json). Воспроизвести удалось только
с разнесённой группировкой: стек в одной точке гибнет от одной боеголовки (`known=0`, приказ
дёшев) — у пользователя силы дожили до второго приказа.
Закреплённые регрессии: нативные «эквивалентность снимка» и «второй умный приказ с толстым
журналом принят и запущен»; тяжёлый WASM fixture расширен двумя умными приказами через
`airdef preset` + `airdef raid` (функция кнопки ПУСК) — 4 принятых приказа, SHA fixture
обновлён; лёгкий контракт 30 шагов с `preset` и отказом пустой волны. Новая команда
`airdef preset <n>` — script-эквивалент кнопки готового состава.
Последний общий прогон: core release **195 + 8 сценариев** / 7 ignored; адаптер **65 + 1
boundary + 5 сценариев**; лёгкий WASM **30 шагов**; тяжёлый WASM **283 шага** (tick max
182413686/300M, command max 6939810/1e9, failures=0), отчёт
[flat-wasm-raid-budget](measurements/flat-wasm-raid-budget.json); 6 тестов отчёта budget
и build-тест прошли. Ни одно issue не закрыто; пуш не выполнялся.
### Контрольная точка 3 ноября
Код предыдущих четырёх задач интегрирован до `6e2d661`. Продолжение #102/обратного вывоза
опубликовано до `aab3e78`; последнее продолжение расследования налётов — `2932364`.
@@ -64,8 +188,9 @@ awaiting-backend. Выход через quit подтверждён. Это не
## Двойные налёты и плотность следов
Перед продолжением читать [RAID-STABILITY.md](RAID-STABILITY.md): один соответствующий класс
отключения теперь воспроизведён и исправлен (`1f28f83`), приёмка конкретного Windows-сеанса остаётся.
Перед продолжением читать [RAID-STABILITY.md](RAID-STABILITY.md): два соответствующих класса
отключения теперь воспроизведены и исправлены — тик (`1f28f83`) и событие UI на втором
приказе (#122, `order_raid`/known_units); приёмка конкретного Windows-сеанса остаётся.
Текущий исправленный WASM stress проверяет две принятые волны, обслуживаемую плоскую геометрию
и 184 воздушные цели в конкретный момент; новый [JSON](measurements/flat-wasm-raid-budget.json)
заменяет прежнее недостаточное доказательство покрытия. Лимиты fuel/memory не увеличивались.
@@ -214,6 +339,30 @@ baseline — 202 сбитых, 2 прорыва, 367 ракет; новое —
Это небольшой регрессионный ориентир, не доказательство баланса всех типов/дальностей.
Данные каждого seed: [CSV](measurements/issue-120-balance.csv).
Расширенная сетка остатка #120 (ветка `agent/issue-120-balance`, коммит см. в git):
baseline `2689d93` против текущего `e6a7000` (то есть с #118/#119/#121 и сменами движка, не только #120),
6 вариантов × 8 одинаковых seed, рейд `SIZE=36` (46 целей: Gerbera 10, Shahed 13, Geran3 5, Х-101 5,
«Калибр» 4, Х-22 2, «Циркон» 1, «Искандер» 4, «Кинжаль» 2; «Орешник» harness исключает, как в `one_raid`):
`batt10/20/50` (10/20/50 ЗРК, дистанция 500), `near200` (20 ЗРК, пуск в 200), `far1500` (20 ЗРК, пуск в 1500),
`hills20` (20 ЗРК, холмы, 500). Кластер тот же `MIX` из 10 систем: `SAMS=10` — по одному комплексу каждого типа.
Итого 2208 целей на сторону, 96 строк: [CSV](measurements/issue-120-grid.csv). Команда (игнорируемый тест
`sim::balance::issue_120_grid`, только harness-поля в `Result`, поведение симуляции не менялось):
```sh
SEEDS=1-8 cargo test --release --manifest-path airdef-core/Cargo.toml issue_120_grid -- --ignored --nocapture
```
Факты сетки (суммы по 8 seed каждого варианта, baseline → текущий): сбитые 297→301 (batt10), 331→334 (batt20),
357→363 (batt50), 313→318 (near200), 328→338 (far1500), 328→334 (hills20); прорывы 70→66, 37→34, 11→5,
53→48, 40→30, 39→33. Промахов по взрывателю заметно меньше (например far1500: 70→38). Расход ракет близок
(516→504 … 597→583). На холмах потери у рельефа: разбито 14 и 14, самоуничтожений у хребта 6→2.
Прорывы во всех вариантах — преимущественно баллистические и быстрые классы («Искандер», «Кинжаль», Х-22,
«Циркон»); у медленных Shahed/Gerbera прорывов почти нет (0–2 на вариант), у ложных Gerbera — ноль ни разу.
`MotorEnergyLost` не сработал ни в одном из 48 сценариев текущего кода, `expired` ≤ 1 на вариант: coast
существует, но бои на этих дистанциях заканчиваются раньше, чем сопротивление 0.995/тик опустит скорость
ниже порога 25% (и раньше выработки ресурса). Это измеренное свойство профиля, не подтверждённый дефект,
поэтому параметры не менялись. Путь потери энергии покрыт юнит-тестом регресса (`regress.rs`), а не этой сеткой.
```sh
SAMS=20 SIZE=12 cargo test --release --manifest-path airdef-core/Cargo.toml sim::balance::one_raid -- --ignored --nocapture
```
@@ -298,13 +447,209 @@ Unknown, stale и слишком старые секции считаются **
Unknown и поздний ответ без повторного урона/запросов; прямое попадание; устаревшая геометрия;
пропуск исходного блока. Все четыре прошли в объединённом наборе.
### #127: устойчивая очередь маршрутов после массового перенацеливания
Реализована только узкая часть issue: `sim::ew::RouteJob` — задание с ID дрона, новой целью,
ID цели-юнита, версией знаний и общим для тика снимком `known_units` (`Arc`). `adapt` по-прежнему
выбирает новые цели раз в 40 тиков, но маршруты теперь достраивает `replan_retargets` **каждый
тик**: одно задание или несколько, пока не исчерпан `WORK_PER_TICK`. Незавершённое задание
остаётся в `Sim::retargets` (FIFO) и не теряется; повторный выбор того же дрона заменяет задание
на месте, поэтому очередь не растёт.
Старый маршрут не очищается при перенацеливании: дрон следует готовому безопасному участку,
пока новое задание не получит маршрут. Если задание отменяется (дрон погиб, цель изменена снова,
юнит уничтожен), маршрут очищается как fallback — дрон летит прямо до следующего адаптивного тика.
Lancet, баллистика и decoy, как и раньше, летят прямо: для них задание не создаётся. В полёте
следующая известная цель берётся только если до неё есть разворот; цель сзади внутри радиуса
разворота пропускается, и дрон завершает текущий заход, а не получает невыполнимый маршрут.
Повторный план использует снимок разведки исходного выбора цели и известный рельеф **той же версии
задания**: `KnownRelief` (сетка и высоты) лежит в `Arc` внутри `RouteJob`, `Sim::known_relief` хранит
тот же `Arc` только для новых заданий. Завершение другой умной волны заменяет глобальный указатель,
но не снимок ожидающего job. Выборка рельефа, цены и кэш маршрутов в `replan_retargets` ключуются
версией знаний целиком — adapt tick плюс указатели на снимки known units и рельефа, — а не только
рельефом: два job с одинаковым рельефом, но разными known units, не делят price/route grid. За
пределами известной сетки — Unknown, новая карта не раскрывается.
Очередь этапа 1 была рантайм-состоянием планировщика: дроны и очередь запуска в `state_text` не
входили, поэтому durable-очередью она не была. Этап 2 (ниже) сохраняет её вместе с дронами, очередью
запуска, картиной и версиями рельефа. Регрессии этапа 1 остаются: `mass_retarget_finishes_its_route_jobs_over_the_budget`
(40+ ретаргетов, прогресс каждый бюджетный тик, старый маршрут до нового, нет пустых маршрутов)
и `mass_retarget_is_deterministic_and_never_duplicates_a_drone` (тот же seed — те же цели и
маршруты; повторный `adapt` не создаёт дублей).
### #127, этап 1: честная EnemyPicture
Журнал `intel.revealed: Vec<(id, место, тик)>` заменён картой контактов: `Intel.contacts: BTreeMap<u32, Contact>`,
одна запись на юнита, последнее наблюдение побеждает. Контакт пишется только в момент раскрытия и
читает истину только тогда: пуск (mod.rs/strike.rs) → `Seen::Launch`; фиксация излучения
радаром рядом с чужим аппаратом (sight.rs, каждые 20 тиков, 1600 блоков) → `Seen::Emission`
(отдельно помечается `emission` — вера в собственный сенсор опирается только на неё); работающая
РЭБ (ew.rs) → `Seen::Jamming`; четвёртый канал — BSA: падение собственной боеголовки рядом с
известным юнитом (`Sim::observe_outcomes`, радиус 16) фиксирует `destroyed` либо обновляет «жив»
и место. Пока юнит незамечен, его перемещения, выключение радара, смена ролей/режима, расход БК,
урон и гибель картину не меняют — это метаморфные тесты `sim::ew::picture_tests`.
Из контактов решается всё: снимок `picture_of_defences()` на приказ и на адаптивный тик (newest first,
при равном тике — больший id, как у старого reversed-журнала), цели `choose_target` и SEAD
(`radar_strikes` — только Probable и свежее), ретаргет в полёте (цель «мертва» лишь по контакту с
`destroyed`; забытого контакта дрон не замечает), живость задания очереди (`job_live` — по картине,
не по истине). Уверенность — функция одного возраста: Confirmed ≤ 600, Probable ≤ 3000, Doubtful до
TTL 6000 тиков (`Confidence`, диагностика и SEAD её используют, цены — нет: консервативно считаются
все живые контакты).
Модель возможностей в `price_grid_known` читает только картину: роли — published `kind.spec().roles`
(смена `/airdef roles` невидима), дальности — `ew::published_reach` (без урона, фактора роли и
мачт истины), донор — любой живой контакт вида Radar в link range от наблюдённого места (роль
донора не наблюдаема: рабочий контакт РЛС предполагается кормящим сеть — это допущение, а не
знание; разрыв связи/гибель донора незамеченными картину не меняют). Собственный сенсор верится,
пока жива фиксация эмиссии; пуск при нуля эмиссионных фиксаций у С-400/С-500 читается как
launcher-only: без донорского контакта такая ПУ в ценовой сетке «слепа», с ним бьёт на дальность
донора. Горизонт РЛС игрока (`self.horizons`) из чужого планировщика убран: маскировка рельефа —
тайна обороны, цены по ней консервативнее и объяснимее.
Диагностика без GUI: `Sim::enemy_picture() -> EnemyPictureReport` (англ.): по каждому контакту —
наблюдение (канал, место, возраст), уверенность, живость, наблюдённое уничтожение, вера в сенсор,
наличие донора и текстовое «что планировщик из этого делает». Адаптация по-прежнему ограничена
статистикой секторов (`best_bearing` по kills/hits): новых всеведущих данных и усиления
характеристик нет.
Форматы этапа 1 не менялись: intel оставался рантаймом (save хранил Layout, replay — траектории);
durable-очередь появилась на этапе 2, ниже. Измерения до/после на одних seed: `docs/measurements/issue-127-enemy-picture-baseline.json`
(0b645d77e) и `issue-127-enemy-picture-result.json` (эта ветка), bench — `cargo run --release --example intel_bench`.
big-smart и logistics побайтово совпали с базой; ew-adaptive изменился (kills 62→59/61→59/61→56,
hits 3→7/5→7/7→8, потери ЗРК 1→3/4→3/4→4) — фиксируется как факт перехода на честную картину,
балансные параметры не трогали. Регрессии: метаморфные `hidden_changes_do_not_move_the_picture_or_its_decisions`,
`a_new_observation_is_what_updates_the_picture`, `launcher_only_is_blind_in_the_picture_without_a_donor`
(донор любой роли; разрыв связи наблюдённый/нет), `destruction_moves_the_picture_only_when_watched`,
`confidence_is_a_function_of_age_alone`, `enemy_picture_report_describes_observation_and_belief`,
`an_impact_watches_the_kill_and_updates_only_the_picture` (BSA end-to-end), обновлённые SEAD/#4/#21/#122
и обе регрессии очереди. Остаток #127 после этапа 1: durable save queue, structured intent, GUI.
### #127, этап 2: structured intent, durable queue и объяснимость
**Намерение отделено от цели.** У дрона теперь два поля: `ew::Intent` — почему он летит туда — и
`ew::Aim` — юнит, когда цель выбрана, сколько раз менялась и уверенность контакта. `Intent`:
`Plan` (собственная цель плана: объект или юнит, выбранный при заказе), `Sead` (плановый удар по РЛС
из `radar_strikes`), `React` (реакция на раскрытие: станция показала себя уже в воздухе) и `Replace`
(картинка увидела гибель/забвение прежней цели). Случайный выбор цели (`choose_target`) больше не
смешивается с реакцией: при заказе налёта intent фиксируется, а `adapt` помечает свои решения явно.
Приоритет очереди — из намерения: Plan 3, Sead 2, React 1, Replace 0.
**Throttle.** `SWITCH_HOLD = 160` тиков (8 с): свежее раскрытие может сменить цель только после
выдержки; `SWITCH_CAP = 3` смены на дрон за жизнь; `ASSIGN_PER_TICK = 16` новых целей за адаптивный
тик и `ASSIGN_PER_CONTACT = 6` на один контакт за тик — массовый ретаргет растягивается на следующие
адаптивные тики, а не переписывает все маршруты сразу. Смена возможна, только если контакт показался
позже текущей цели (`tick > aim.since`), он не Doubtful, и он либо достовернее текущего, либо ближе
на `SWITCH_GAIN = 120` блоков: смена выбрасывает готовый маршрут и стоит планировщику нового, поэтому
маргинальная не делается. Замена убитой цели выдержку не ждёт (цели уже нет), но упирается в тот же
cap. В полёте, как и раньше, цель меняется только когда картинка её убила или забыла.
**Явные игровые реакции без скрытых данных.** Реакции читают только поля контакта, записанные каналом
наблюдения: выключенный радар остаётся в картине таким, каким его видели (эмиссия не фиксировалась —
собственный сенсор не верится), разделённая батарея читается как пуск без эмиссии (launcher-only,
без донора «слепа»), конечный БК наблюдается только как пуски (`Contact.launches`: счётчик увиденных
пусков; остаток магазина в картину не входит никогда), энергия/нагрев РЭБ — своё состояние станции,
а не раскрытие. Метаморфный тест `hidden_changes_do_not_move_the_picture_or_its_decisions` расширен:
скрытые перемещение, off, роли, режим, БК, урон, гибель и нагрев/замок/выключение РЭБ не двигают ни
картинку, ни цены, ни намерения/aims/очередь заданий. Повторное наблюдение двигает всё — как и должно.
**Неизвестная земля не бесплатна.** `raid::Relief` получил поле `unknown`; у плана умной волны оно
0 (поведение этапа 1 сохранено), у повторного планирования задания — `UNKNOWN_LAND = 6` сверх базовой
цены клетки 1. Задание, чья версия рельефа ничего не знает, планируется по полностью неизвестной
земле с той же ценой, а не «как по свободной»: маршрут держится размеченной части, если она есть.
Тест `unknown_land_is_not_free_in_a_replanned_route` сравнивает маршрут с ценой 0 и с ценой 6 на одной
сетке: бесплатный срезает через неразмеченное, платный идёт по размеченному.
**Durable queue: формат save.** `state_text` (автосейв) дописывает версионированную секцию
(`sim::durable`, формат `air 1`):
```
air 1 <такт> <номер следующего задания> <дронов> <в очереди> <заданий> <контактов> <версий рельефа>
airintel <12 kills> <12 hits>
airglobal <версия рельефа|->
airrelief <номер> <minX> <minZ> <клетка> <сторона> <RLE: u<n> | <высота>x<n> ...>
aircontact <id> <тип> <x> <y> <z> <такт наблюдения> <канал> <эмиссия|-> <гибель|-> <пусков>
airdrone <id> <тип> ... <полёт> <намерение> <юнит> <since> <смены> <уверенность> ... <маршрут: n x y z ...|->
airqueue <такт запуска> <то же тело дрона>
airjob <id> <дрон> <x> <y> <z> <юнит> <версия> <приоритет> <намерение> <рельеф|->
```
Секция пишется только автосейвом: сценарий — это стартовое состояние, его тело её не несёт
(`scenario_text` → `state_text_with(..., air = false)`). Старые saves без секции читаются как прежде
(пустое небо); старые сборки новые saves читают как Layout, игнорируя `air*` (Layout пропускает
неизвестные строки). Всё проверяется до применения: битая строка отказывает save целиком с номером
строки и полем, счётчики в заголовке сверяются с числом строк (обрезанный файл отвергается), чужая
строка внутри секции — тоже. Границы: 512 дронов, 512 точек маршрута, 4096 контактов, 8 версий
рельефа, 40 000 клеток; координаты пишутся до 0.01 блока (полёт этого не замечает), рельеф — RLE
целых высот. Секция дополнительно ограничена 900 КБ (хост разрешает 1 МиБ на одну запись): дрон,
который не влез, не пишется, и его задание тоже (восстановить его было бы нельзя). Измеренный размер секции в bench: 4.0–8.8 КБ для logistics/ew-adaptive и 61–62 КБ для
big-smart (38 дронов в воздухе).
**Что именно восстанавливается.** Дроны в воздухе (живые; падающие обломки — эффект, их нет),
очередь запуска с тактами, задания (`id`, дрон, цель, юнит, версия, приоритет, намерение, версия
рельефа), контакты картины (счётчики секторов, пуски), глобальный снимок рельефа и `job_next`.
Картина задания восстанавливается «на свою версию»: контакты, наблюдённые не позже версии, плюс
собственная цель задания (её последнее сохранённое наблюдение заменяет более позднее — иначе цель
исчезла бы из своей же картины). Устаревшие задания отменяются при загрузке (`prune_air`): дрон
исчез/погиб, цель уже другая, юнит наблюдённо уничтожен или забыт, дубль по дрону, версия старше
`JOB_TTL = 1200` тиков (60 с). Маршрут отменённого «по устареванию/дублю» задания сохраняется (он
ведёт к той же цели), отменённого из-за смены цели — очищается.
`apply_state` сначала проверяет Layout и секцию, затем применяет обе; секция заменяет воздушное
состояние, а не сливается с ним. `durable_mark` включает `air_mark` (число дронов/очереди/заданий/
контактов и `job_next`): автосейв берётся на запуске, потере, новом/завершённом задании и новом/забытом
контакте, а не каждый тик полёта. Пока налёт *планируется*, периодический save откладывается (план не
имеет durable-формы; поиск площадок ограничен `sites::SEARCH_TICKS = 400`); при смене мира пишется
только Layout. Replay по-прежнему хранит траектории: секция пишется и читается только для живого
`Sim`, записи не смешиваются с ней.
Остаток и ограничения: ракеты-перехватчики в воздухе, пусковые площадки (`sites`), промежуточный
план, статистика волны и состояние RNG не сохраняются — после загрузки перехваты начнутся заново,
очередь стартует без площадки (свободный слот), отчёт волны не придёт, а случайные броски идут от
нового генератора мира; сама воздушная обстановка (дроны, цели, задания, картина) восстанавливается
точно. GUI поверх отчёта не делался.
**Объяснимость.** `EnemyPictureReport` расширен без русского текста в core: у контакта — `launches`,
`aimed_by` (сколько дронов на него нацелено) и `pending_jobs`; добавлены `aims` (дрон, юнит, intent,
since, switches, confidence) и `pending` (id задания, дрон, юнит, точка, версия, приоритет, intent,
`relief_known`, `reason` словами: ждёт бюджета / ждёт бюджета, земля неизвестна и стоит дороже /
устарело), плюс `work_per_tick`. Тест `the_report_explains_aims_and_pending_jobs_in_english`
проверяет и ASCII-only диагностику.
**Измерения (baseline 8fc10c07a → эта ветка, `cargo run --release --example intel_bench`, seeds 1/7/42):**
`docs/measurements/issue-127-intent-queue-baseline.json` и `issue-127-intent-queue-result.json`.
big-smart: завершение у всех, launched 38, kills 38, hits 0, потери 0 — как в базе; ticks 1716→1676
(seed 1) и 1542/1433 без изменений, fired 49→60, 48→68, 49→71 (больше пусков ПВО). logistics: все
поля совпали (27 запусков, 11/12/12 сбито, 8/7/8 прорвалось, 18 ракет, 0 потерь). ew-adaptive:
kills 59→58, 59→58, 56→63; hits 7→7, 7→9, 8→3; потери ЗРК 3→3, 3→4, 4→2; ticks 8084→7146, 8193→7650,
7916→7243; fired 69→76, 81→98, 69→82. Это следствие throttle назначений и приоритетной очереди, а не
подкрутки баланса: параметры ПВО/дронов не менялись, числа фиксируются как факт. В result-файле есть
новые поля (`retargets_max`, `air_bytes`, `switches_max`, `intents`), у baseline их нет.
**Регрессии этапа 2.** Core: `the_plan_records_sead_separately_from_its_objective`,
`assignments_are_throttled_per_tick_and_per_contact`, `a_fresh_disclosure_switches_an_aim_only_after_the_hold`,
`a_watched_kill_replaces_the_aim_and_queues_a_lower_priority_route`,
`launched_rounds_are_observed_but_the_magazine_is_not`, `unknown_land_is_not_free_in_a_replanned_route`,
`the_route_queue_is_bounded_and_refuses_a_worthless_job`, `the_same_seed_chose_the_same_intents_and_jobs`,
`the_report_explains_aims_and_pending_jobs_in_english`, `the_air_state_round_trips_every_job_field`,
`a_pending_route_continues_after_a_save_and_a_load` (save/load посреди незавершённой очереди: та же
очередь, те же маршруты, обе кампании доводят задания, пустых маршрутов нет),
`stale_ghost_and_duplicate_jobs_are_cancelled`, `a_job_for_a_unit_the_picture_lost_is_cancelled_on_load`,
`a_damaged_air_section_is_refused_with_its_line_and_field`, `the_section_stays_inside_its_byte_bound`
(600 дронов с длинными маршрутами: секция ≤ 900 КБ, записанные задания принадлежат записанным дронам),
обновлённые массовые ретаргеты (40+ дронов:
прогресс на бюджетном тике, throttle назначений, у дрона, стартовавшего без маршрута, маршрут
появляется). Adapter: `the_air_section_of_a_save_is_written_and_read_by_the_adapter` (запись/чтение
секции, замена не слияние, старый save без секции, сценарий без воздуха).
## Что следующему агенту проверить в первую очередь
1. На Windows: обновление сабмодуля через `all`, сохранение/перезаход, рабочий цикл игры.
2. В GUI: полный холодный пуск крупным планом; карточка On/Off; маршрут ТЗМ по сложной местности;
разрушение стены одним взрывом и защита от того же взрыва по исходной геометрии.
3. Прослушать прекращение голоса двигателя при burnout и seek/экспорт вокруг этой границы.
4. Расширить баланс #120 на разные батареи, пределы дальности и классы целей; исходная CSV — ориентир.
4. Расширенная балансировка #120 (батареи/дальности/классы) записана в `measurements/issue-120-grid.csv`;
остаются прослушивание голоса мотора и платформенная приёмка.
5. Продолжить оставшиеся архитектурные #87/#88/#89/#91/#102 и художественный #115 по статусной таблице.
Это незавершённая платформенная/визуальная приёмка, а не отсутствие перечисленного выше кода.
+126
View File
@@ -0,0 +1,126 @@
# Продолжение 4 ноября: #115, #87, #91, #102, #96
Рабочая ветка `kimi-work`. Все issues оставлены открытыми. Работа выполнена Codex с GPT-6.1 Terra.
Движок опубликован в `horizon-airdef:airdef`, текущий pin
`57f8b2853c4443f7e3ff5701600cbb262b53118f`, API **29**.
## Изменения
- **#115:** authored-модели «Ланцета» и Х-101: сегментные стреловидные крылья,
детали носа/корпуса. Элементы 17→49 и 22→30 соответственно; игровые параметры не менялись.
`5366988`, `cfae0c1`, `914f723`. [Кадры и ограничения](AIRCRAFT-MODELS.md).
`tools/model-preview` воспроизводит реальный `set-models`, `glow=false`; установленный
stone-template блок не подходит для оценки света динамической модели. Полосы яркости
на наклонных сегментах вынесены в [#123](https://gitea.maoniao.team/chexit/airdef/issues/123).
- **#87:** `375fdf2`, `cb73cb7`, `0c870c1`: типизированный `BatteryStatus`, отчёт кэша мира
и причины повреждений отделены от русского форматирования. Команда/карта/монитор используют
адаптеры `battery_view`, `world_view`, `why_view`. Порядок и тексты сохранены.
Это постепенное разделение: `CheckReason::Text`, сообщения `Out` и часть представления в ядре остаются.
- **#91:** `eea1b36`, `1553976`, `daa9ed7`: `catalog/content.json` — идентичности техники,
предметы и метаданные иконок; `catalog/sounds.json` — звуковые события, дальности и far-варианты.
`gen_catalog.py` создаёт Rust-константы, Python-регистрации читают тот же источник;
CI проверяет актуальность. Сохранены порядок позиционных сейвов, все 35 звуковых событий,
OGG и порядок общего RNG синтезатора. Числовые `DroneSpec`/`SamSpec` остаются типизированным
источником в Rust; полного переноса всех характеристик в JSON не было.
Продолжение переноса чисел — ниже.
- **#102:** `63aefc7`: `test-budgets` включает настоящий `--fuel-profile` и сохраняет
`measured_fuel.callbacks`, включая ошибки. Отсутствие запрошенных счётчиков запрещает success.
В движке `6230ec703`/`d8fa77b00` добавлены API28 point-lights-status и API29 sound-sources-status.
Свет: заявка → cache → обработка main-view HD списка; звук: заявка → фактический apply
source manager при live/offline output. Отдельные run/world/source epochs, clear/reload и
отсутствие output проверены настоящими Wasmtime-гостями. Это не обещание пикселя/слышимости.
`/airdef capabilities` показывает оба состояния (`c1a595b`).
`57f8b2853` также устраняет коллизию камер: texture targets, scheduler, HUD/canvas/corner и
main-view адресуются `(run_serial, local_id)`. Проверены два настоящих гостя с одинаковым ID,
поиск target и scheduler, компиляция клиента.
`efe017ffb`/`278f356aa` добавляют API30 `camera-status`: `prepared` — закодированный в target
кадр камеры или кадр мира с её main-view, причём milestone получает только тот запуск, чей выбор
экран реально использовал (чужой тот же local ID и чужая картинка его не готовят). `enabled` —
последний отмеченный кадр был кадром мира, не заголовком. Пустая `set-views` и смена мира
очищают заявку/выбор/готовность, reload начинает заново; главный вид теряет picture target до
нового кадра. Проверено настоящими Wasmtime-гостями. Итоговый engine `278f356aa` с AirDef API30
проверен и в запущенной игре на Metal/offscreen (Apple M5, чистый `HORIZON_HOME`, копии тестовых
миров): monitor даёт `ready` с нарисованной картинкой (по снимкам), film-main-view — `ready` с
main-view (на экране карточка подготовки фильма), пустая заявка
и смена мира — `not-requested` с новым поколением, после deploy+monitor камера снова готова;
команды и ограничения — в [ENGINE.md](ENGINE.md#gpu-приёмка-картинки-камер-metaloffscreen).
- **#96:** engine `e44ad82a9`: opt-in `audio::tests::export_moving_mass_raid` проводит
100 движущихся двигателей и 16 импульсных источников через настоящие `Audio::tick_acoustics`
и `film_mix`: эхо/реверб, камера, инвалидация и смена epoch, новый capture без старого хвоста.
Два 6-секундных прогона дают одинаковые float-сэмплы; ненулевая дорожка, finite/peak и reset
проверяются assertions. Сэмплы и геометрия синтетические, устройство звука не открывается.
Release на Apple M5: step+mix на 50 мс аудио — p50 **3.55 мс**, p95 **4.30 мс**, max **5.57 мс**.
[Отчёт и SHA дорожки](measurements/mass-acoustics-2026-11-04.json).
Это не замер полного игрового CPU/GPU, не Windows FPS и не готовый MP4.
## Продолжение #91: один источник чисел
`catalog/specs.json` теперь единственная копия числовых строк симуляции: 13 дронов
(`DroneKind::spec`), 9 ракет (включая `seeker`, звук пуска и голос мотора), 15 комплексов
(`SamKind::spec`, включая части моделей и именованные наборы), общие константы гравитации,
высоты раскрытия «Орешника», приводов и логистики. `tools/gen_catalog.py` генерирует
`airdef-mod/src/sim/specs_generated.rs` и `unit_specs_generated.rs`; `include!` встраивает их в
`mod.rs` и `units.rs`, поэтому мод и `airdef-core` компилируют одни и те же строки. Прежние
`match`-литералы удалены; `DroneKind::spec`, `MissileKind::spec`, `SamKind::spec` и их производные
(RCS, seeker, звуки, голос) читают сгенерированные константы.
`load_specs` проверяет схему, звуковые ссылки, совпадение набора kinds с `content.json`, ссылки на
именованные части и то, что каждая строка кем-то используется; `gen_catalog.py --check` уже в
CI-шаге «Проверка generated assets», поэтому расхождение JSON и Rust валит сборку.
Сверка перед переносом: JSON сравнивался с литералами `632061d` по всем полям. Голос P1-SUN —
тонкое место: фактически играет ранний возврат `flame == 0` в старом `voices.rs`
(`(DRONE_LANCET, 0.8, 1.6)`), а `P1sun => 1.7` в `match` недостижим. Первая версия сверки ошибочно
приняла недостижимую ветку за факт и поставила в JSON 1.7 — это меняло звук перехватчика; fixup
вернул 1.6 и добавил регрессию `missile_engine_voices_keep_their_played_values` (P1-SUN и M48N6).
После генерации строки сверены с прежними литералами поле-в-поле (включая части моделей и
именованные refs) — расхождений нет. Порядок raid/save, ключи `sam`/дронов, RNG и тексты не менялись.
Проверки этого этапа: `cargo test --release` ядра — **194 passed, 7 ignored** + **8 сценариев**;
адаптер — **64 unit**, **1 boundary**, **5 сценариев**; `gen_catalog.py --check`, `gen_models.py --check`,
тесты генераторов/звука/границ моделей; настоящий WASM `test-wasm` — **27 шагов**, 1 скрипт.
GUI/MP4 и варианты комплексов (разные ракеты/профили по батареям) в этот этап не входили.
## Проверки и продолжение
Объединённый core release: **193 unit**, 7 ignored, **8 сценариев**; адаптер: **64 unit**,
**1 boundary**, **5 сценариев**. Генераторы catalog/models, asset pipeline, sound references,
границы моделей и 6 тестов provenance/failure отчёта проверяются отдельно. Лёгкий WASM — 27 шагов.
Тяжёлый default fixture — 271 шаг с двумя принятыми налётами; его текущий отчёт пишет
`python tools/airdef.py test-budgets` в `.horizon-cache/wasm-budget-report.json`.
Чистый финальный прогон `56339b0` с API29 сохранён в
[api29-wasm-budget.json](measurements/api29-wasm-budget.json): tick max 106132646/300000000,
command max 1013387/1000000000, ошибок 0, build identity совпал.
Не завершены: субъективное прослушивание, настоящий MP4 с акустикой, полный 10-минутный
replay/export, расширенная модельная/ночная/FPS приёмка, визуальная/Windows-GPU приёмка
camera-ready картинки и полные query/voice/peak-memory бюджеты.
Старый допуск broadband RT60 35% не ужесточался до 15%.
Попытка живого MP4 в этом проходе не дала проверенного файла и за приёмку не считается;
изолированные процессы закрыты. Продолжать с текущего pin, не с временных пакетов агентов.
Обновление Windows прежнее: `git switch kimi-work`, `git pull --ff-only`,
`python tools/airdef.py all`, `python tools/airdef.py play`.
## Обновление #89 (4 ноября, после этого прохода)
Живой короткий MP4 получен и проверен на pin `57f8b2853` (API 29) на scratch `HORIZON_HOME`/мире:
h264 + AAC, отчёт мода совпадает с `ffprobe nb_frames`, отмена/ошибка SDK/ошибка энкодера/повторный
запуск проходят. Найден и исправлен дефект: выход в заголовок во время экспорта оставлял захват
записывать заголовок (запрос `sec=10` дал 3898 кадров); теперь показ завершается по кадровому хуку.
Подробности и проверенные ограничения — [HD-RENDERER](HD-RENDERER.md) (раздел про кинорежиссёра)
и [ENGINE](ENGINE.md) (раздел про захват). Очистка временных файлов при ошибке энкодера
исправлена в движке `73b9d3070`: лог удаляется, его последние строки входят в текст ошибки, а
готовый MP4 прежнего экспорта с тем же именем сохраняется. Акустика проверена отдельно в настоящем
MP4 (пары on/off одного повтора, статусы ready, диффузный wet-остаток в каменном дворе); чистый
хвост/RT60 и прослушивание остаются — [ACOUSTICS](ACOUSTICS.md). 10-минутный экспорт и Windows/Linux
по-прежнему не проверены.
## Обновление #123
Engine `45b43f00d`: dynamic block models используют геометрическую нормаль квада вместо осевого
`facing`; для вырожденных вершин сохранён прежний fallback. Unit-тест покрывает `±45°`, другие
наклоны, осевые и вырожденные квады. На реальном Lancet-инстансе через `set-models`, `glow=false`
и HD получены парные кадры до/после в одном мире и ракурсе, а также вид сверху и ночью; полосы
осевого освещения устранены. [Кадры и ограничения](AIRCRAFT-MODELS.md). Массовый FPS и полёт не
измерялись.
+67
View File
@@ -0,0 +1,67 @@
# Проверка DLSS SR на Windows / RTX
Это тестовая, а не релизная сборка #124. Она включает native DLSS Super Resolution через Vulkan и сохраняет обычный TAAU как fallback. Frame generation здесь нет; RTX 3060 его и не поддерживает.
## Быстрый старт
1. Один раз запусти обычный Horizon Launcher, чтобы он подготовил ресурсы Minecraft 26.3.
2. Распакуй `airdef-dlss-windows-x86_64.zip`. Не удаляй `nvngx_dlss.dll`: он должен остаться рядом с `horizon-client.exe`. Если Windows сообщает об отсутствии `MSVCP140.dll` или `VCRUNTIME140.dll`, поставь Microsoft Visual C++ Redistributable 2015–2022 x64.
3. Запусти **`test-dlss.bat --world "Имя мира"**. Скрипт сам включит мод, `HORIZON_DLSS=1` и GPU pass timing.
4. В игре выполни одну и ту же последовательность:
```text
/airdef shader hd
/airdef deploy radar_track
/airdef deploy s400
/airdef damage off
/airdef wave shahed 8 300
```
Подожди около 20 секунд, пока начнётся налёт. Для движущихся моделей подойдёт и `/airdef move 2`.
5. Посмотри на ракеты/технику, сделай скриншот и запиши FPS/кадр. Не включай `HORIZON_HD_DEBUG_MOTION` при измерении качества или FPS.
6. Выйди и запусти **`test-native.bat --world "Имя мира"`**. Он использует TAAU с тем же масштабом 2/3 и тем же GPU timing. Повтори ту же сцену, ракурс и скриншоты.
Для честного A/B используй один мир и одну позицию камеры. Если налёт уже закончился, запусти следующий `/airdef wave shahed 8 300`. Не меняй разрешение окна или HD-настройки между прогонами.
## Что подтверждает, что DLSS действительно включён
В `%APPDATA%\horizon\logs\latest.log` должна быть строка вроде:
```text
DLSS Super Resolution: [1280, 720] -> [1920, 1080]
```
Не должно быть `using native TAAU`, `FeatureNotSupported`, `no DLSS context` или `DLSS evaluation failed`. Само наличие повышенного FPS не считается подтверждением backend.
Скрипты включают `HORIZON_SHADER_PACK_TIMING=1`, поэтому в лог попадают GPU pass timings. Сравнивай не только средний FPS, но и микрофризы, дым, вспышки и движущиеся ракеты.
## Что прислать
- `%APPDATA%\horizon\logs\latest.log` после DLSS-прогона.
- Скриншоты одного ракурса с DLSS и native TAAU, желательно с движущейся техникой/ракетой и отдельно с дымом.
- Скриншот FPS/debug overlay обоих режимов или текстовые значения FPS.
- Если есть артефакты: кратко, что именно не так и меняется ли оно при движении камеры.
- Сохранения миров присылать не нужно.
## Если игра не запускается
- Сначала проверь, что `nvngx_dlss.dll` лежит рядом с `horizon-client.exe` и ресурсы подготовлены лаунчером.
- При ошибке про Vulkan/NGX пришли `latest.log`: там должна быть конкретная причина. Не подменяй её догадкой про драйвер.
- При `FeatureNotSupported` или другом сбое игра должна продолжить работу через native TAAU; это будет видно в логе. Такой запуск не является успешным тестом DLSS.
- `test-native.bat` нужен только для сравнения; он не включает DLSS.
## Сборка самостоятельно вместо готового архива
Нужны Visual Studio Build Tools с C++, Rust, clang, Vulkan SDK и NVIDIA DLSS SDK v310.9.1. Ветка — `kimi-work`.
```powershell
git clone --branch kimi-work https://gitea.maoniao.team/chexit/airdef.git
cd airdef
rustup target add x86_64-pc-windows-msvc wasm32-unknown-unknown
$env:DLSS_SDK = "C:\path\to\DLSS"
$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/кадрами.
+108 -3
View File
@@ -63,7 +63,9 @@ runtime закреплённого движка. Используется вре
## Акустика и владение захватом (API 27)
Текущий pin: `f95f03c08ec2916a0e5bd3b2d4a2a790e7937b47` (API 27). Новые
Текущий pin: `2bcce642362ab5d3f04de193e390d8293cd1bf30` (API 31; `render.project` — проекция
мировых точек через камеру последнего отрисованного кадра, #132; ниже — staging, cascades,
previous-frame motion и feature-gated DLSS SR backend #124, API 30). Акустические
`render.acoustics-status` и `render.capture-owner-status` возвращают поколение,
`available`, `enabled`, `request-accepted`, `prepared` и причину. В игре всё это показывает
`/airdef capabilities`. Отсутствие запроса, выключение, ожидание backend и ошибка различаются.
@@ -81,6 +83,19 @@ AirDef не принимает чужие Recording/Done за свой эксп
сбрасывает готовность. Уже переданный writer файл на Encoding может всё же завершиться:
это запрос отмены, не гарантия удаления файла.
Проверено на реальном экспорте 4 ноября (pin `57f8b2853`; очистка ошибки в `73b9d3070`):
- Смена мира доходит до движка только через снимок мода (`set_snapshot`). На экране заголовка тики
не вызываются, поэтому мод без хука `frame` не сообщает о закрытии мира, и захват продолжает
писать заголовок. AirDef теперь просит `frame` и завершает показ по `game.world-id = none`.
- При ошибке энкодера временные файлы этого захвата (`<имя>.video.mp4`, `<имя>.audio.raw`,
`<имя>.ffmpeg.log`) удаляются, а последние строки лога переносятся в текст ошибки: ссылки на
уже удалённый лог больше нет. Кодировщик всегда пишет `<имя>.video.mp4`, а `<имя>.mp4`
появляется только после успешного mux или переименования, поэтому неудачный, отменённый или
беззвучный захват не перезаписывает и не удаляет готовый фильм прежнего экспорта с тем же
именем. Исправлено в `73b9d307048fc44d7f21fa3c829fc5a855d144a6` (`game/film.rs`), проверено
реальной ошибкой ffmpeg и контрольным MP4.
## Отдельный тяжёлый WASM tier
```sh
@@ -108,6 +123,13 @@ GPU не имитируется. Проверяются два принятых
frame hook; эти вызовы не являются нагрузкой на GPU или измерением 10M frame fuel мода.
Точный отчёт: [flat-world budget](measurements/flat-wasm-raid-budget.json).
С 4 ноября (#122) fixture расширен хвостом умных приказов через UI-путь: 4 РЭБ, `airdef preset 1`
(та же `apply()`, что у кнопки готового состава) и два `airdef raid` — это та же функция
`launch_wave`, что у кнопки ПУСК (`ui_select`), с боевым журналом разведки и EW; оба приказа
приняты (`expect.chat = []`), итого 4 принятых приказа, финальный `/stats` закреплён строкой.
Прогон исправления #122: 283 шага, 3302 tick; max fuel tick 182413686/300M, command 6939810/1e9,
ошибок 0. Отчёт: [flat-world budget](measurements/flat-wasm-raid-budget.json).
Fixture копируется из тех же байтов, чей SHA записан до сборки. Проверенные 2 принятия и точка
184/2102 заносятся только после success и совпадения `BUDGET_ASSERTED_SHA256` с точной версией файла.
После изменения fixture нужно повторно проверить её и обновить SHA/метаданные; простой список
@@ -123,16 +145,90 @@ API/WIT/артефакт, проверку build identity, сценарий, Was
Отсутствие запрошенных счётчиков делает проверку неуспешной, даже если сценарий завершился.
Это не время host/GPU и не peak memory; невызывавшиеся callbacks, включая init до включения профиля,
не получают выдуманного нуля. Первый прогон: tick 2102 вызова, max 106132646/300000000;
command 69 вызовов, max 1013370/1000000000; ошибок нет.
command 69 вызовов, max 1013370/1000000000; ошибок нет. Прогон исправления #122 (283 шага,
включая два умных UI-приказа): tick 3302 вызова, max 182413686/300M; command 79 вызовов,
max 6939810/1e9; ошибок нет.
Исторический отчёт без измерения fuel:
[API27 budget report с поправкой покрытия](measurements/api27-wasm-budget.json).
Актуальный чистый API29-прогон с измерением:
[271 шаг, fuel и build identity](measurements/api29-wasm-budget.json).
Актуальный прогон с умными UI-приказами #122 и build identity:
[flat-world budget](measurements/flat-wasm-raid-budget.json).
Проверены реальный WASM guest с переходами состояний/владельца/мира, сборка клиента и два коротких
offscreen-профиля Metal. При `HORIZON_ACOUSTICS=1` + `HORIZON_NO_AUDIO=1` в игре получено
enabled/request=true, prepared=false, awaiting-backend; HD smoke переходит в ready после подготовки
основного кадра. Это не замер производительности и не прослушивание.
Остаток #102: аналогичные статусы света/камер/источников звука, полные query/voice/peak budgets,
API28/29 добавляют отдельные `point-lights-status` и `sound-sources-status`: свет подтверждается
после cache/main-view HD обработки, звук — после source-manager apply с live/offline output.
Заявки привязаны к запуску мода и поколению мира; звук также к source epoch. Clear/reload/выход
снимают подтверждение. Это не GPU fence, загрузка сэмпла, наличие голоса или слышимость.
Камеры и их targets изолированы по `(run_serial, local_id)` вместо глобального ID.
API30 добавляет `camera-status` для камер `set-views` вызывающего запуска: доступность API,
включение пути картинок в последнем отмеченном кадре, принятие заявки поколения и поштучная
готовность каждой камеры. `prepared` означает, что рендерер закодировал кадр камеры в её
texture target, либо кадр мира отрендерен с неё как main-view **этого** запуска: если одинаковый
local ID выбрали два мода, экран использует выбор первого, и milestone получает только он; чужая
картинка с тем же ID чужую камеру не готовит. `enabled` — последний отмеченный кадр был кадром
мира (не заголовок/загрузка). Это не регистрация target и не GPU fence: видимый пиксель,
представление кадра и обход ротации per-frame бюджета не гарантируются. Пустая `set-views`
снимает заявку и готовность; смена мира очищает заявку, выбор main-view и готовность (камеры
другого мира не рисуются), перезагрузка мода начинает заново, а повторная отправка и камера,
отданная в main-view, ждут нового кадра (у такой камеры нет своего picture target).
Проверено двумя настоящими Wasmtime-гостями с одинаковым local ID, пустой заявкой, сменой мира
и reload. `/airdef capabilities` показывает строку камер.
### GPU-приёмка картинки камер (Metal/offscreen)
Итоговый engine `278f356aa` с AirDef API30 проверен в запущенной игре, а не только в песочнице:
macOS, Apple M5 (Metal, IntegratedGpu), `--offscreen`, `HORIZON_NO_AUDIO=1`, чистый
`HORIZON_HOME=/tmp/airdef-camera-accept` и копии тестовых миров из scratch-папки прежних прогонов
(`AirDefenseLab`, `Polygon`), ресурсы лаунчера v0.2.91. `.hmod` — из этого дерева
(`python3 tools/airdef.py mod`, API30), не из основного дерева.
```
tools/airdef.py install # HORIZON_HOME=<scratch>
horizon-ctl --socket $H/ctl.sock launch --game horizon/target/fast/horizon-client \
--world AirDefenseLab --creative --offscreen --wait --resources <26.3>
# мод-команды клиентские: ctl command/chat уходят в консоль сервера, поэтому — через поле чата
horizon-ctl key t tap; horizon-ctl type "/airdef capabilities"; horizon-ctl key enter tap
horizon-ctl screenshot <png>
```
Наблюдения (строки `/airdef capabilities`, `поколение` = generation):
| Когда | Камеры |
| --- | --- |
| камер нет | `API=true, включено=true, запрос=false, подготовлено=false, поколение=1, not-requested, main=нет, []` |
| `/airdef deploy s400` + `/airdef monitor` | `... запрос=true, подготовлено=true, поколение=1, ready, main=нет, [32:ready]` |
| `/airdef monitor` (пустая заявка) | `... запрос=false, ... not-requested, main=нет, []` |
| `/airdef replay film best` | `... main=1996488705, [1996488705:ready]`, затем `main=1996488707` на следующем плане |
| другой мир (AirDefenseLab → Polygon) | `поколение=2, запрос=false, ... not-requested, main=нет, []` |
| там же deploy+monitor | `поколение=2, запрос=true, подготовлено=true, ready, [32:ready]` |
Снимки подтверждают, что `prepared` — нарисованная картинка, а не регистрация (число различных
цветов, выборка каждого 6-го пикселя): при взгляде в небо (кадр однородный) включение монитора
добавляло панель и picture-область — 477→4867 цветов на кадре; в том же мире A/B
«монитор выключен/включён» в области панели: 199→2080 цветов,
доля тёмной панели 1.2%→48.7%, а в области картинки 110→1771 цветов с доминирующим небом (рисуется
сцена с камеры С-400, а не плоская заглушка «НЕТ СВЯЗИ»). В film-режиме экран показывал карточку
«Готовлю кадры…» (фильм готовит планы), при этом main-view milestone был `ready` — это API-отметка
и отрисовка кадров рендерером, не проверка пикселей фильма.
`title → тот же мир` не меняет поколение: заявка и milestone сохраняются (смена поколения — это
смена мира), а `enabled` сбрасывается кадром заголовка (note с `world=false`), поэтому `ready`
требует нового кадра мира после возврата; он и наступает (наблюдалось). 8 из 8 запросов при
работающем мониторе дали `ready`. `set_views`/`set_main_view` вызываются модом каждый tick, то есть каждый
tick начинает ожидание нового кадра: выборка между tick и note может честно показать
`awaiting-frame` по порядку вызовов — это не flicker, а порядок tick → render → note.
Остаток этой приёмки: визуальная оценка человеком, Windows/другие GPU, два запуска с одинаковым
local ID на GPU (покрыто Wasmtime-гостями), reload мода на GPU (покрыт host-тестом), fence/представление
кадров не проверялись.
Остаток #102: полные query/voice/peak budgets,
GPU/готовый MP4 и платформенная приёмка. Эти результаты текущими тестами не объявляются выполненными.
## Измеренный fuel и массовые взрывы
@@ -150,3 +246,12 @@ GPU/готовый MP4 и платформенная приёмка. Эти ре
3602 тика прошли, max tick fuel = 135273690/300M, failures=0. Лимиты не менялись.
Диагностический гость содержит только временный способ запуска точного меню-состава;
это не исходный пользовательский Windows-сеанс. [Данные и воспроизведение](RAID-STABILITY.md).
С профилем воспроизведён и второй класс — остановка в **событии UI** (не тике) на втором
крупном приказе: переснимок `known_units` на каждом дроне приказа давал `дроны × журнал ×
группировка` за одно событие, 1e9 исчерпаны ровно (max command fuel 1000000000/1e9,
failures=1; состояние: 13172 записей журнала, 144 известных живых комплекса). Исправление
(#122, одним снимком на приказ и O(журнал+группировка) за проход) доводит тот же сценарий
до max command fuel 32946177/1e9, failures=0, `/stats` на тике 2602 совпал побайтово.
Это гостевые инструкции, не прирост FPS; приёмка Windows-сеанса внешняя.
[Данные и воспроизведение](RAID-STABILITY.md).
+6
View File
@@ -66,3 +66,9 @@
`ground-unload` у склада выгружает одну RM48U сразу; вдали резервирует её и вызывает ТЗМ для
вывоза. `ground-cancel` отменяет ещё ожидающую доставку/вывоз. Уже забранная ракета находится
в ТЗМ и продолжает путь на склад; команда не телепортирует её обратно в ПУ.
Возврат имеет приоритет, только пока он выполним: ПУ исправна и развёрнута, маршрут доступен,
ракету ещё не забирает другая ТЗМ, а у склада есть место. Заявка при этом сохраняется, но
невыполнимый вывоз не блокирует ТЗМ: свободная машина исполняет независимые заявки на доставку
RM48U, а как только вывоз снова становится выполнимым, он встаёт в приоритет. Проверено
регрессиями #128, включая консервацию боеприпасов и save-restore посреди маршрута.
+83 -6
View File
@@ -58,8 +58,12 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
возвращается. Рисуются секции террейна в коробке дальнего каскада (`hd_shadow_visible`) и сущности-тенеотбрасыватели
(`shadow_casters`: без оверлеев 4/9/10/40 — 40 это светящиеся модели мода).
2. **G-буфер** (свой depth): albedo `Rgba8Unorm` (a = эмиссия), нормаль `Rgba16Float` (мировая, из `dpdx/dpdy`),
уровни света `Rgba8Unorm` (x = небо, y = блоки — сырые координаты лайтмапа /240). Террейн + дальние LOD-тайлы +
сущности. Полупрозрачное в G-буфер **не** попадает (идёт ванильным путём); вода — отдельный путь, см. п. 3 и «Вода».
уровни света `Rgba8Unorm` (x = небо, y = блоки — сырые координаты лайтмапа /240), motion `Rg16Float`
(current→previous в render-пикселях, обе проекции с jitter). Террейн + дальние LOD-тайлы + сущности.
Terrain/ванильные сущности пишут camera/static motion; `motion_models_pass` перезаписывает mod-модели
previous-frame transforms с read-only depth и тем же alpha cutout (`7a73e8d26`). Ветер остаётся camera-only.
`HORIZON_HD_DEBUG_MOTION=1` показывает R/G displacement и validity вместо обычного TAA-кадра.
Полупрозрачное в G-буфер **не** попадает (идёт ванильным путём); вода — отдельный путь, см. п. 3 и «Вода».
3. **Вода** (`water_pass`, только если на экране есть полупрозрачные секции, нет `frame.underwater` и не `HORIZON_HD_WATER=0`):
те же секции ещё раз с `fs_water` (terrain.wgsl), который отбрасывает всё, кроме слоёв спрайтов `water_still`/`water_flow`
(номера слоёв передаются в `Renderer::new` из `sprite_layers` и ставятся override-константами `WATER_STILL/WATER_FLOW`; стекло,
@@ -86,7 +90,9 @@ cd .. && rm -f horizon-patches/*.patch && git -C horizon format-patch -q $(cat H
5. **Пост-проход мода** `lit` → `fx` (`effects.wgsl`: взрывы, дым, вспышки, свечение; при HD его собственная
«подсветка огнём» выключена — свет даёт HD).
6. **TAA** — после пост-прохода мода (`fx`, либо `lit` без него), до bloom: история пинг-понгом, в альфе истории —
дистанция для отбраковки дизокклюзии; телепорт > 64 блоков сбрасывает историю. Джиттер добавляется к
дистанция для отбраковки дизокклюзии; телепорт > 64 блоков сбрасывает историю. Если world/G-buffer depth
совпадают, history UV = current UV + motion/render_size; вода, прозрачность и небо используют прежний
depth/camera fallback. Джиттер добавляется к
`view_projection` только при HD (публичная матрица без джиттера); рука и HUD рисуются после tonemap и не дрожат.
**TAAU**: если мир меньше окна (`HORIZON_HD_SCALE=0.67`), тот же проход (`fs_taau`, в таймингах `hd taau`) восстанавливает
полное разрешение. История, bloom и tonemap — в разрешении окна. Для каждого пикселя выхода берётся 3×3 выборки мира
@@ -225,6 +231,7 @@ 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 не проверялись) | в рабочем дереве форка |
| #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) | готово | в рабочем дереве форка |
| #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/` |
| Облака в воде, перистые, туман по рельефу, лучи, тень облаков при низком солнце, дальний дым (768 блоков) | готово, в рабочем дереве форка; тайминги не сняты чисто | не закоммичено |
| Материалы и блики (план 5): G-буфер `levels.zw` = шероховатость, металличность; GGX-блик солнца с Френелем и отражение неба (`sky_along`/`atmosphere_sky`) в `shade_surface`; мокрые поверхности и лужи в дождь (`HdFrame.surface`); `HORIZON_HD_SPECULAR=0` — выкл. | готово | в рабочем дереве форка |
@@ -245,8 +252,14 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
TAA-проход восстанавливает полное разрешение: история в полном разрешении, текущий кадр семплируется с учётом
джиттера (Catmull-Rom/Lanczos-веса по субпиксельной позиции), клиппинг окрестности как в TAA. Настройка
масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно
выше. Альтернатива на Mac — MetalFX через wgpu-hal (нативный код, только Metal) — отдельной опцией потом. DLSS
нереален для нашей цели (только NVIDIA через Streamline, нет в wgpu).
выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature
и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit:
world+linearize → NGX → delinearize; native TAAU остаётся fallback. По умолчанию DLSS рендерит world 2/3,
`HORIZON_HD_SCALE` переопределяет это. Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и
`--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build`
на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен.
A/B инструкция — `docs/DLSS-TESTING.md`.
Ванильные сущности/ветер остаются camera-only. MetalFX — отдельный Metal backend, FG отдельно.
2. **Вода** — СДЕЛАНО (патч 19, см. «Вода» ниже). Исходное ТЗ: отдельный G-буфер-путь для воды (маска + нормаль с анимированными волнами), SSR (трассировка по
глубине, откат на небо/туман), преломление (смещение по нормали), затухание по глубине воды (цвет биома),
блики солнца (GGX-подобный), френель. Подводный вид не ломать (`frame.underwater`).
@@ -351,6 +364,36 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
- Мод в повторе берёт взрывы из записи (`record::replay_blasts`, чистая функция времени), время идёт по часам повтора (`params[255].x` — доля частичного тика, которую эффекты не используют при паузе/замедлении).
- #51: на перехвате слои звука (`cinema.rs`), свет-«удар» (белая вспышка в HD-освещении, радиус до 256), пик экспозиции/bloom (`set-lighting`), в `effects.wgsl` широкое гало, подсветка неба/облаков и яркое кольцо ударной волны на экране.
## Retained-геометрия моделей мода (#126, этап 1)
- **Что изменилось.** `game/mod_models.rs`: грани модели резолвятся против атласа один раз на
generation пака (`MeshCache` по `BlockStateId`; generation — `Arc<RenderAssets>` текущего пака,
сравнение `ptr_eq`, клон удерживает адрес от переиспользования): прямоугольник спрайта,
model-space квад и нормаль (`block_model_normal`), emission и special-материал квада (40/41/42)
по центру UV. Кадр только применяет трансформ инстанса: позиции — `m.transform_point3`,
нормаль — один inverse-transpose на инстанс (не на грань), свет — мировой свет позиции + emission.
Таблица special-материалов строится раз в generation, а не каждый кадр обходом всего атласа;
линейный поиск материала по квадам убран из кадра. HD motion-проход (#124) берёт previous-позиции
из тех же retained-граней с матрицей прошлого кадра — второй bake модели больше нет. Вершины
бит-в-бит совпадают с прежним покадровым bake (тест `retained_emit_matches_the_per_frame_bake`,
матрица трансформов × glow × свет × emission, включая motion).
- **Инвалидация.** Resource reload (`apply_staged_pack`) и выход из мира (`clear_entities`,
`leave_server`) сбрасывают кэш; generation-guard дополнительно ловит любую смену пака. Размер
кэша ограничен числом состояний моделей в паке, не числом инстансов и не временем.
- **Счётчики и span.** `stats`/`bench` control-сокета возвращают `mod_models`: frames, models,
quads, motion_quads, vertex_bytes, motion_bytes, mesh_builds, atlas_scans с момента сброса
(bench сбрасывает). Span `mod_models` внутри `entity_geometry` виден при `HORIZON_SPIKES`.
- **Замеры.** M5, Metal, 2560×1440 offscreen, HD, in-frame, Polygon: 14 батарей + 3 волны
(`shahed 40 900`, `kh101 16 1400`, `mix 24 700`), ~135 моделей/кадр, ~17.8 тыс. квадов/кадр.
`entity_geometry` CPU 5.71 → 1.57 мс avg (p95 8.7 → 2.2, p99 10.6 → 2.7), фаза prepare
23.5 → 7.05 мс; span `mod_models` 1.32 мс avg — чистые трансформы. Static-сцена (4 батареи,
TAA/wind/clouds/volfog выключены, время заморожено): пиксели identical (0 px > 20/255 при
сошедшемся LOD). Байты upload не менялись (~3.1 МБ/кадр вершин + ~4 МБ motion): этап убирает
CPU-bake, не объём upload. Полная таблица и методика — `docs/measurements/issue-126-first-stage/`.
- **Чем это не является.** Не GPU-instancing: вершины по-прежнему трансформируются на CPU и
загружаются каждый кадр. Per-instance буферы, GPU-интерполяция и indirect draws — следующий
этап направления A #126. Боевые правила, 20 Гц, API мода, DLSS/RT не тронуты; мод (WASM) тот же.
## Прожекторы: направленный свет и объёмный луч (#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`): координаты камеры, косинусы углов.
@@ -368,9 +411,43 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
- Мод-HUD (`set-hud`) теперь рисуется и при `set-main-view` (титры, леттербокс фильма); ванильный HUD по-прежнему скрыт.
- Режиссура: `airdef-mod/src/film.rs` (план по записи, варианты ракурсов, проверка рельефа по высотам `Ground::land_state`, ускорение/замедление времени).
### Проверенный жизненный цикл MP4 (4 ноября, pin `57f8b2853`, очистка ошибки энкодера — `73b9d3070`, API 29)
Реальный короткий экспорт на scratch `HORIZON_HOME`/мире (не на сохранениях игрока), Apple M5, Metal,
ffmpeg 9.0.1. `/airdef replay export` с записанного налёта (4 цели, 4 перехвата), 640×360:
- готовый файл: h264 + AAC 48 кГц stereo, длительность видео = длительность звука; звук не пустой
(mean −29.4 dB, max −18.0 dB); 2 с при 30 fps — 62 кадра, `sec=1` — 32, `noaudio` — 33 кадра без
звуковой дорожки, `sec=0.01` — 3 кадра; 1920×1080 `sec=1` — 32 кадра. Число кадров в отчёте мода
всегда совпадает с `ffprobe nb_frames`: очередь не теряет кадры на остановке.
- 2–3 кадра сверх `sec` — это кадры, уже находившиеся в полёте на момент остановки (движок их
дописывает); это не потеря хвоста. Отчёт и файл сходятся.
- отмена во время записи (`/airdef replay stop`): сообщение «Экспорт отменён», файла и процессов
ffmpeg не остаётся; сразу после отмены новый экспорт проходит.
- отказ SDK (`size=10000x10000`): сообщение об ошибке, захват не остаётся, следующий экспорт проходит.
- ошибка энкодера (подставной `HORIZON_FFMPEG`, отвечающий на `-encoders`, но падающий при записи):
«Экспорт не удался: … Broken pipe …: fake encoder failed: no such codec»; временных файлов и
процесса нет, а последние строки лога теперь в самом тексте ошибки (сам лог удалён). Готовый
`keep.mp4` прежнего экспорта с тем же именем остался байт-в-байт (sha256), как и беззвучный
`keepnone.mp4` после неудачного `noaudio`-экспорта с тем же именем. Движок `73b9d3070` всегда
пишет `<имя>.video.mp4`; `<имя>.mp4` появляется только после успешного mux/переименования.
Контрольный `ctrl` на итоговой сборке `73b9d3070` — h264 + AAC, 33 кадра, временных файлов нет;
`keep` (h264 + AAC, 32 кадра) и `keepnone` (только h264, 32 кадра) проверялись на той же правке.
- акустика в MP4: пары on/off одного повтора (кнопка мода) со статусами `Акустика … ready` и
`Захват … ready`; в открытом поле send реверба нулевой по построению, в каменном дворе ON тише и
глуше, а остаток после вычитания масштабированного сухого сигнала низкочастотный и
декоррелированный (wet-путь). Цифры, статусы и ограничения — [ACOUSTICS.md](ACOUSTICS.md).
- **выход в заголовок во время экспорта** (до исправления): игра перестаёт тикать на экране
заголовка, но продолжает кадры, поэтому захват писал заголовок; запрос `sec=10` дал 3898 кадров
(129.9 с), временные `video.mp4`/`audio.raw` и ffmpeg оставались, а после возврата в тот же мир
экспорт продолжался. Мод получает кадры и вне мира (`Mod::frame`), поэтому `Session::world_left`
завершает показ с `ExitCause::WorldChange` и одним `CancelCapture`: после исправления при выходе
в заголовок ffmpeg и временные файлы исчезают, повторный вход и следующий экспорт проходят.
Пропуск мира виден по `game.world-id = none`; тик мода вне мира не вызывается.
## Цветные тени, рябь, кино-пост: что знать преемнику
- **Цветные тени.** Ближний каскад (c = 0) рисуется `fs_shadow_near` (листва `MAT_LEAVES` отброшена), потом проход `hd shadow colour` (`Hd::shadow_tint_pass`, цель `Shadows::tint`, очистка в белое) рисует листву (`shadow_tint_leaves`, твёрдые квады, `SHADOW_SOLID`) и полупрозрачные квады секций (`shadow_tint_glass`, по отсортированным индексам; вода не рисуется) тем же `fs_shadow_tint`: rgb умножаются (blend `Dst*src`), альфа = `(расстояние от света − 320)/160` с blend Min — ближайший такой квад. Приёмник в `shadow_tint` (`light.wgsl`, привязка 22) окрашивается, если квад ближе к свету, чем он; 8 точек Vogel радиусом 0.4 блока размывают листву в «пятна». Дальний каскад по-прежнему рисует листву полностью (на границе 36 блоков шов: ближе листва светлее). Цвет не доходит до лучей тумана, воды и дальнего каскада. Цена: `hd shadow colour` 0.25–0.35 мс (Mac, малая сцена).
- **Цветные тени.** Ближний каскад (c = 0) рисуется `fs_shadow_near` (листва `MAT_LEAVES` отброшена), потом проход `hd shadow colour` (`Hd::shadow_tint_pass`, цель `Shadows::tint`, очистка в белое) рисует листву (`shadow_tint_leaves`, твёрдые квады, `SHADOW_SOLID`) и полупрозрачные квады секций (`shadow_tint_glass`, по отсортированным индексам; вода не рисуется) тем же `fs_shadow_tint`: rgb умножаются (blend `Dst*src`), альфа = `(расстояние от света − 320)/160` с blend Min — ближайший такой квад. Приёмник в `shadow_tint` (`light.wgsl`, привязка 22) окрашивается, если квад ближе к свету, чем он; 8 точек Vogel радиусом 0.4 блока размывают листву в «пятна». Дальний каскад по-прежнему рисует листву полностью; с `17382445a` near/far depth filters смешиваются на последних 6 блоках перед границей 36,8, а tint затухает по той же smoothstep — круглого шва нет. Цвет не доходит до лучей тумана, воды и дальнего каскада. Цена: `hd shadow colour` 0.25–0.35 мс (Mac, малая сцена).
- **Рябь.** `ripple_gradient` берёт часы воды (`water.y`, часы фильма): частоты — целые циклы на 600 с, сетка 160 клеток на 256 блоков, поэтому рисунок не прыгает на обороте. Гаснет по размеру пикселя, только под открытым небом (`nt.a`). Амплитуда 0.012 не подбиралась.
- **Кино-пост.** `Hd::film` между `taa` и `finish` (`HdSource::Film`), только при `film_quality()`; цели создаются при первом фильме. Motion blur — только от движения камеры (глубина + `prev_view_proj`, затвор 180°, мёртвая зона 1–2.5 px из-за джиттера; движущиеся объекты не размываются; нет после склейки/телепорта: `taa.w`). DoF — диск 24 отсчёта, фокус авто (гармоническое среднее 9 глубин у центра) или `HORIZON_HD_DOF_FOCUS`. Детерминизм: единственное время в шейдере — `water.y` (часы фильма) для шума. Проверять на реальном фильме `/airdef replay film`; `HORIZON_HD_FILM_QUALITY=1` принудительно включает качество фильма для проб. DoF в игре был слишком сильным и дорогим; параметры уменьшены без повторного снимка. Motion blur на снимке (поворот 40° за 1.5 с) не разобран.
- Из Photon (MIT) ничего нового не переносилось: THIRD_PARTY_PHOTON.md не менялся.
+29 -7
View File
@@ -1,18 +1,26 @@
# Состояние исходных 16 задач
Ветка `kimi-work`, 3 ноября 2026. Issues остаются открытыми по просьбе владельца.
Ветка `kimi-work`, 6 ноября 2026. Issues остаются открытыми по просьбе владельца.
«Реализовано» ниже означает проверенный объём кода, а не закрытие issue и не подтверждение всех платформ.
Новый проверенный объём: [продолжение пяти задач 4 ноября](CONTINUATION-2026-11-04.md).
#87: typed battery/world/damage diagnostics и адаптеры текста; #91: общий content/sound catalog
для Rust и Python; #102: измеренный fuel, API29 light/source milestones, API30 camera-status
и изоляция камер; #96: массовый deterministic offline capture; #115: authored Lancet/Х-101
и кадры инстансов.
Текущий engine pin — API31 (`render.project`, #132); старые номера/числа ниже описывают предыдущие этапы.
Проблема нормалей модели #123 исправлена в engine `45b43f00d`; парные HD-кадры и ночная проверка Lancet записаны в галерее.
| Issue | Реализовано | Что остаётся для полной приёмки |
|---|---|---|
| #72 | Upstream Horizon 0.2.97 объединён с форком; сохранена история; локальные тесты и Metal-полигон | Windows/Linux, native HDR, сравнительная производительность |
| #87 | Каноническое SDK-free ядро `airdef-core`, используется модом и сценариями | Дальнейшее отделение текстового/визуального вывода домена от адаптера |
| #88 | Типизированный журнал измеренных переходов; read-only Snapshot для Smoke/Shown; записанные пожары, позы, пуски и зажигание | Перевести оставшиеся model/audio adapters и режиссёра на общий снимок; замер полной 10-минутной записи |
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа | Полный игровой цикл MP4 с отменой/ошибкой энкодера и проверкой хвоста очереди |
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей | Единый источник всех чисел, звуков и Python-регистраций; проверка вариантов комплексов |
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа; выход в заголовок завершает показ одним cleanup (хук `frame`, `Session::world_left`); движок освобождает temp/лог ошибки энкодера и не трогает готовый MP4 | Реальный короткий MP4 проверен 4 ноября (звук/видео, отмена, ошибка SDK и энкодера, повторный запуск, совпадение кадров и хвоста очереди, сохранность прежнего MP4). Остаётся: 10-минутный экспорт; приёмка Windows/Linux |
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей; `catalog/specs.json` — единственный источник числовых строк, из него генерируются Rust-таблицы для мода и `airdef-core`, CI проверяет свежесть; первый типизированный slice вариантов комплексов: `catalog/content.json → variants` описывает существующие ключи развёртывания элементов батареи (`s400_launcher`…), вариант = `id/kind/mode/role/label` без нового баланса, таблица `catalog::VARIANTS` генерируется и потребляется меню/командами, ручные параллельные списки в `lib.rs`/`commands.rs` удалены | Профили боезапаса по вариантам (разные ракеты/боекомплекты по батареям) не заводились: обязательное условие — зафиксированный профиль и явная игровая абстракция (см. поправку ревью о PAC-3 в комментарии #91); далее полная игровая приёмка; каталог остаётся статичными данными, не динамическим ECS |
| #92 | Authored overrides, проверка ссылок/PNG/границ, manifest, безопасная транзакционная генерация; registry/texture/icon modules | Дальнейшее ручное улучшение контента относится к #115 |
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах | Прослушивание, игровой массовый звук/CPU, акустика реального MP4; точность RT60 пока по допуску 35%, не 15% |
| #102 | Pinned engine/API27, packer/build identity; smoke/acoustics/capture-owner milestones; fallback/владение; WASM26 и flat stress271 с двумя принятыми налётами и проверенными184 воздушными на тике2102; JSON provenance/failure tests; Metal/no-audio smoke; URL/Git-регрессия | Старое69-шаговое утверждение о перекрытии отозвано; статусы света/камер/sound sources, полные query/voice/peak budgets, GPU/готовый MP4 и Windows-приёмка остаются |
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах; настоящий MP4 с акустикой: пары on/off, статусы ready, окклюзия/поглощение и диффузный wet-остаток в замкнутой геометрии | Прослушивание, игровой массовый звук/CPU, чистый хвост/RT60 в MP4; точность RT60 пока по допуску 35%, не 15% |
| #102 | Pinned engine/API30, packer/build identity; smoke/acoustics/capture-owner/light/source/owner-scoped camera milestones; fallback/владение; WASM27 и flat stress271; измеренный callback fuel; JSON provenance/failure tests; Metal/no-audio smoke; URL/Git-регрессия; camera-ready по закодированному кадру с per-run/per-world сбросом; GPU-приёмка monitor/main-view на Metal/offscreen (Apple M5) | Старое69-шаговое утверждение о перекрытии отозвано; визуальная/Windows-GPU приёмка картинки камер, полные query/voice/peak budgets, GPU/готовый MP4 и Windows-приёмка остаются |
| #104 | Движок вынесен в `chexit/horizon-airdef`, ветка `airdef`; AirDef использует точный gitlink | Отдельная Windows-проверка миграции старого standalone checkout |
| #107 | ПУ оценивается по наблюдениям: обратный курс не выдаёт точную ПУ | Повторная игровая проверка сценариев с маневрирующими целями |
| #110 | Изменения чанков инвалидируют акустические снимки/кэш; включено в pin и проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
@@ -21,6 +29,9 @@
| #115 | Три пилота с кадрами до/после, спокойные материалы; authored-проход по боевым и вспомогательным машинам | Крупные планы и точность прототипов ещё промежуточные; остальные летательные аппараты/ракеты, анимации, дальние виды и FPS |
| #116 | Streaming не освобождает busy-guard работающего acoustic worker; проверено engine-тестами | Внешняя игровая приёмка на целевых машинах |
| #118 | Физический С-400/RM48U, четыре общие ячейки, конечные запасы; доставка и обратный вывоз ТЗМ, резерв/отмена, возврат снятой ПВО; обе фазы вывозного маршрута сохраняются; carrier/крышки/выброс/зажигание/разгон в записи; фантомное ПВО удалено | Визуальная приёмка пуска и маршрутов на сложном рельефе; другие носители не добавлены без подтверждённого профиля |
| #128 | Невыполнимый возврат RM48U (ПУ движется/повреждена, маршрут недоступен, заявку уже везёт другая ТЗМ, у склада нет места) больше не блокирует ТЗМ: заявка сохраняется, свободная ТЗМ исполняет независимые заявки на доставку; выполнимый возврат снова в приоритете; консервация боеприпасов и save-restore посреди маршрута покрыты регрессиями | Игровая приёмка маршрутов на сложном рельефе остаётся за #118 |
| #129 | Единые стадии пуска: выброс без мотора (`cold` 20/24 тика у С-400/С-500, 8 у IRIS-T/Тора), зажигание в текущей позиции, departure с плавным ростом тяги/темпа поворота, наведение только после `cold + boost`; рельсовые ракеты получили spool тяги без холодного выброса, P1-SUN — без струи; RM48U согласован на 20 тиков; live/replay/export читают записанное зажигание; `pk`, максимальные скорости и коллизии не менялись | Парные replay-MP4 до/после и кадры сняты на одном мире/seed/сценарии (Metal/offscreen); измеренный сдвиг первой вспышки 0,233 → 0,900 с. Остаётся человеческая визуальная оценка композиции, very-close план выброса; live-видео, Windows/Linux и живое прослушивание не проверялись |
| #134 | Три самостоятельных игровых профиля отдельных РЛС (`radar_search`, `radar_track`, `radar_height`) с устойчивыми ID, циклом/каналами/локальным поиском и разрешёнными продуктами измерения; `on/off` сохраняется, переключение роли на ходу отклоняется; встроенные РЛС комплексов сохраняют своё право на пуск. Сеть передаёт измерившую станцию, возраст и качество, но повторная пересылка не освежает измерение и не даёт права на пуск. Пуск требует собственного подтверждённого огневого трека (или внешней огневой РЛС для отдельной пусковой и дальнего пуска). Карта/монитор/`why` показывают профиль, источник, продукт, качество, каналы и причину отказа; старые сейвы мигрируют по роли, replay хранит профиль. Тесты: сценарий профилей по отдельности/парами/втроём, дублирование, каналы, off/повреждение/связь, relay, миграция и replay | Общий силуэт машины у трёх профилей (различаются поведение, подписи и статусы); публикация наблюдаемой роли РЛС в картине противника (#127) не расширена; визуальная приёмка на Windows/Linux и живые замеры совокупной картины не проводились |
Для #118 RM48U — явно условный Minecraft-профиль. Существование сочетания опирается на сообщение ведомства,
а игровые параметры не выдаются за реальные. `ground-stock` — команда подготовки sandbox-сценария,
@@ -38,9 +49,20 @@
| Issue | Реализовано | Границы и оставшаяся приёмка |
|---|---|---|
| #119 | Три read-only луча в известной геометрии ослабляют непрямой blast для корпуса/узлов/объектов; проёмы дают частичное воздействие; прямой контакт сохранён | Unknown/stale: прежний урон без защиты, нулевое ожидание; partial blocks считаются занятыми кубами; GUI-проверка разрушения укрытия ещё нужна |
| #120 | Конечное горение, powered/coast, сопротивление и снижение доступного манёвра, один остаточный pk по фактической скорости; swept-встреча; события burnout/energy loss; согласованное прекращение факела/дыма/звука | Игровой профиль, без аэродинамики и реальных параметров; сравнительная выборка 12 рейдов, расширенная балансировка и прослушивание остаются |
| #120 | Конечное горение, powered/coast, сопротивление и снижение доступного манёвра, один остаточный pk по фактической скорости; swept-встреча; события burnout/energy loss; согласованное прекращение факела/дыма/звука | Игровой профиль, без аэродинамики и реальных параметров; сравнительная выборка 12 рейдов и расширенная сетка 48 рейдов (6 вариантов × 8 seed, батареи/дальности/классы) записаны в measurements; без подтверждённого дефекта параметры не менялись; прослушивание остаётся |
| #121 | On/Off в команде и карте, save/replay; Off не создаёт own measurements и сохраняет сетевой приём; раскрытие работающего радара наблюдателем; SEAD использует last-known и возраст | Условный наблюдатель по расстоянию, без радиотехнической модели и ошибки пеленга; выбор на карте ещё не проверен в GUI |
| #122 | Воспроизведён tick fuel exhaustion на двух максимальных составах, HD; полный обход height-cache на каждом взрыве заменён удалением нужных ключей; тест эквивалентности и WASM421/3602 прошли, max135.3M/300M; callback diagnostics/profile | Требуется приёмка на Windows; без старого лога нельзя подтвердить ту же причину пользовательского сеанса; FPS/GPU не измерялись |
| #122 | Воспроизведены три класса: tick fuel exhaustion на двух максимальных составах, HD (полный обход height-cache на каждом взрыве заменён удалением нужных ключей; max135.3M/300M); остановка в UI event на втором крупном приказе (переснимок known_units на каждом дроне заменён одним снимком на приказ и O(журнал+группировка); max command 32.9M/1e9, `/stats` до/после совпал); OOM в `note_sams` (до: 384000 SamKey/27 MiB в одной полной записи 64 РЛС; после: бюджет 32768, адаптивное прореживание без остановки записи; WASM 24002 тика/64 РЛС/60 малых волн прошёл с прежним лимитом 64 MiB); нативные регрессии и callback diagnostics/profile | Требуется приёмка на Windows; без подтверждённого build identity нельзя утверждать ту же причину пользовательского сеанса; FPS/GPU не измерялись |
| #124 | Motion + object transforms + feature-gated DLSS SR: engine `ed751714e`; NGX+HDR bootstrap, долгоживущий SDK/context, display↔linear conversion и ordered submit; native TAAU fallback. Полный `cargo xwin build` на MSVC и `v0.4.0-dlss-rc1` с PE32+, `airdef.hmod`, `nvngx_dlss.dll`, notices и A/B launchers опубликованы; 24 HD + layout, mods/no-mods, обычный Metal кадр проверены | Runtime/качество/FPS на RTX/Vulkan не подтверждены; нужна приёмка по `docs/DLSS-TESTING.md`. Ванильные сущности/ветер camera-only; reactive/transparency, FSR3/MetalFX и FG отдельно |
| #130 | Первый небольшой backport: upstream `f7b77fbc8` перенесён как engine `94b572cd2`; oversized staging allocations округляются до степени двойки и переиспользуются, копируются только фактические байты; 3 upload/GPU readback-теста прошли на Metal | Полная миграция на Nightly не начата; VSync/pacing, дальний рельеф и другие кандидаты остаются; Windows/Vulkan и долгий игровой RSS-профиль не проверялись |
| #127 | Этапы 1–2. **Картина:** журнал раскрытий заменён картой контактов (`Intel.contacts`: последнее «пуск/излучение/глушение», место, время, метка эмиссии, наблюдённая гибель, счётчик увиденных пусков), уверенность — функция возраста (Confirmed/Probable/Doubtful, TTL 6000), угроза и цены читают только published-параметры и факты наблюдений (launcher-only без донора «слеп»), уничтожение учится только из BSA. **Structured intent:** `Intent` (Plan/Sead/React/Replace) и `Aim` (юнит, since, switches, confidence) отделены от random-выбора; throttle `SWITCH_HOLD=160`, `SWITCH_CAP=3`, `ASSIGN_PER_TICK=16`, `ASSIGN_PER_CONTACT=6`, цена смены `SWITCH_GAIN=120`; в полёте цель меняется только когда картинка её убила/забыла. **Durable queue:** автосейв пишет версионированную секцию `air 1` — дроны, очередь запуска, задания (id, дрон, цель, юнит, версия, приоритет, намерение, версия рельефа), контакты, RLE-рельеф; очередь ограничена 256, устаревшие/фантомные/дублирующие задания отменяются при загрузке (`JOB_TTL=1200`), картина задания восстанавливается на свою версию, старые saves читаются (пустое небо), сценарии воздух не несут, Live/Replay не смешиваются. **Неизвестная земля не бесплатна** (`Relief.unknown=6` у повторного плана). **Объяснимость:** `enemy_picture()` дополнен aims/pending reason/aimed_by/pending_jobs без русского текста в core. Метаморфные тесты скрытых изменений (включая нагрев/замок РЭБ), save/restore посреди незавершённой очереди, детерминизм seed, 40+ массовый ретаргет. Замеры: `docs/measurements/issue-127-intent-queue-{baseline,result}.json` | GUI поверх `enemy_picture()`, игровая приёмка сохранения налёта на Windows/Linux, оценка баланса ew-adaptive (kills 59→58/59→58/56→63, потери 3→3/3→4/4→2 — следствие throttle, параметры не менялись) |
| #135 | **Core (`9d8f3da57`):** умная волна высылает ограниченный бюджет невооружённых разведчиков (Gerbera, собственные id `0x3000_0000`, не тратят combat RNG волны и не входят в её replay); они физически проходят игровые зоны вокруг отмеченных целей и через `REPORT_DELAY` передают только область, публичную категорию, канал (пролёт/излучение/РЭБ/пуск), возраст и качество — без точной точки, `SamKind`, HP, боезапаса, сети и реального id. Сбитый до донесения разведчик ничего не передаёт; уже переданное остаётся и переживает налёты. Планировщик читает отметки наравне с контактами раскрытия и назначает по наблюдаемой роли/свежести/качеству (`Mark::priority`), скрытая станция не становится целью, старая сомнительная отметка уступает свежей скромной; бюджет назначений и исходные цели волны сохранены. Save/load хранит отметки, вылеты, ожидающие донесения и проверенные зоны. **UI/диагностика (этот коммит):** на карте сети разведчик — узнаваемый жёлтый ромб с подписью «разведчик», роль в панели выбора и легенда фильтра; в боевом HUD и на карте — понятная фаза вылета (разведка/донесение/завершение) только пока сеть держит разведчика; в sandbox-режиме `truth` — янтарная метка и счётчик отметок. Причина выбора показана в `/airdef recon` и на странице меню «Разведка противника (разбор)» (из «Повторы…»): отметки best-first с разбором `приоритет = свежесть×4 + качество×3 + роль` (`recon::priority_parts`, сверен тестом с `Mark::priority`) и дроны, нацеленные на отметку. Всеведущая картина противника в обычный HUD не выводится — только явный debug/разбор. Механика, модели и текстуры не менялись. Тесты: `priority_parts`-кросс-чек, `recon_view`, панель, дерево команд | Игровая/визуальная приёмка значка и фазы на Windows/Linux; приёмка разбора в GUI; баланс приоритетов по серии seed остаётся за core-приёмкой |
По #127 реализованы карта контактов, структурированное намерение с throttle и durable-очередь:
autosave хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому
незавершённый ретаргет продолжается после перезахода. Старые saves без секции `air` читаются как
прежде (пустое небо), сценарии воздушное состояние не несут, replay по-прежнему хранит траектории.
Ракеты-перехватчики, площадки запуска, промежуточный план, статистика волны и RNG не сохраняются —
это ограничение записано в handoff.
Точные коммиты, формат сохранения, тесты и порядок продолжения:
[CODEX-HANDOFF.md](CODEX-HANDOFF.md). Формальный open-статус не меняется после реализации.
+72 -3
View File
@@ -7,10 +7,79 @@
поэтому запись может сохраниться и без ручного копирования.
Задача: [#122](https://gitea.maoniao.team/chexit/airdef/issues/122).
**Воспроизведена и исправлена одна конкретная причина отключения при таком классе нагрузки.**
Без старого лога не утверждается, что Windows-сеанс имел именно её; GPU/FPS отдельно не измерялись.
**Воспроизведены и исправлены три конкретные причины отключения в этом классе нагрузки.**
Первая — тик и кэш высот (`1f28f83`, ниже). Вторая — событие UI и второй приказ
(`order_raid`, см. раздел «Второй налёт из UI: событие, не тик»). Третья — исчерпание
64 MiB линейной памяти WASM полными ключами поз техники в реплеях. GPU/FPS отдельно не измерялись.
## Найденная причина и фикс
## OOM при записи поз техники
Точный лог Windows: `rust_oom` ← `RawVec<SamKey>::grow_one` ← `Recording::note_sams` ←
`Sim::step` во время обычного `tick`, с оставшимся fuel. Это не повтор прежнего OutOfFuel.
До исправления нативная регрессия с 64 непрерывно вращающимися РЛС на полной записи 12000 тиков
создавала 384000 `SamKey`: 27 MiB только в этих ключах, без учёта ёмкости `Vec`, траекторий и
событий. Активная запись и три сохранённых реплея могли превысить лимит 64 MiB.
`Recording` теперь имеет общий бюджет 32768 ключей поз. При превышении старые ключи каждой
трассы прореживаются вдвое без потери первой и последней позы, освобождённая ёмкость возвращается,
а интервал следующих samples удваивается. Запись не обрывается: регрессия проверяет бюджет
длины и реально выделенной ёмкости, а также наличие свежей позы в конце окна. Для обычных
коротких записей частота не меняется; при нехватке памяти точность старого движения снижается.
Проверки: core release 233 + 8 сценариев (8 ignored), adapter 68 + 1 boundary + 5 сценариев;
настоящий WASM contract 30 шагов. Дополнительный flat-world WASM-стресс: 64 РЛС, 60 волн по
4 Shahed на 4000 блоках, 24002 тика и два полных окна записи, 185 шагов; max tick fuel
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
синтетический host без GPU и не приёмка Windows GUI.
## Второй налёт из UI: событие, не тик
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,
remaining Some(0))`; backtrace: `ew::Sim::known_units` ← `raid::Sim::order_raid` ←
`airdef::AirDef::launch_wave` ← `ui_select`. Прежний fix `1f28f83` — другой класс: тогда
мод останавливался в **тике** на 300M.
**Причина.** `order_raid` для каждого дрона заново вычислял снимок известных комплексов
`known_units()` (`choose_target`), а сам `known_units()` на каждую запись журнала разведки
пересканировал весь список комплексов и список уже принятых. Журнал держит каждый пуск,
каждое раскрытие РЭБ и каждую emitting-РЛС за последние 6000 тиков. Стоимость второго
большого приказа росла как `дроны × журнал × размер группировки` внутри одного UI-события.
**Воспроизведение** (настоящий WASM, измеренный fuel по callback, диагностический гость —
`trigger.patch` гоняет тот же обработчик `ui_select(BTN_LAUNCH)` → `launch_wave` →
`order_raid` с максимальным составом меню; метка callback — `command`, бюджет тот же 1e9):
разнесённая группировка 172 комплекса (40 кластеров × 4 тяжёлых + 12 РЭБ, игрок двигается
шагами сценария — стек в одной точке умирает от одной боеголовки и не воспроизводит),
первый налёт 111 дронов отбит, второй приказ на тике ~2600 при `revealed=13172`,
`known=144` живых. До fix: второй приказ исчерпывает ровно 1e9 и останавливает мод
(`before-trap.txt`); тот же приказ из 11 дронов в том же состоянии — 247805865
(`before-scaling.txt`). После fix тот же сценарий проходит целиком: max command fuel
32946177/1e9, max tick 236581288/300M, ошибок 0; `/stats` на тике 2602 совпал побайтово
до/после, включая счётчики мира.
**Фикс.** Один снимок `known_units` на весь приказ, передаётся в `radar_strikes` и
`choose_target`; сам `known_units` — один проход O(журнал + группировка) через множества;
`price_grid_on` переиспользует свой снимок. Семантика планирования не изменилась:
нативный тест сверяет новый снимок с прежним предикатом (дубликаты, погибшие, устаревшие,
чужие id, порядок «новые первыми»). Лимиты не менялись, HD/запись не отключались,
размер волны не ограничивался.
**Регрессии.** Нативные: эквивалентность снимка и «второй умный приказ с толстым журналом
принят и запущен». Закреплённые WASM: тяжёлый fixture расширен — два умных приказа через
функцию кнопки ПУСК (`airdef preset 1` + `airdef raid` — тот же `launch_wave`, что и у
`ui_select`) с РЭБ и боевым журналом, оба приняты (`expect.chat = []`), 4 принятых приказа
в отчёте; лёгкий контракт проверяет `preset` и отказ пустой волны. Данные и точный
сценарий: [summary.json](measurements/issue-122-ui-fuel/summary.json),
[trigger.patch](measurements/issue-122-ui-fuel/trigger.patch),
[до](measurements/issue-122-ui-fuel/scenario-before.toml),
[после](measurements/issue-122-ui-fuel/scenario-after.toml). Patch — только для
диагностического гостя, в мод не входит.
Приёмка конкретного Windows-сеанса остаётся внешней: нужны build identity и строки
`latest.log` вокруг остановки. Измерение fuel — не прирост FPS.
## Первая причина и фикс (тик, `1f28f83`)
Два максимальных состава меню (11 видов × 40, два принятых приказа), 64 ПВО, расстояние 300,
HD и grid, обслуживаемый плоский мир: tick 1835 исчерпал ровно 300M fuel и мод остановился.
+3 -1
View File
@@ -34,10 +34,12 @@
Команды:
- `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow).
- `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.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 --check` — только сравнить, выход 1 при различиях.
`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/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`.
## Архив: `legacy/`
+85
View File
@@ -0,0 +1,85 @@
{
"airdef": {
"diff_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"dirty": false,
"sha": "56339b076e3dad9c6825ddbc73fdfe6b9a2727bc"
},
"api_level": 29,
"artifact_sha256": "f3720d58e18210b2e962ae924306a18cbf12c28e033c2bf862ad6a1a0db462b6",
"build_identity": {
"checks": {
"airdef_diff_sha256": true,
"airdef_dirty": true,
"airdef_sha": true,
"artifact_sha256": true,
"engine_identity": true,
"engine_pin": true,
"wit_sha256": true
},
"matches": true,
"path": "/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/build-identity.json"
},
"command": "test-budgets",
"engine": {
"identity": "57f8b2853c4443f7e3ff5701600cbb262b53118f",
"pin": "57f8b2853c4443f7e3ff5701600cbb262b53118f"
},
"exit_code": 0,
"measured_fuel": {
"available": true,
"callbacks": [
{
"budget": 1000000000,
"callback": "command",
"calls": 69,
"failures": 0,
"max_used": 1013387,
"mod": "airdef"
},
{
"budget": 300000000,
"callback": "tick",
"calls": 2102,
"failures": 0,
"max_used": 106132646,
"mod": "airdef"
}
],
"scope": "guest callback fuel; excludes host CPU, memory and GPU time"
},
"output": " Compiling horizon-mods v0.1.0 (/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/crates/horizon-mods)\n Compiling cargo-horizon-mod v0.1.0 (/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/crates/cargo-horizon-mod)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.70s\n Running `/Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod /Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/airdef.hmod --fuel-profile budget`\nrunning 1 scripts against /Users/chexit/Documents/ChatGPT/reviewer-horizon/airdef-kimi-work/airdef-mod/target/horizon-mod/airdef.hmod\nfuel airdef command: calls=69 max=1013387 budget=1000000000 failures=0\nfuel airdef tick: calls=2102 max=106132646 budget=300000000 failures=0\ntest tests/wasm_budget.toml ... ok (271 steps)\ntest result: ok. 1 passed\n",
"runtime_limits": {
"fuel_per_call": {
"event": 1000000000,
"frame": 10000000,
"init": 2000000000,
"tick": 300000000
},
"memory_bytes": 67108864,
"metering": "source_configured",
"source": "horizon/crates/horizon-mods/src/runtime.rs",
"wasmtime_component_model": true,
"wasmtime_fuel_metering": true
},
"scenario": "tests/budgets/wasm_flat_budget.toml",
"scenario_counts": {
"accepted_raids_asserted": 2,
"air_defense_units": 64,
"frames": 2052,
"layout_unit_limit": 2000,
"peak_airborne_observed": null,
"raid_requests": 2,
"raid_units_requested": 80,
"scripts": 1,
"snapshot_airborne_asserted": 184,
"snapshot_tick": 2102,
"steps": 271,
"ticks": 2102
},
"scenario_render_world": "flat at y=64",
"scenario_sha256": "bcc0359289ab20ab3de608bcc130f72d2cf88f9f6fbc470d7b6846e9db5d11df",
"schema": 1,
"status": "passed",
"wasmtime_version": "48.0.7",
"wit_sha256": "dded023a150a5f916bc5d935b7f891806728e0118eb7107ad0551d2aad8c70a5"
}
+47 -17
View File
@@ -1,11 +1,11 @@
{
"airdef": {
"diff_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"dirty": false,
"sha": "293236490b567866f7468a5bee5d61b0dcf8086d"
"diff_sha256": "143fbab5f1fd60981df9ef8ef3081b08a4102507f2588c6942924a7325b5139b",
"dirty": true,
"sha": "e6a70004406b34ea17884875ce236a5fb4b849e4"
},
"api_level": 27,
"artifact_sha256": "cb52fa5fd6beb266c63f2a5f2aa50553c24bc435a212c76142cc1bd228fd0aa6",
"api_level": 29,
"artifact_sha256": "c4ef7d759524eb053ccd55f0eccdcb49c91954201eb4e0ad923ee9b2828efc4e",
"build_identity": {
"checks": {
"airdef_diff_sha256": true,
@@ -17,15 +17,45 @@
"wit_sha256": true
},
"matches": true,
"path": "airdef-mod/target/horizon-mod/build-identity.json"
"path": "/private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/build-identity.json"
},
"command": "test-budgets",
"engine": {
"identity": "ed7615d362490f57bca5ac239c64eb9360913a4b",
"pin": "ed7615d362490f57bca5ac239c64eb9360913a4b"
"identity": "73b9d307048fc44d7f21fa3c829fc5a855d144a6",
"pin": "73b9d307048fc44d7f21fa3c829fc5a855d144a6"
},
"exit_code": 0,
"output": " Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.39s\n Running `<checkout>/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod <checkout>/airdef-mod/target/horizon-mod/airdef.hmod budget`\nrunning 1 scripts against <checkout>/airdef-mod/target/horizon-mod/airdef.hmod\ntest tests/wasm_budget.toml ... ok (271 steps)\ntest result: ok. 1 passed\n",
"measured_fuel": {
"available": true,
"callbacks": [
{
"budget": 1000000000,
"callback": "command",
"calls": 79,
"failures": 0,
"max_used": 6939810,
"mod": "airdef"
},
{
"budget": 10000000,
"callback": "frame",
"calls": 2202,
"failures": 0,
"max_used": 77,
"mod": "airdef"
},
{
"budget": 300000000,
"callback": "tick",
"calls": 3302,
"failures": 0,
"max_used": 182413686,
"mod": "airdef"
}
],
"scope": "guest callback fuel; excludes host CPU, memory and GPU time"
},
"output": " Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.35s\n Running `/private/tmp/issue-122-raid/horizon/target/debug/cargo-horizon-mod horizon-mod test --hmod /private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod --fuel-profile budget`\nrunning 1 scripts against /private/tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod\nfuel airdef command: calls=79 max=6939810 budget=1000000000 failures=0\nfuel airdef frame: calls=2202 max=77 budget=10000000 failures=0\nfuel airdef tick: calls=3302 max=182413686 budget=300000000 failures=0\ntest tests/wasm_budget.toml ... ok (283 steps)\ntest result: ok. 1 passed\n",
"runtime_limits": {
"fuel_per_call": {
"event": 1000000000,
@@ -34,16 +64,16 @@
"tick": 300000000
},
"memory_bytes": 67108864,
"metering": "source_configured; measured_per_scenario: unavailable",
"metering": "source_configured",
"source": "horizon/crates/horizon-mods/src/runtime.rs",
"wasmtime_component_model": true,
"wasmtime_fuel_metering": true
},
"scenario": "tests/budgets/wasm_flat_budget.toml",
"scenario_counts": {
"accepted_raids_asserted": 2,
"air_defense_units": 64,
"frames": 2052,
"accepted_raids_asserted": 4,
"air_defense_units": 68,
"frames": 2202,
"layout_unit_limit": 2000,
"peak_airborne_observed": null,
"raid_requests": 2,
@@ -51,13 +81,13 @@
"scripts": 1,
"snapshot_airborne_asserted": 184,
"snapshot_tick": 2102,
"steps": 271,
"ticks": 2102
"steps": 283,
"ticks": 3302
},
"scenario_render_world": "flat at y=64",
"scenario_sha256": "bcc0359289ab20ab3de608bcc130f72d2cf88f9f6fbc470d7b6846e9db5d11df",
"scenario_sha256": "134cb4667691cf9faa639ed37120941d829cfc13ce45e9638582c409d9e0dd29",
"schema": 1,
"status": "passed",
"wasmtime_version": "48.0.7",
"wit_sha256": "14c57b73f144888e04e27b77a6dfa29098c6b0c27c0383bb96aedaccb4c0a1d4"
"wit_sha256": "dded023a150a5f916bc5d935b7f891806728e0118eb7107ad0551d2aad8c70a5"
}
+97
View File
@@ -0,0 +1,97 @@
variant,commit,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,10,500,46,35,11,61,9,781,0,0,0,9,0,21,0,Geran3:3;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,1,10,500,46,37,9,62,9,812,0,0,0,4,1,23,0,Geran3:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,10,500,46,40,6,62,10,875,0,0,0,7,0,16,0,Shahed:1;Kh101:2;Kalibr:2;Iskander:1
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,2,10,500,46,41,5,65,11,883,0,0,0,6,0,20,0,Shahed:1;Kh101:2;Kalibr:1;Iskander:1
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,10,500,46,39,7,56,6,740,0,0,0,4,0,18,0,Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,3,10,500,46,39,7,56,6,740,0,0,0,4,0,18,0,Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,10,500,46,38,8,75,9,919,0,0,0,13,0,24,0,Geran3:1;Kh101:1;Kh22:1;Iskander:3;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,4,10,500,46,34,11,57,8,854,0,0,0,4,0,20,0,Geran3:2;Kh101:3;Kalibr:2;Kh22:1;Iskander:2;Kinzhal:1
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,10,500,46,34,11,66,8,871,0,0,0,12,0,26,0,Geran3:1;Kh101:2;Kh22:2;Zircon:1;Iskander:4;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,5,10,500,46,39,7,67,6,914,0,0,0,7,0,26,0,Kh101:2;Kh22:1;Iskander:3;Kinzhal:1
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,10,500,46,36,10,72,11,986,0,0,0,6,0,30,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,6,10,500,46,36,10,73,11,977,0,0,0,7,0,30,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,10,500,46,35,11,62,6,802,0,0,0,6,0,23,0,Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,7,10,500,46,35,11,63,6,802,0,0,0,7,0,23,0,Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,10,500,46,40,6,62,8,979,0,0,0,6,0,20,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
batt10,e6a70004406b34ea17884875ce236a5fb4b849e4,8,10,500,46,40,6,61,8,979,0,0,0,3,0,21,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,500,46,41,5,72,13,580,0,0,0,11,0,22,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,500,46,42,4,75,13,578,0,0,0,10,1,22,0,Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,500,46,40,6,81,14,629,0,0,0,10,0,36,0,Kh101:2;Kalibr:1;Zircon:1;Kinzhal:2
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,500,46,41,5,71,15,612,0,0,0,4,0,26,0,Kh101:2;Kalibr:1;Kinzhal:2
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,500,46,42,4,64,13,513,0,0,0,9,0,17,0,Zircon:1;Iskander:3
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,500,46,44,2,68,13,541,0,0,0,6,0,23,0,Zircon:1;Iskander:1
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,500,46,42,4,81,15,581,0,0,0,14,0,28,0,Kh22:1;Iskander:2;Kinzhal:1
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,500,46,42,4,76,15,614,0,0,0,8,0,27,0,Kh22:1;Iskander:2;Kinzhal:1
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,500,46,42,4,71,15,730,0,0,0,7,0,23,0,Kh101:1;Iskander:2;Kinzhal:1
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,500,46,42,4,73,15,748,0,0,0,6,0,25,0,Kh101:1;Iskander:2;Kinzhal:1
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,500,46,41,5,77,14,696,0,0,0,7,0,29,0,Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,500,46,41,5,80,13,681,0,0,0,5,0,34,0,Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,500,46,40,6,68,13,619,0,0,0,6,0,23,0,Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,500,46,40,6,68,13,619,0,0,0,6,0,23,0,Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
batt20,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,500,46,43,3,70,15,632,0,0,0,10,0,23,0,Zircon:1;Iskander:1;Kinzhal:1
batt20,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,500,46,42,4,67,14,669,0,0,0,8,0,23,0,Kh101:1;Iskander:2;Kinzhal:1
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,50,500,46,45,1,84,30,394,0,0,0,9,0,31,0,Kh22:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,1,50,500,46,45,1,83,28,418,0,0,0,7,0,32,0,Kh22:1
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,50,500,46,46,0,83,26,575,0,0,0,10,0,31,0,
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,2,50,500,46,46,0,82,28,514,0,0,0,6,0,35,0,
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,50,500,46,46,0,81,27,499,0,0,0,10,0,35,0,
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,3,50,500,46,46,0,77,27,523,0,0,0,3,0,35,0,
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,50,500,46,45,1,84,31,581,0,0,0,14,0,26,0,Iskander:1;Kinzhal:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,4,50,500,46,46,0,82,31,607,0,0,0,7,0,32,0,
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,50,500,46,44,2,82,32,586,0,0,0,8,0,36,0,Zircon:1;Kinzhal:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,5,50,500,46,46,0,87,29,707,0,0,0,10,0,40,0,
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,50,500,46,45,1,82,26,629,0,0,0,9,0,29,0,Kinzhal:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,6,50,500,46,46,0,94,29,584,0,0,0,11,0,39,0,
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,50,500,46,41,5,91,29,573,0,0,0,17,0,34,0,Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,7,50,500,46,42,4,82,31,523,0,0,0,4,0,37,0,Kh101:1;Kh22:1;Zircon:1;Kinzhal:1
batt50,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,50,500,46,45,1,74,26,677,0,0,0,6,0,30,0,Kinzhal:1
batt50,e6a70004406b34ea17884875ce236a5fb4b849e4,8,50,500,46,46,0,75,26,695,0,0,0,4,0,33,0,
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,200,46,41,5,75,16,350,0,0,0,2,0,32,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,200,46,41,5,75,16,350,0,0,0,2,0,32,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,200,46,40,5,69,14,383,0,0,1,5,0,25,0,Shahed:1;Kh101:2;Iskander:1;Kinzhal:2
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,200,46,40,5,71,14,401,0,0,1,4,0,29,0,Kh101:2;Iskander:2;Kinzhal:1
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,200,46,39,6,61,14,375,0,0,1,3,0,26,0,Shahed:1;Kh101:2;Iskander:2;Kinzhal:1
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,200,46,39,6,60,12,344,0,0,1,2,0,22,0,Shahed:1;Kh101:2;Iskander:3
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,200,46,40,6,83,15,459,0,0,0,15,0,30,0,Geran3:1;Kh22:2;Zircon:1;Iskander:1;Kinzhal:1
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,200,46,40,6,73,13,495,0,0,0,7,0,26,0,Geran3:1;Kh22:2;Iskander:2;Kinzhal:1
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,200,46,37,9,76,16,406,0,0,0,14,0,33,0,Kh101:1;Kh22:2;Zircon:1;Iskander:3;Kinzhal:2
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,200,46,41,5,71,17,455,0,0,0,2,0,34,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,200,46,39,7,71,13,450,0,0,0,4,0,29,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,200,46,39,7,71,13,450,0,0,0,4,0,29,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,200,46,39,7,77,14,448,0,0,0,9,0,31,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,200,46,40,6,84,14,465,0,0,0,11,0,33,0,Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
near200,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,200,46,38,8,70,14,524,0,0,0,10,0,28,0,Kh101:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
near200,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,200,46,38,8,67,15,563,0,0,0,4,0,31,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,1500,46,42,4,75,15,2181,0,0,0,9,0,27,0,Kh101:1;Iskander:1;Kinzhal:2
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,1500,46,44,2,68,14,2218,0,0,0,4,0,24,0,Iskander:1;Kinzhal:1
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,1500,46,41,5,72,17,2342,0,0,0,8,0,23,0,Kh101:1;Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,1500,46,43,3,70,20,2342,0,0,0,7,0,20,0,Kh101:1;Kalibr:1;Iskander:1
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,1500,46,43,3,68,19,2385,0,0,0,8,0,19,0,Iskander:2;Kinzhal:1
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,1500,46,44,2,70,20,2363,0,0,0,5,0,21,0,Iskander:2
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,1500,46,41,5,73,16,2388,0,0,0,14,0,22,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,1500,46,42,4,68,16,2387,0,0,0,5,0,25,0,Kh101:1;Kh22:1;Iskander:1;Kinzhal:1
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,1500,46,42,4,75,18,2550,0,0,0,12,0,24,0,Kh101:2;Iskander:1;Kinzhal:1
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,1500,46,42,4,69,19,2635,0,0,0,5,0,23,0,Kh101:2;Iskander:1;Kinzhal:1
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,1500,46,36,10,75,18,2575,0,0,0,3,0,37,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,1500,46,38,8,76,18,2575,0,0,0,2,0,36,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,1500,46,42,4,78,20,2361,0,0,0,10,0,27,0,Kh101:1;Iskander:1;Kinzhal:2
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,1500,46,43,3,73,18,2361,0,0,0,6,0,25,0,Kh101:1;Kalibr:1;Kinzhal:1
far1500,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,1500,46,41,5,66,19,2544,0,0,0,6,0,23,0,Kh101:1;Iskander:2;Kinzhal:2
far1500,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,1500,46,42,4,68,20,2544,0,0,0,4,0,26,0,Kh101:1;Iskander:2;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,1,20,500,46,41,5,79,14,606,0,0,0,12,0,27,0,Kalibr:1;Kh22:1;Zircon:1;Iskander:2
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,1,20,500,46,40,6,73,12,551,0,0,0,8,0,25,0,Geran3:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,2,20,500,46,38,8,77,15,651,8,0,0,2,0,30,0,Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,2,20,500,46,38,8,81,14,681,7,0,0,3,0,33,0,Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,3,20,500,46,44,1,79,12,640,0,1,1,10,0,28,0,Kh101:1;Zircon:1;Iskander:1
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,3,20,500,46,44,1,78,13,675,0,0,1,7,0,29,0,Kh101:1;Zircon:1;Iskander:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,4,20,500,46,40,6,82,15,492,3,3,0,13,0,25,0,Kh22:1;Iskander:4;Kinzhal:1
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,4,20,500,46,42,4,77,15,515,3,2,0,8,0,24,0,Kh22:1;Iskander:3
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,5,20,500,46,39,7,69,18,514,0,1,0,8,0,23,0,Kh22:1;Iskander:4;Kinzhal:2
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,5,20,500,46,42,4,65,15,469,1,0,0,4,0,22,0,Kh22:1;Iskander:2;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,6,20,500,46,43,3,68,13,612,0,0,0,3,0,22,0,Zircon:1;Iskander:1;Kinzhal:1
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,6,20,500,46,43,3,68,13,612,0,0,0,3,0,22,0,Zircon:1;Iskander:1;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,7,20,500,46,41,5,66,13,554,0,0,0,6,0,19,0,Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,7,20,500,46,43,3,64,15,546,0,0,0,5,0,16,0,Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
hills20,2689d933e790b7d751dfcf2a4c6a325e041562ce,8,20,500,46,42,4,77,14,712,3,0,0,14,0,20,0,Iskander:2;Kinzhal:2
hills20,e6a70004406b34ea17884875ce236a5fb4b849e4,8,20,500,46,42,4,77,14,712,3,0,0,13,0,20,0,Iskander:2;Kinzhal:2
1 variant commit seed sams dist sent kills leaked missiles heavy ticks blocked scrubbed crashes fuse_miss expired orphaned energy_lost leaks_by_kind
2 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 10 500 46 35 11 61 9 781 0 0 0 9 0 21 0 Geran3:3;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
3 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 1 10 500 46 37 9 62 9 812 0 0 0 4 1 23 0 Geran3:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
4 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 10 500 46 40 6 62 10 875 0 0 0 7 0 16 0 Shahed:1;Kh101:2;Kalibr:2;Iskander:1
5 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 2 10 500 46 41 5 65 11 883 0 0 0 6 0 20 0 Shahed:1;Kh101:2;Kalibr:1;Iskander:1
6 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 10 500 46 39 7 56 6 740 0 0 0 4 0 18 0 Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
7 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 3 10 500 46 39 7 56 6 740 0 0 0 4 0 18 0 Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
8 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 10 500 46 38 8 75 9 919 0 0 0 13 0 24 0 Geran3:1;Kh101:1;Kh22:1;Iskander:3;Kinzhal:2
9 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 4 10 500 46 34 11 57 8 854 0 0 0 4 0 20 0 Geran3:2;Kh101:3;Kalibr:2;Kh22:1;Iskander:2;Kinzhal:1
10 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 10 500 46 34 11 66 8 871 0 0 0 12 0 26 0 Geran3:1;Kh101:2;Kh22:2;Zircon:1;Iskander:4;Kinzhal:2
11 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 5 10 500 46 39 7 67 6 914 0 0 0 7 0 26 0 Kh101:2;Kh22:1;Iskander:3;Kinzhal:1
12 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 10 500 46 36 10 72 11 986 0 0 0 6 0 30 0 Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
13 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 6 10 500 46 36 10 73 11 977 0 0 0 7 0 30 0 Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
14 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 10 500 46 35 11 62 6 802 0 0 0 6 0 23 0 Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
15 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 7 10 500 46 35 11 63 6 802 0 0 0 7 0 23 0 Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
16 batt10 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 10 500 46 40 6 62 8 979 0 0 0 6 0 20 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
17 batt10 e6a70004406b34ea17884875ce236a5fb4b849e4 8 10 500 46 40 6 61 8 979 0 0 0 3 0 21 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
18 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 20 500 46 41 5 72 13 580 0 0 0 11 0 22 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
19 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 1 20 500 46 42 4 75 13 578 0 0 0 10 1 22 0 Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
20 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 20 500 46 40 6 81 14 629 0 0 0 10 0 36 0 Kh101:2;Kalibr:1;Zircon:1;Kinzhal:2
21 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 2 20 500 46 41 5 71 15 612 0 0 0 4 0 26 0 Kh101:2;Kalibr:1;Kinzhal:2
22 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 20 500 46 42 4 64 13 513 0 0 0 9 0 17 0 Zircon:1;Iskander:3
23 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 3 20 500 46 44 2 68 13 541 0 0 0 6 0 23 0 Zircon:1;Iskander:1
24 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 20 500 46 42 4 81 15 581 0 0 0 14 0 28 0 Kh22:1;Iskander:2;Kinzhal:1
25 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 4 20 500 46 42 4 76 15 614 0 0 0 8 0 27 0 Kh22:1;Iskander:2;Kinzhal:1
26 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 20 500 46 42 4 71 15 730 0 0 0 7 0 23 0 Kh101:1;Iskander:2;Kinzhal:1
27 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 5 20 500 46 42 4 73 15 748 0 0 0 6 0 25 0 Kh101:1;Iskander:2;Kinzhal:1
28 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 20 500 46 41 5 77 14 696 0 0 0 7 0 29 0 Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
29 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 6 20 500 46 41 5 80 13 681 0 0 0 5 0 34 0 Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
30 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 20 500 46 40 6 68 13 619 0 0 0 6 0 23 0 Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
31 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 7 20 500 46 40 6 68 13 619 0 0 0 6 0 23 0 Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
32 batt20 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 20 500 46 43 3 70 15 632 0 0 0 10 0 23 0 Zircon:1;Iskander:1;Kinzhal:1
33 batt20 e6a70004406b34ea17884875ce236a5fb4b849e4 8 20 500 46 42 4 67 14 669 0 0 0 8 0 23 0 Kh101:1;Iskander:2;Kinzhal:1
34 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 50 500 46 45 1 84 30 394 0 0 0 9 0 31 0 Kh22:1
35 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 1 50 500 46 45 1 83 28 418 0 0 0 7 0 32 0 Kh22:1
36 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 50 500 46 46 0 83 26 575 0 0 0 10 0 31 0
37 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 2 50 500 46 46 0 82 28 514 0 0 0 6 0 35 0
38 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 50 500 46 46 0 81 27 499 0 0 0 10 0 35 0
39 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 3 50 500 46 46 0 77 27 523 0 0 0 3 0 35 0
40 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 50 500 46 45 1 84 31 581 0 0 0 14 0 26 0 Iskander:1;Kinzhal:1
41 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 4 50 500 46 46 0 82 31 607 0 0 0 7 0 32 0
42 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 50 500 46 44 2 82 32 586 0 0 0 8 0 36 0 Zircon:1;Kinzhal:1
43 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 5 50 500 46 46 0 87 29 707 0 0 0 10 0 40 0
44 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 50 500 46 45 1 82 26 629 0 0 0 9 0 29 0 Kinzhal:1
45 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 6 50 500 46 46 0 94 29 584 0 0 0 11 0 39 0
46 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 50 500 46 41 5 91 29 573 0 0 0 17 0 34 0 Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
47 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 7 50 500 46 42 4 82 31 523 0 0 0 4 0 37 0 Kh101:1;Kh22:1;Zircon:1;Kinzhal:1
48 batt50 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 50 500 46 45 1 74 26 677 0 0 0 6 0 30 0 Kinzhal:1
49 batt50 e6a70004406b34ea17884875ce236a5fb4b849e4 8 50 500 46 46 0 75 26 695 0 0 0 4 0 33 0
50 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 20 200 46 41 5 75 16 350 0 0 0 2 0 32 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
51 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 1 20 200 46 41 5 75 16 350 0 0 0 2 0 32 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
52 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 20 200 46 40 5 69 14 383 0 0 1 5 0 25 0 Shahed:1;Kh101:2;Iskander:1;Kinzhal:2
53 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 2 20 200 46 40 5 71 14 401 0 0 1 4 0 29 0 Kh101:2;Iskander:2;Kinzhal:1
54 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 20 200 46 39 6 61 14 375 0 0 1 3 0 26 0 Shahed:1;Kh101:2;Iskander:2;Kinzhal:1
55 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 3 20 200 46 39 6 60 12 344 0 0 1 2 0 22 0 Shahed:1;Kh101:2;Iskander:3
56 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 20 200 46 40 6 83 15 459 0 0 0 15 0 30 0 Geran3:1;Kh22:2;Zircon:1;Iskander:1;Kinzhal:1
57 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 4 20 200 46 40 6 73 13 495 0 0 0 7 0 26 0 Geran3:1;Kh22:2;Iskander:2;Kinzhal:1
58 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 20 200 46 37 9 76 16 406 0 0 0 14 0 33 0 Kh101:1;Kh22:2;Zircon:1;Iskander:3;Kinzhal:2
59 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 5 20 200 46 41 5 71 17 455 0 0 0 2 0 34 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
60 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 20 200 46 39 7 71 13 450 0 0 0 4 0 29 0 Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
61 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 6 20 200 46 39 7 71 13 450 0 0 0 4 0 29 0 Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
62 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 20 200 46 39 7 77 14 448 0 0 0 9 0 31 0 Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
63 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 7 20 200 46 40 6 84 14 465 0 0 0 11 0 33 0 Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
64 near200 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 20 200 46 38 8 70 14 524 0 0 0 10 0 28 0 Kh101:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
65 near200 e6a70004406b34ea17884875ce236a5fb4b849e4 8 20 200 46 38 8 67 15 563 0 0 0 4 0 31 0 Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
66 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 20 1500 46 42 4 75 15 2181 0 0 0 9 0 27 0 Kh101:1;Iskander:1;Kinzhal:2
67 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 1 20 1500 46 44 2 68 14 2218 0 0 0 4 0 24 0 Iskander:1;Kinzhal:1
68 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 20 1500 46 41 5 72 17 2342 0 0 0 8 0 23 0 Kh101:1;Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
69 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 2 20 1500 46 43 3 70 20 2342 0 0 0 7 0 20 0 Kh101:1;Kalibr:1;Iskander:1
70 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 20 1500 46 43 3 68 19 2385 0 0 0 8 0 19 0 Iskander:2;Kinzhal:1
71 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 3 20 1500 46 44 2 70 20 2363 0 0 0 5 0 21 0 Iskander:2
72 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 20 1500 46 41 5 73 16 2388 0 0 0 14 0 22 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
73 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 4 20 1500 46 42 4 68 16 2387 0 0 0 5 0 25 0 Kh101:1;Kh22:1;Iskander:1;Kinzhal:1
74 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 20 1500 46 42 4 75 18 2550 0 0 0 12 0 24 0 Kh101:2;Iskander:1;Kinzhal:1
75 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 5 20 1500 46 42 4 69 19 2635 0 0 0 5 0 23 0 Kh101:2;Iskander:1;Kinzhal:1
76 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 20 1500 46 36 10 75 18 2575 0 0 0 3 0 37 0 Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
77 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 6 20 1500 46 38 8 76 18 2575 0 0 0 2 0 36 0 Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
78 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 20 1500 46 42 4 78 20 2361 0 0 0 10 0 27 0 Kh101:1;Iskander:1;Kinzhal:2
79 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 7 20 1500 46 43 3 73 18 2361 0 0 0 6 0 25 0 Kh101:1;Kalibr:1;Kinzhal:1
80 far1500 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 20 1500 46 41 5 66 19 2544 0 0 0 6 0 23 0 Kh101:1;Iskander:2;Kinzhal:2
81 far1500 e6a70004406b34ea17884875ce236a5fb4b849e4 8 20 1500 46 42 4 68 20 2544 0 0 0 4 0 26 0 Kh101:1;Iskander:2;Kinzhal:1
82 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 1 20 500 46 41 5 79 14 606 0 0 0 12 0 27 0 Kalibr:1;Kh22:1;Zircon:1;Iskander:2
83 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 1 20 500 46 40 6 73 12 551 0 0 0 8 0 25 0 Geran3:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
84 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 2 20 500 46 38 8 77 15 651 8 0 0 2 0 30 0 Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
85 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 2 20 500 46 38 8 81 14 681 7 0 0 3 0 33 0 Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
86 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 3 20 500 46 44 1 79 12 640 0 1 1 10 0 28 0 Kh101:1;Zircon:1;Iskander:1
87 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 3 20 500 46 44 1 78 13 675 0 0 1 7 0 29 0 Kh101:1;Zircon:1;Iskander:1
88 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 4 20 500 46 40 6 82 15 492 3 3 0 13 0 25 0 Kh22:1;Iskander:4;Kinzhal:1
89 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 4 20 500 46 42 4 77 15 515 3 2 0 8 0 24 0 Kh22:1;Iskander:3
90 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 5 20 500 46 39 7 69 18 514 0 1 0 8 0 23 0 Kh22:1;Iskander:4;Kinzhal:2
91 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 5 20 500 46 42 4 65 15 469 1 0 0 4 0 22 0 Kh22:1;Iskander:2;Kinzhal:1
92 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 6 20 500 46 43 3 68 13 612 0 0 0 3 0 22 0 Zircon:1;Iskander:1;Kinzhal:1
93 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 6 20 500 46 43 3 68 13 612 0 0 0 3 0 22 0 Zircon:1;Iskander:1;Kinzhal:1
94 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 7 20 500 46 41 5 66 13 554 0 0 0 6 0 19 0 Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
95 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 7 20 500 46 43 3 64 15 546 0 0 0 5 0 16 0 Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
96 hills20 2689d933e790b7d751dfcf2a4c6a325e041562ce 8 20 500 46 42 4 77 14 712 3 0 0 14 0 20 0 Iskander:2;Kinzhal:2
97 hills20 e6a70004406b34ea17884875ce236a5fb4b849e4 8 20 500 46 42 4 77 14 712 3 0 0 13 0 20 0 Iskander:2;Kinzhal:2
@@ -0,0 +1,6 @@
running 1 scripts against /tmp/issue-122-raid/airdef-mod/target/horizon-mod/airdef.hmod
fuel airdef command: calls=179 max=32946177 budget=1000000000 failures=0
fuel airdef frame: calls=377 max=77 budget=10000000 failures=0
fuel airdef tick: calls=3802 max=236581288 budget=300000000 failures=0
test tests/wasm_budget.toml ... ok (255 steps)
test result: ok. 1 passed
@@ -0,0 +1,10 @@
=== BEFORE: scaling witness — an 11-drone second order at the same state ===
running 1 scripts against /tmp/issue-122-run/airdef-diag-before.hmod
fuel airdef command: calls=177 max=247805865 budget=1000000000 failures=0
fuel airdef frame: calls=257 max=77 budget=10000000 failures=0
fuel airdef tick: calls=2602 max=241372671 budget=300000000 failures=0
test tests/wasm_budget.toml ... FAILED
step 229 (/airdef wave mix 1 300): feedback
expected: Some("PROBE")
got: Some("DIAG revealed=13172 known=144 sams=172 alive=144 planning=true queue=0")
error: 1 failed, 0 passed
@@ -0,0 +1,7 @@
=== BEFORE: second order (UI path) traps at the 1e9 event budget ===
running 1 scripts against /tmp/issue-122-run/airdef-diag-before.hmod
fuel airdef command: calls=177 max=1000000000 budget=1000000000 failures=1
fuel airdef frame: calls=257 max=77 budget=10000000 failures=0
fuel airdef tick: calls=2602 max=241372671 budget=300000000 failures=0
test tests/wasm_budget.toml ... ok (229 steps)
test result: ok. 1 passed
@@ -0,0 +1,762 @@
[[step]]
render-ground-y = 64
ticks = 2
frames = 2
expect.commands = ["airdef"]
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
command = "airdef ew on"
[[step]]
command = "airdef wave mix 10 300"
[[step]]
ticks = 100
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef ew on"
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef ew on"
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef stats"
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 308, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8156 секций (382 КБ), запросов 16075, неизвестно 0, лучей 87524 (ударов 1830, неизв. 1567), клеток 1318224; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
[[step]]
command = "airdef wave mix 10 300"
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef stats"
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 309, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8557 секций (401 КБ), запросов 16511, неизвестно 0, лучей 89230 (ударов 2855, неизв. 2039), клеток 1326528; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
@@ -0,0 +1,688 @@
[[step]]
render-ground-y = 64
ticks = 2
frames = 2
expect.commands = ["airdef"]
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 0.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 40.0 }
command = "airdef deploy ew"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 40.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 80.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 120.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 0.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 40.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 80.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 120.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 160.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 200.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 240.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy s400"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy patriot"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy nasams"
[[step]]
player = { x = 280.0, z = 160.0 }
command = "airdef deploy pantsir"
[[step]]
command = "airdef ew on"
[[step]]
command = "airdef wave mix 10 300"
[[step]]
ticks = 100
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef ew on"
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef ew on"
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
ticks = 50
frames = 5
[[step]]
command = "airdef stats"
expect.feedback = "В воздухе: 0, ракет: 0, ПВО: 172, сбито: 308, поражений: 87, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8156 секций (382 КБ), запросов 16075, неизвестно 0, лучей 87524 (ударов 1830, неизв. 1567), клеток 1318224; взрывы в блоках: 239 (подтверждено 0, без перемен 37, нет чанка 202), чужих ответов 0"
[[step]]
command = "airdef wave mix 10 300"
expect.stopped = "exceeded its execution limit"
@@ -0,0 +1,67 @@
{
"schema": 1,
"issue": 122,
"kind": "diagnostic_guest_ui_path_comparison_not_exact_user_session",
"user_report": {
"log": "Horizon: mod airdef stopped in UI event (fuel budget 1000000000, remaining Some(0))",
"backtrace": "airdef_core::sim::ew::Sim::known_units <- sim::raid::Sim::order_raid <- airdef::AirDef::launch_wave <- horizon_mod_sdk::Mod::ui_select <- ui-events select",
"windows_session_confirmed_same_cause": false
},
"root_cause": {
"what": "order_raid recomputed the planner snapshot known_units() for every drone (choose_target), and known_units() itself rescanned the whole force and the dedup list per intel entry",
"growth": "drones x intel_log x force_size per UI event; the intel log holds every launch, EW disclosure, and radar disclosure of the last 6000 ticks",
"state_at_trap": {
"revealed_entries": 13172,
"known_alive_units": 144,
"sams_total": 172
}
},
"fix": {
"description": "one known_units snapshot per order_raid passed to radar_strikes and choose_target; known_units is a single O(R+S) set pass; price_grid_on reuses its snapshot",
"semantics": "identical planner results; native equivalence test against the former predicate; WASM checkpoint /airdef stats byte-identical before/after at tick 2602",
"limits_unchanged": true,
"wave_size_unrestricted": true,
"hd_record_untouched": true
},
"setup": {
"defenses": "40 spread clusters x 4 heavy SAMs + 12 EW = 172, player moved per deploy step",
"first_raid": "airdef wave mix 10 (111 drones, Smart, AllSides) via the diagnostic UI-path trigger",
"second_raid": "same, at tick ~2600 after the first raid is fought off",
"note": "stacked single-point layouts die to one warhead (known=0, cheap order); the trap needs a surviving force, like the user's session"
},
"before": {
"source": "e6a7000 + trigger.patch (diagnostic guest only)",
"second_order_111_drones": {
"callback": "command (the diagnostic trigger invokes the exact ui_select(BTN_LAUNCH) handler; the UI event and the command share the same 1e9 event budget)",
"max_used": 1000000000,
"budget": 1000000000,
"failures": 1,
"mod_stopped": true,
"log": "before-trap.txt"
},
"scaling_witness_11_drones_same_state": {
"max_used": 247805865,
"budget": 1000000000,
"failures": 0,
"log": "before-scaling.txt"
}
},
"after": {
"same_scenario_passed": true,
"steps": 255,
"max_command_fuel": 32946177,
"max_tick_fuel": 236581288,
"failures": 0,
"checkpoint_stats_equal_before_after": true,
"log": "after.txt"
},
"artifacts": {
"trigger_patch": "trigger.patch",
"scenario_before": "scenario-before.toml",
"scenario_after": "scenario-after.toml",
"before_guest_sha256": "6d4525cd7aaa61dbf344593f9819be1b61e06654126e9e9088e57967dc657365",
"after_guest_sha256": "c4ef7d759524eb053ccd55f0eccdcb49c91954201eb4e0ad923ee9b2828efc4e",
"scenario_before_sha256": "398d099275e396deab269601e5adbcf325ab5e0ea6b540c1d03a477d6b0963d1",
"scenario_after_sha256": "3bc27338d2e6fb433f027a0cf1afc39ff9a94e1af5840454082af6d8d15aad7c"
}
}
@@ -0,0 +1,23 @@
diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs
index dc6585eb3..73864e41e 100644
--- a/airdef-mod/src/lib.rs
+++ b/airdef-mod/src/lib.rs
@@ -2351,8 +2351,16 @@ impl Mod for AirDef {
.nearest_target(DVec3::new(p.x, p.y, p.z))
.unwrap_or(DVec3::new(p.x, p.y, p.z));
if *kind == "mix" {
- let objects = self.objects(DVec3::new(p.x, p.y, p.z));
- self.sim.order_raid(&wave::WaveConfig::mix(count, dist), &objects, &mut out);
+ // DIAGNOSTIC ONLY (issue #122): drive the exact UI launch path
+ // (Page::WaveGo, BTN_LAUNCH) with the maximum menu composition.
+ let mut wave = wave::WaveConfig::default();
+ wave.counts = [40; wave::KINDS.len()];
+ wave.dist = dist;
+ wave.approach = sim::Approach::AllSides;
+ wave.aim = sim::Aim::Smart;
+ self.wave = wave;
+ self.menu = Some(Page::WaveGo);
+ self.ui_select(BTN_LAUNCH, 0);
} else {
let kind = DroneKind::from_key(kind).ok_or(
"Тип: shahed, geran3, lancet, gerbera, kh101, kalibr, kh22, zircon, iskander, kinzhal, oreshnik или mix",
@@ -0,0 +1,102 @@
# Issue #126, этап 1: retained-геометрия моделей мода — замеры
Первый самостоятельный этап направления A #126: грани моделей мода резолвятся против атласа
один раз на generation пака, кадр только трансформирует и освещает их. Это **не** GPU-instancing:
вершины по-прежнему собираются на CPU и загружаются каждый кадр; объём upload не менялся.
Изменение только в рендере (`game/mod_models.rs` + span/счётчики/инвалидация), боевая симуляция
(WASM-мод) не тронута — тот же `airdef.hmod` в обоих прогонах A/B.
## Стенд
- Apple M5 (10 ядер, 16 ГБ), macOS, Metal. **Ryzen 5600X / RTX 3060 не профилировались** —
приёмка на целевом железе pending (контракт #126).
- Engine pin `ed751714e` (ветка форка `agent/126-engine-first-stage`), AirDef base `60f1bf0fd`.
Baseline-бинарник — тот же pin без правки; after — с правкой. Оба `--profile fast --features mods`.
- 2560×1440 offscreen (окно 1280×720 @2x), пресет HD, `HORIZON_HD_SCALE=1`, in-frame
(`--in-frame`: фидбек мода читается `chat-log`, тик в кадре — одинаково в A/B),
`HORIZON_NO_AUDIO=1`, `HORIZON_SPIKES=0` (span каждого кадра в логе),
`HORIZON_SHADER_PACK_TIMING=1`. Одна игра за раз; чужих игр во время парных прогонов не было.
- Мир `Polygon` (копия `run-home/saves/Polygon`), свежий `HORIZON_HOME` на прогон.
Камера `tp @s 40 76 40 135 25`, `time set 6000`, `advance_time/advance_weather false`,
`weather clear`, creative, HUD скрыт.
## Сцена и драйвер
Драйвер — scratch-скрипт `/tmp/airdef-issue126-run/profile.py` (в коммит не входит; команды и
тайминги зафиксированы здесь и в `report.json`):
1. 14 батарей: `airdef deploy s400/patriot/pantsir/gepard/nasams/irist/tor` ×2.
2. Raid: `airdef wave shahed 40 900`, `airdef wave kh101 16 1400`, `airdef wave mix 24 700`.
Волна принимается не сразу: противник ищет площадки и ждёт terrain (~15–20 с), факт принятия
проверялся по чату («ВОЗДУШНАЯ ТРЕВОГА», «В воздухе: N») и counters `mod_models.models`.
3. `bench N` (сброс frame-stats и counters, ответ — p50/p95/p99/max frame/CPU/GPU + фазы),
`stats` (counters `mod_models`), `sample` процесса на окно bench, скриншот.
Static-сцена: только батареи, `HORIZON_HD_TAA=0 HORIZON_HD_WIND=0 HORIZON_HD_CLOUDS=0
HORIZON_HD_VOLFOG=0`, 3 кадра подряд; движущиеся пиксели (вода) маскируются по размаху >16/255
между кадрами одного прогона (методика `tools/hd_bench.py`), сравнение A/B — по статичным.
## Результаты (парные прогоны, одна сцена)
Raid, develop 30 с + bench 12 с (`before-raid3` / `after-raid`), ~135 моделей/кадр:
| Метрика | before | after |
|---|---|---|
| `entity_geometry` CPU avg / p95 / p99, мс | 5.71 / 8.7 / 10.6 | 1.57 / 2.2 / 2.7 |
| фаза `prepare` avg, мс | 23.49 | 7.05 |
| frame CPU avg / p50 / p95 / p99, мс | 78.8 / 75.5 / 133.0 / 263.4 | 71.8 / 65.3 / 112.7 / 181.0 |
| span `mod_models` CPU avg / p95 / p99, мс | — (внутри `entity_geometry`) | 1.32 / 2.0 / 2.3 |
Combat-плотный raid, develop 45 с + bench 15 с (`before-combat` / `after-combat`); фазы боя
не синхронизированы по тикам (before: 28 в воздухе, 12 сбито; after: 40 в воздухе, 0 сбито):
| Метрика | before | after |
|---|---|---|
| `entity_geometry` CPU avg / p95 / p99, мс | 6.5 / 12.1 / 15.0 | 1.95 / 3.3 / 4.4 |
| фаза `prepare` avg, мс | 20.13 | 7.78 |
| frame CPU avg / p50 / p95 / p99, мс | 85.8 / 84.8 / 127.2 / 167.5 | 49.5 / 48.9 / 71.8 / 77.1 |
Counters `mod_models` (after-raid, окно bench, 155 кадров): models 21001 (~135/кадр),
quads 2 760 334 (~17.8 тыс./кадр), vertex_bytes 485.8 МБ (~3.1 МБ/кадр, 44 Б/вершина),
motion_bytes 618.3 МБ (~4 МБ/кадр, 56 Б/вершина), mesh_builds 0, atlas_scans 0 — в установившемся
кадре bake нет, только трансформы. Байты upload до/после одинаковы (вершины те же).
Static (4 батареи, ~60 моделей/кадр): `prepare` 6.38 → 1.51 мс, frame CPU p50 15.1 → 10.9 мс,
p95 42.7 → 15.5, p99 77.1 → 18.3 (settle 8 с). **Пиксели A/B при settle 25 с (LOD сошёлся):
0 статичных пикселей с разницей >20/255 из 3.44 млн (93.2% кадра статичны), mean abs diff 0.128.**
При settle 8 с разница 3991 px (0.116%) — вся в полосе горизонта y≤385 (дальний LOD не сошёлся,
after-бинарник быстрее → другое состояние LOD к снимку); baseline↔baseline при том же settle — 14 px.
## Reload и world unload (lifecycle-smoke)
`lifecycle.py`: батареи → скриншот → F3+T (reload) → скриншот → Esc → «Save and Quit to Title» →
`open Polygon` → батареи → скриншот. Counters after: atlas_scans 1 → 2 → 3, mesh_builds
17 → 34 → 51 (17 состояний моделей перестроены после reload и после unload), модели рисуются
в каждом этапе. Пиксели pre/post reload при 25 с ожидания: **before 0.3003%, after 0.2982%**
статичных пикселей >20/255 — одинаковая у обоих бинарников остаточная разница самого reload
(атлас/LOD после `clear_lod`), не регрессия правки; при 12 с ожидания разница больше у обоих
(LOD не сошёлся), вся в полосе горизонта, на моделях — ноль.
## Тесты
```sh
cd horizon && cargo test --profile fast -p horizon-client --bin horizon-client --features mods mod_models::tests
```
- `retained_emit_matches_the_per_frame_bake` — вершины retained-пути бит-в-бит равны прежнему
покадровому bake (`block_model_vertices` + material/post-pass) на матрице трансформов
(scale × rotation × translation) × glow × light × emission, включая previous-позиции motion (#124).
- `special_materials_match_names_and_centres` — таблица special-материалов и строгие границы
прямоугольников (центр квада).
## Ограничения и что дальше
- Замеры только на M5/Metal; 5600X/3060 и M5-боевой p99-trace — pending acceptance #126.
- In-frame режим замера (тик в кадре); server-thread путь проверен smoke-прогоном (HD, модели,
reload работают), парные замеры в нём не снимались.
- Фазы боя в A/B не синхронизированы по тикам (wall-clock waits); ordered combat trace harness
не строился — правка только рендерная, sim/RNG не тронуты (diff scope).
- Upload bytes/frame не уменьшены: GPU-instancing (per-instance буферы, GPU-интерполяция,
indirect draws) — следующий этап A. HD smoke (направление B) не тронут.
- Скрипты драйверов — scratch (`/tmp/airdef-issue126-run/`), в репозиторий не входят;
воспроизведение — по командам выше и `report.json`.
@@ -0,0 +1,338 @@
{
"issue": 126,
"stage": "first: retained CPU-resolved model meshes (not GPU instancing)",
"engine_pin": "ed751714e0d24d02062976ee615e994186284170",
"airdef_base": "60f1bf0fd873d89a28b47bc7316b2fc02a79e669",
"machine": "Apple M5, 10 cores, 16 GB, macOS, Metal backend",
"render": "2560x1440 offscreen (window 1280x720 @2x), HD preset, HORIZON_HD_SCALE=1, in-frame mode, HORIZON_NO_AUDIO=1, HORIZON_SPIKES=0, HORIZON_SHADER_PACK_TIMING=1",
"mod": "airdef.hmod built from airdef-mod @ base (unchanged between A/B), packer pinned ed751714",
"scene": {
"world": "Polygon (copy of run-home/saves/Polygon), fresh HORIZON_HOME per run",
"camera": "tp @s 40 76 40 135 25, time set 6000, advance_time/advance_weather false, weather clear, gamemode creative, HUD hidden (f1)",
"batteries": "deploy s400/patriot/pantsir/gepard/nasams/irist/tor twice (14 complexes)",
"raid": "wave shahed 40 900; wave kh101 16 1400; wave mix 24 700",
"static_env": "HORIZON_HD_TAA=0 HORIZON_HD_WIND=0 HORIZON_HD_CLOUDS=0 HORIZON_HD_VOLFOG=0",
"driver": "/tmp/airdef-issue126-run/profile.py (scratch; commands and waits recorded here)"
},
"runs": {
"before-raid3": {
"frames": 130,
"cpu_ms": {
"avg_ms": 78.76,
"max_ms": 321.6,
"p50_ms": 75.53,
"p95_ms": 132.96,
"p99_ms": 263.41
},
"phases_avg_ms": {
"prepare": 23.49,
"render": 25.45,
"tick": 28.1,
"update": 1.73
},
"entity_geometry_cpu_ms": {
"n": 1355,
"avg": 5.71,
"p50": 6.0,
"p95": 8.7,
"p99": 10.6,
"max": 29.1
},
"mod_models_span_cpu_ms": null,
"mod_models_counters": null,
"airborne_at_bench": "В воздухе: 19, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 4; удары по ПУ: пущено 0, уничтожено 0, подавле"
},
"after-raid": {
"frames": 124,
"cpu_ms": {
"avg_ms": 71.75,
"max_ms": 427.98,
"p50_ms": 65.26,
"p95_ms": 112.68,
"p99_ms": 181.0
},
"phases_avg_ms": {
"prepare": 7.05,
"render": 30.29,
"tick": 30.43,
"update": 3.97
},
"entity_geometry_cpu_ms": {
"n": 1260,
"avg": 1.57,
"p50": 1.6,
"p95": 2.2,
"p99": 2.7,
"max": 33.9
},
"mod_models_span_cpu_ms": {
"n": 1065,
"avg": 1.32,
"p50": 1.3,
"p95": 2.0,
"p99": 2.3,
"max": 2.7
},
"mod_models_counters": {
"atlas_scans": 0,
"frames": 155,
"mesh_builds": 0,
"models": 21001,
"motion_bytes": 618314816,
"motion_quads": 2760334,
"quads": 2760334,
"vertex_bytes": 485818784
},
"airborne_at_bench": "В воздухе: 24, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавле"
},
"before-combat": {
"frames": 166,
"cpu_ms": {
"avg_ms": 85.79,
"max_ms": 185.08,
"p50_ms": 84.82,
"p95_ms": 127.19,
"p99_ms": 167.54
},
"phases_avg_ms": {
"prepare": 20.13,
"render": 35.38,
"tick": 29.07,
"update": 1.21
},
"entity_geometry_cpu_ms": {
"n": 1709,
"avg": 6.5,
"p50": 5.8,
"p95": 12.1,
"p99": 15.0,
"max": 18.4
},
"mod_models_span_cpu_ms": null,
"mod_models_counters": null,
"airborne_at_bench": "В воздухе: 28, ракет: 0, ПВО: 14, сбито: 12, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавл"
},
"after-combat": {
"frames": 275,
"cpu_ms": {
"avg_ms": 49.47,
"max_ms": 88.18,
"p50_ms": 48.89,
"p95_ms": 71.79,
"p99_ms": 77.13
},
"phases_avg_ms": {
"prepare": 7.78,
"render": 24.58,
"tick": 16.23,
"update": 0.88
},
"entity_geometry_cpu_ms": {
"n": 1861,
"avg": 1.95,
"p50": 1.8,
"p95": 3.3,
"p99": 4.4,
"max": 19.5
},
"mod_models_span_cpu_ms": {
"n": 1733,
"avg": 1.63,
"p50": 1.5,
"p95": 2.8,
"p99": 3.9,
"max": 4.4
},
"mod_models_counters": {
"atlas_scans": 0,
"frames": 286,
"mesh_builds": 3,
"models": 44077,
"motion_bytes": 1173606784,
"motion_quads": 5239316,
"quads": 5239316,
"vertex_bytes": 922119616
},
"airborne_at_bench": "В воздухе: 40, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавле"
},
"before-static": {
"frames": 174,
"cpu_ms": {
"avg_ms": 17.92,
"max_ms": 88.07,
"p50_ms": 15.12,
"p95_ms": 42.66,
"p99_ms": 77.07
},
"phases_avg_ms": {
"prepare": 6.38,
"render": 7.6,
"tick": 3.9,
"update": 0.04
},
"entity_geometry_cpu_ms": {
"n": 1094,
"avg": 4.21,
"p50": 4.6,
"p95": 6.6,
"p99": 7.1,
"max": 27.1
},
"mod_models_span_cpu_ms": null,
"mod_models_counters": null,
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
},
"after-static": {
"frames": 190,
"cpu_ms": {
"avg_ms": 11.1,
"max_ms": 20.46,
"p50_ms": 10.92,
"p95_ms": 15.54,
"p99_ms": 18.3
},
"phases_avg_ms": {
"prepare": 1.51,
"render": 6.47,
"tick": 2.97,
"update": 0.16
},
"entity_geometry_cpu_ms": {
"n": 1163,
"avg": 1.29,
"p50": 1.3,
"p95": 1.9,
"p99": 2.1,
"max": 26.3
},
"mod_models_span_cpu_ms": {
"n": 913,
"avg": 1.04,
"p50": 1.0,
"p95": 1.4,
"p99": 1.5,
"max": 1.6
},
"mod_models_counters": {
"atlas_scans": 0,
"frames": 196,
"mesh_builds": 0,
"models": 11760,
"motion_bytes": 322255360,
"motion_quads": 1438640,
"quads": 1438640,
"vertex_bytes": 253200640
},
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
},
"before-static-long": {
"frames": 237,
"cpu_ms": {
"avg_ms": 9.68,
"max_ms": 15.56,
"p50_ms": 9.59,
"p95_ms": 12.85,
"p99_ms": 14.01
},
"phases_avg_ms": {
"prepare": 3.72,
"render": 4.32,
"tick": 1.51,
"update": 0.12
},
"entity_geometry_cpu_ms": {
"n": 1951,
"avg": 3.29,
"p50": 3.5,
"p95": 3.9,
"p99": 4.1,
"max": 13.8
},
"mod_models_span_cpu_ms": null,
"mod_models_counters": null,
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
},
"after-static-long": {
"frames": 181,
"cpu_ms": {
"avg_ms": 14.21,
"max_ms": 24.87,
"p50_ms": 14.27,
"p95_ms": 20.55,
"p99_ms": 23.39
},
"phases_avg_ms": {
"prepare": 1.92,
"render": 8.27,
"tick": 3.64,
"update": 0.37
},
"entity_geometry_cpu_ms": {
"n": 1506,
"avg": 1.15,
"p50": 1.0,
"p95": 2.0,
"p99": 2.2,
"max": 14.9
},
"mod_models_span_cpu_ms": {
"n": 1354,
"avg": 0.88,
"p50": 0.8,
"p95": 1.6,
"p99": 1.7,
"max": 1.8
},
"mod_models_counters": {
"atlas_scans": 0,
"frames": 183,
"mesh_builds": 0,
"models": 10980,
"motion_bytes": 300881280,
"motion_quads": 1343220,
"quads": 1343220,
"vertex_bytes": 236406720
},
"airborne_at_bench": "В воздухе: 0, ракет: 0, ПВО: 14, сбито: 0, поражений: 0, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлен"
}
},
"pixel_ab": {
"static_settle25": {
"static_pixels_pct": 93.2,
"diff_gt20": 0,
"diff_gt60": 0,
"mean_abs_diff": 0.128
},
"static_settle8": {
"static_pixels_pct": 93.1,
"diff_gt20": 3991,
"diff_gt60": 0,
"note": "LOD not converged at 8 s; diffs all in horizon band y<=385, none on models; baseline-vs-baseline at same settle: 14 px"
},
"reload_lifecycle_settle25": {
"before_diff_gt20_pct": 0.3003,
"after_diff_gt20_pct": 0.2982,
"note": "same residual in both binaries (atlas/LOD after clear_lod); at 12 s settle both larger, all in horizon band, zero on models"
}
},
"tests": {
"command": "cargo test --profile fast -p horizon-client --bin horizon-client --features mods mod_models::tests",
"result": "2 passed (retained_emit_matches_the_per_frame_bake, special_materials_match_names_and_centres)"
},
"lifecycle_counters_after": {
"pre_reload": {
"atlas_scans": 1,
"mesh_builds": 17
},
"post_reload": {
"atlas_scans": 2,
"mesh_builds": 34
},
"post_unload_reenter": {
"atlas_scans": 3,
"mesh_builds": 51
}
},
"engine_commit": "a861c1ed2402fb13950a3c3049d16e9971489c24",
"engine_branch": "kimi-work-124"
}
@@ -0,0 +1,155 @@
{
"schema": 1,
"world": "EnemyPicture127",
"branch": "kimi-work (baseline, before #127 stage 1)",
"code_commit": "0b645d77e",
"bench": "cargo run --release --example intel_bench (airdef-core, SDK-free)",
"scenarios": [
"big-smart",
"logistics",
"ew-adaptive"
],
"seeds": [
1,
7,
42
],
"metrics": "completion: raids_ended/raids_ordered, all_ended; losses: sams_lost; exchange: launched/kills/hits/crashes/fired; failure reasons: sim.tally text (Russian, as the tally words them)",
"runs": [
{
"scenario": "big-smart",
"seed": 1,
"ticks_run": 1642,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 50,
"failures": "5 промахов по взрывателю, 30 ракет остались без цели, 4 потерь трека"
},
{
"scenario": "big-smart",
"seed": 7,
"ticks_run": 1514,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 49,
"failures": "2 промахов по взрывателю, 22 ракет остались без цели, 6 потерь трека"
},
{
"scenario": "big-smart",
"seed": 42,
"ticks_run": 1490,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 56,
"failures": "5 промахов по взрывателю, 35 ракет остались без цели, 9 потерь трека"
},
{
"scenario": "logistics",
"seed": 1,
"ticks_run": 1009,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 11,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 7,
"ticks_run": 970,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 7,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 42,
"ticks_run": 1003,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
},
{
"scenario": "ew-adaptive",
"seed": 1,
"ticks_run": 8661,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 62,
"hits": 3,
"crashes": 4,
"sams_lost": 1,
"fired": 82,
"failures": "8 промахов по взрывателю, 1 ракет выработали ресурс, 24 ракет остались без цели, 14 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 7,
"ticks_run": 8809,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 61,
"hits": 5,
"crashes": 3,
"sams_lost": 4,
"fired": 78,
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 10 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 42,
"ticks_run": 6976,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 61,
"hits": 7,
"crashes": 1,
"sams_lost": 4,
"fired": 75,
"failures": "8 промахов по взрывателю, 1 ракет выработали ресурс, 25 ракет остались без цели, 10 потерь трека"
}
]
}
@@ -0,0 +1,155 @@
{
"schema": 1,
"world": "EnemyPicture127",
"branch": "agent/issue-127-enemy-picture",
"code_commit": "agent/issue-127-enemy-picture (see git log for the exact SHA)",
"bench": "cargo run --release --example intel_bench (airdef-core, SDK-free)",
"scenarios": [
"big-smart",
"logistics",
"ew-adaptive"
],
"seeds": [
1,
7,
42
],
"metrics": "completion: raids_ended/raids_ordered, all_ended; losses: sams_lost; exchange: launched/kills/hits/crashes/fired; failure reasons: sim.tally text (Russian, as the tally words them)",
"runs": [
{
"scenario": "big-smart",
"seed": 1,
"ticks_run": 1716,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 49,
"failures": "3 промахов по взрывателю, 27 ракет остались без цели, 3 потерь трека"
},
{
"scenario": "big-smart",
"seed": 7,
"ticks_run": 1542,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 48,
"failures": "2 промахов по взрывателю, 22 ракет остались без цели, 5 потерь трека"
},
{
"scenario": "big-smart",
"seed": 42,
"ticks_run": 1433,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 49,
"failures": "2 промахов по взрывателю, 27 ракет остались без цели, 7 потерь трека"
},
{
"scenario": "logistics",
"seed": 1,
"ticks_run": 1009,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 11,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 7,
"ticks_run": 970,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 7,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 42,
"ticks_run": 1003,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
},
{
"scenario": "ew-adaptive",
"seed": 1,
"ticks_run": 8084,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 59,
"hits": 7,
"crashes": 3,
"sams_lost": 3,
"fired": 69,
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 11 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 7,
"ticks_run": 8193,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 59,
"hits": 7,
"crashes": 3,
"sams_lost": 3,
"fired": 81,
"failures": "4 промахов по взрывателю, 3 ракет выработали ресурс, 26 ракет остались без цели, 8 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 42,
"ticks_run": 7916,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 56,
"hits": 8,
"crashes": 5,
"sams_lost": 4,
"fired": 69,
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 12 потерь трека"
}
]
}
@@ -0,0 +1,154 @@
{
"schema": 1,
"world": "IntentQueue127",
"branch": "8fc10c07a",
"code_commit": "8fc10c07a (base of the branch; the run was made from a clean worktree at that commit)",
"bench": "cargo run --release --example intel_bench (airdef-mod, SDK-free harness)",
"scenarios": [
"big-smart",
"ew-adaptive",
"logistics"
],
"seeds": [
1,
7,
42
],
"runs": [
{
"scenario": "big-smart",
"seed": 1,
"ticks_run": 1716,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 49,
"failures": "3 промахов по взрывателю, 27 ракет остались без цели, 3 потерь трека"
},
{
"scenario": "big-smart",
"seed": 7,
"ticks_run": 1542,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 48,
"failures": "2 промахов по взрывателю, 22 ракет остались без цели, 5 потерь трека"
},
{
"scenario": "big-smart",
"seed": 42,
"ticks_run": 1433,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 49,
"failures": "2 промахов по взрывателю, 27 ракет остались без цели, 7 потерь трека"
},
{
"scenario": "logistics",
"seed": 1,
"ticks_run": 1009,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 11,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 7,
"ticks_run": 970,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 7,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 42,
"ticks_run": 1003,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
},
{
"scenario": "ew-adaptive",
"seed": 1,
"ticks_run": 8084,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 59,
"hits": 7,
"crashes": 3,
"sams_lost": 3,
"fired": 69,
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 11 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 7,
"ticks_run": 8193,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 59,
"hits": 7,
"crashes": 3,
"sams_lost": 3,
"fired": 81,
"failures": "4 промахов по взрывателю, 3 ракет выработали ресурс, 26 ракет остались без цели, 8 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 42,
"ticks_run": 7916,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 56,
"hits": 8,
"crashes": 5,
"sams_lost": 4,
"fired": 69,
"failures": "7 промахов по взрывателю, 20 ракет остались без цели, 12 потерь трека"
}
]
}
@@ -0,0 +1,190 @@
{
"schema": 1,
"world": "IntentQueue127",
"branch": "agent/issue-127-intent-durable",
"code_commit": "agent/issue-127-intent-durable (this branch; see git log for the exact SHA)",
"bench": "cargo run --release --example intel_bench (airdef-mod, SDK-free harness)",
"scenarios": [
"big-smart",
"ew-adaptive",
"logistics"
],
"seeds": [
1,
7,
42
],
"runs": [
{
"scenario": "big-smart",
"seed": 1,
"ticks_run": 1676,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 60,
"retargets_max": 1,
"air_bytes": 61895,
"switches_max": 1,
"intents": "plan:25,sead:0,react:13,replace:0",
"failures": "3 промахов по взрывателю, 41 ракет остались без цели, 9 потерь трека"
},
{
"scenario": "big-smart",
"seed": 7,
"ticks_run": 1542,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 68,
"retargets_max": 2,
"air_bytes": 62311,
"switches_max": 1,
"intents": "plan:24,sead:0,react:14,replace:0",
"failures": "6 промахов по взрывателю, 37 ракет остались без цели, 9 потерь трека"
},
{
"scenario": "big-smart",
"seed": 42,
"ticks_run": 1433,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 38,
"kills": 38,
"hits": 0,
"crashes": 0,
"sams_lost": 0,
"fired": 71,
"retargets_max": 2,
"air_bytes": 61205,
"switches_max": 1,
"intents": "plan:22,sead:0,react:16,replace:0",
"failures": "5 промахов по взрывателю, 49 ракет остались без цели, 21 потерь трека"
},
{
"scenario": "logistics",
"seed": 1,
"ticks_run": 1009,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 11,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"retargets_max": 0,
"air_bytes": 4041,
"switches_max": 0,
"intents": "plan:0,sead:0,react:0,replace:0",
"failures": "1 промахов по взрывателю, 6 ракет остались без цели, 1 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 7,
"ticks_run": 970,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 7,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"retargets_max": 0,
"air_bytes": 4031,
"switches_max": 0,
"intents": "plan:0,sead:0,react:0,replace:0",
"failures": "6 ракет остались без цели, 2 потерь трека, 3 ожиданий БК"
},
{
"scenario": "logistics",
"seed": 42,
"ticks_run": 1003,
"raids_ordered": 1,
"raids_ended": 1,
"all_ended": true,
"launched": 27,
"kills": 12,
"hits": 8,
"crashes": 0,
"sams_lost": 0,
"fired": 18,
"retargets_max": 0,
"air_bytes": 4018,
"switches_max": 0,
"intents": "plan:0,sead:0,react:0,replace:0",
"failures": "6 ракет остались без цели, 3 потерь трека, 3 ожиданий БК"
},
{
"scenario": "ew-adaptive",
"seed": 1,
"ticks_run": 7146,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 58,
"hits": 7,
"crashes": 4,
"sams_lost": 3,
"fired": 76,
"retargets_max": 0,
"air_bytes": 7125,
"switches_max": 1,
"intents": "plan:47,sead:8,react:14,replace:0",
"failures": "10 промахов по взрывателю, 17 ракет остались без цели, 11 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 7,
"ticks_run": 7650,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 58,
"hits": 9,
"crashes": 2,
"sams_lost": 4,
"fired": 98,
"retargets_max": 0,
"air_bytes": 8808,
"switches_max": 1,
"intents": "plan:19,sead:2,react:13,replace:35",
"failures": "9 промахов по взрывателю, 45 ракет остались без цели, 13 потерь трека"
},
{
"scenario": "ew-adaptive",
"seed": 42,
"ticks_run": 7243,
"raids_ordered": 3,
"raids_ended": 3,
"all_ended": true,
"launched": 69,
"kills": 63,
"hits": 3,
"crashes": 3,
"sams_lost": 2,
"fired": 82,
"retargets_max": 0,
"air_bytes": 7997,
"switches_max": 1,
"intents": "plan:49,sead:8,react:12,replace:0",
"failures": "12 промахов по взрывателю, 21 ракет остались без цели, 18 потерь трека"
}
]
}
+25
View File
@@ -0,0 +1,25 @@
variant,commit,seed,sent,kills,leaked,missiles,ticks
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,17,17,0,27,434
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,17,16,1,28,462
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,17,17,0,30,384
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,17,17,0,31,551
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,17,17,0,29,700
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,17,17,0,33,443
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,17,17,0,33,463
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,17,17,0,25,548
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,9,17,17,0,30,728
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,10,17,17,0,26,875
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,11,17,17,0,30,640
baseline,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,12,17,17,0,33,546
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,17,17,0,28,301
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,17,16,1,30,544
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,17,16,1,30,384
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,17,17,0,30,465
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,17,17,0,30,731
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,17,17,0,32,521
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,17,17,0,35,592
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,17,17,0,26,626
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,9,17,17,0,30,729
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,10,17,16,1,26,765
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,11,17,17,0,30,632
cold-launch,4b013fb7f30dbaa87a266b27a31911937fc523b4,12,17,17,0,33,546
1 variant commit seed sent kills leaked missiles ticks
2 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 17 17 0 27 434
3 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 17 16 1 28 462
4 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 17 17 0 30 384
5 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 17 17 0 31 551
6 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 17 17 0 29 700
7 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 17 17 0 33 443
8 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 17 17 0 33 463
9 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 17 17 0 25 548
10 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 9 17 17 0 30 728
11 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 10 17 17 0 26 875
12 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 11 17 17 0 30 640
13 baseline dc36d67eb740e6a9fb56224b32b007e3bf2512b9 12 17 17 0 33 546
14 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 17 17 0 28 301
15 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 17 16 1 30 544
16 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 17 16 1 30 384
17 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 17 17 0 30 465
18 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 17 17 0 30 731
19 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 17 17 0 32 521
20 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 17 17 0 35 592
21 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 17 17 0 26 626
22 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 9 17 17 0 30 729
23 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 10 17 16 1 26 765
24 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 11 17 17 0 30 632
25 cold-launch 4b013fb7f30dbaa87a266b27a31911937fc523b4 12 17 17 0 33 546
+97
View File
@@ -0,0 +1,97 @@
variant,commit,seed,sams,dist,sent,kills,leaked,missiles,heavy,ticks,blocked,scrubbed,crashes,fuse_miss,expired,orphaned,energy_lost,leaks_by_kind
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,10,500,46,37,9,62,9,812,0,0,0,4,1,23,0,Geran3:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,10,500,46,41,5,65,11,883,0,0,0,6,0,20,0,Shahed:1;Kh101:2;Kalibr:1;Iskander:1
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,10,500,46,39,7,56,6,740,0,0,0,4,0,18,0,Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,10,500,46,34,11,57,8,854,0,0,0,4,0,20,0,Geran3:2;Kh101:3;Kalibr:2;Kh22:1;Iskander:2;Kinzhal:1
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,10,500,46,39,7,67,6,914,0,0,0,7,0,26,0,Kh101:2;Kh22:1;Iskander:3;Kinzhal:1
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,10,500,46,36,10,73,11,977,0,0,0,7,0,30,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,10,500,46,35,11,63,6,802,0,0,0,7,0,23,0,Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,10,500,46,40,6,61,8,979,0,0,0,3,0,21,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,10,500,46,36,10,58,9,825,0,0,0,4,0,20,0,Geran3:3;Kh101:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,10,500,46,38,8,64,10,892,0,0,0,4,0,23,0,Shahed:1;Kh101:2;Kalibr:2;Zircon:1;Iskander:2
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,10,500,46,38,8,62,8,714,0,0,0,7,0,23,0,Kalibr:2;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,10,500,46,35,10,61,8,902,0,0,0,4,0,24,0,Geran3:1;Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:2
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,10,500,46,36,9,62,6,896,0,0,0,6,0,27,0,Geran3:1;Kh101:2;Kh22:1;Iskander:4;Kinzhal:1
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,10,500,46,31,13,64,8,988,0,0,0,4,0,29,0,Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:3;Kinzhal:2
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,10,500,46,36,9,60,9,921,0,0,0,5,0,20,0,Geran3:1;Kh101:3;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
batt10,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,10,500,46,40,6,63,7,979,0,0,0,5,0,22,0,Kh101:1;Zircon:1;Iskander:2;Kinzhal:2
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,20,500,46,42,4,75,13,578,0,0,0,10,1,22,0,Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,20,500,46,41,5,71,15,612,0,0,0,4,0,26,0,Kh101:2;Kalibr:1;Kinzhal:2
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,20,500,46,44,2,68,13,541,0,0,0,6,0,23,0,Zircon:1;Iskander:1
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,20,500,46,42,4,76,15,614,0,0,0,8,0,27,0,Kh22:1;Iskander:2;Kinzhal:1
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,20,500,46,42,4,73,15,748,0,0,0,6,0,25,0,Kh101:1;Iskander:2;Kinzhal:1
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,20,500,46,41,5,80,13,681,0,0,0,5,0,34,0,Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,20,500,46,40,6,68,13,619,0,0,0,6,0,23,0,Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
batt20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,20,500,46,42,4,67,14,669,0,0,0,8,0,23,0,Kh101:1;Iskander:2;Kinzhal:1
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,20,500,46,40,6,79,12,555,0,0,0,10,0,31,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,20,500,46,40,6,71,14,626,0,0,0,4,0,29,0,Kh101:2;Kalibr:1;Zircon:1;Iskander:1;Kinzhal:1
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,20,500,46,42,4,65,14,528,0,0,0,5,0,22,0,Zircon:1;Iskander:1;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,20,500,46,42,4,79,15,632,0,0,0,10,0,30,0,Kh22:1;Iskander:1;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,20,500,46,41,5,74,14,687,0,0,0,6,0,27,0,Kh101:1;Iskander:2;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,20,500,46,39,7,83,15,689,0,0,0,9,0,34,0,Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,20,500,46,40,6,70,12,606,0,0,0,6,0,26,0,Kh101:2;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
batt20,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,20,500,46,43,3,72,16,636,0,0,0,5,0,28,0,Iskander:2;Kinzhal:1
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,50,500,46,45,1,83,28,418,0,0,0,7,0,32,0,Kh22:1
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,50,500,46,46,0,82,28,514,0,0,0,6,0,35,0,
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,50,500,46,46,0,77,27,523,0,0,0,3,0,35,0,
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,50,500,46,46,0,82,31,607,0,0,0,7,0,32,0,
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,50,500,46,46,0,87,29,707,0,0,0,10,0,40,0,
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,50,500,46,46,0,94,29,584,0,0,0,11,0,39,0,
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,50,500,46,42,4,82,31,523,0,0,0,4,0,37,0,Kh101:1;Kh22:1;Zircon:1;Kinzhal:1
batt50,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,50,500,46,46,0,75,26,695,0,0,0,4,0,33,0,
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,50,500,46,45,1,81,29,481,0,0,0,3,0,32,0,Zircon:1
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,50,500,46,45,1,85,29,501,0,0,0,2,0,42,0,Kinzhal:1
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,50,500,46,45,1,76,26,474,0,0,0,6,0,35,0,Kinzhal:1
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,50,500,46,46,0,77,29,617,0,0,0,4,0,32,0,
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,50,500,46,46,0,86,31,597,0,0,0,7,0,40,0,
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,50,500,46,44,2,91,31,821,0,0,0,10,0,42,0,Kh22:1;Kinzhal:1
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,50,500,46,43,3,79,28,523,0,0,0,4,0,34,0,Kh101:1;Zircon:1;Kinzhal:1
batt50,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,50,500,46,44,2,77,27,678,0,0,0,6,0,35,0,Zircon:1;Kinzhal:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,20,1500,46,44,2,68,14,2218,0,0,0,4,0,24,0,Iskander:1;Kinzhal:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,20,1500,46,43,3,70,20,2342,0,0,0,7,0,20,0,Kh101:1;Kalibr:1;Iskander:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,20,1500,46,44,2,70,20,2363,0,0,0,5,0,21,0,Iskander:2
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,20,1500,46,42,4,68,16,2387,0,0,0,5,0,25,0,Kh101:1;Kh22:1;Iskander:1;Kinzhal:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,20,1500,46,42,4,69,19,2635,0,0,0,5,0,23,0,Kh101:2;Iskander:1;Kinzhal:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,20,1500,46,38,8,76,18,2575,0,0,0,2,0,36,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,20,1500,46,43,3,73,18,2361,0,0,0,6,0,25,0,Kh101:1;Kalibr:1;Kinzhal:1
far1500,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,20,1500,46,42,4,68,20,2544,0,0,0,4,0,26,0,Kh101:1;Iskander:2;Kinzhal:1
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,20,1500,46,44,2,67,16,2145,0,0,0,4,0,26,0,Iskander:1;Kinzhal:1
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,20,1500,46,42,4,65,17,2346,0,0,0,6,0,18,0,Kh101:1;Kalibr:1;Iskander:1;Kinzhal:1
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,20,1500,46,43,3,68,18,2358,0,0,0,5,0,21,0,Iskander:3
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,20,1500,46,41,5,70,16,2386,0,0,0,5,0,28,0,Kh101:1;Kh22:1;Iskander:1;Kinzhal:2
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,20,1500,46,42,4,71,19,2551,0,0,0,5,0,24,0,Kh101:2;Iskander:1;Kinzhal:1
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,20,1500,46,37,9,78,19,2579,0,0,0,3,0,38,0,Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,20,1500,46,43,3,75,20,2365,0,0,0,7,0,26,0,Kh101:1;Kinzhal:2
far1500,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,20,1500,46,42,4,67,18,2548,0,0,0,4,0,25,0,Kh101:1;Iskander:2;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,20,500,46,40,6,73,12,551,0,0,0,8,0,25,0,Geran3:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,20,500,46,38,8,81,14,681,7,0,0,3,0,33,0,Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,20,500,46,44,1,78,13,675,0,0,1,7,0,29,0,Kh101:1;Zircon:1;Iskander:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,20,500,46,42,4,77,15,515,3,2,0,8,0,24,0,Kh22:1;Iskander:3
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,20,500,46,42,4,65,15,469,1,0,0,4,0,22,0,Kh22:1;Iskander:2;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,20,500,46,43,3,68,13,612,0,0,0,3,0,22,0,Zircon:1;Iskander:1;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,20,500,46,43,3,64,15,546,0,0,0,5,0,16,0,Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
hills20,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,20,500,46,42,4,77,14,712,3,0,0,13,0,20,0,Iskander:2;Kinzhal:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,20,500,46,38,8,75,14,541,0,0,0,6,0,31,0,Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,20,500,46,39,6,77,14,633,5,0,1,3,0,31,0,Kh101:2;Iskander:3;Kinzhal:1
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,20,500,46,41,3,71,12,643,0,1,2,1,0,27,0,Kh101:1;Zircon:1;Iskander:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,20,500,46,39,7,75,16,520,3,2,0,3,0,28,0,Kh22:1;Iskander:4;Kinzhal:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,20,500,46,39,7,70,18,512,0,1,0,3,0,28,0,Kh101:1;Kh22:1;Iskander:3;Kinzhal:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,20,500,46,41,5,66,14,615,1,0,0,4,0,20,0,Kh101:1;Iskander:2;Kinzhal:2
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,20,500,46,41,5,76,14,579,0,0,0,8,0,28,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
hills20,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,20,500,46,41,5,70,14,653,0,0,0,6,0,26,0,Kh101:1;Zircon:1;Iskander:2;Kinzhal:2
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,1,20,200,46,41,5,75,16,350,0,0,0,2,0,32,0,Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,2,20,200,46,40,5,71,14,401,0,0,1,4,0,29,0,Kh101:2;Iskander:2;Kinzhal:1
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,3,20,200,46,39,6,60,12,344,0,0,1,2,0,22,0,Shahed:1;Kh101:2;Iskander:3
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,4,20,200,46,40,6,73,13,495,0,0,0,7,0,26,0,Geran3:1;Kh22:2;Iskander:2;Kinzhal:1
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,5,20,200,46,41,5,71,17,455,0,0,0,2,0,34,0,Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,6,20,200,46,39,7,71,13,450,0,0,0,4,0,29,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,7,20,200,46,40,6,84,14,465,0,0,0,11,0,33,0,Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
near200,dc36d67eb740e6a9fb56224b32b007e3bf2512b9,8,20,200,46,38,8,67,15,563,0,0,0,4,0,31,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,1,20,200,46,41,5,84,16,404,0,0,0,8,0,35,0,Geran3:1;Kh22:1;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,2,20,200,46,38,7,70,15,393,0,0,1,4,0,30,0,Shahed:1;Kh101:2;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,3,20,200,46,39,6,61,13,338,0,0,1,4,0,27,0,Shahed:1;Kh101:2;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,4,20,200,46,38,7,74,14,467,0,0,0,3,0,36,0,Geran3:1;Kh22:2;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,5,20,200,46,40,6,73,13,481,0,0,0,8,0,32,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,6,20,200,46,38,8,66,14,540,0,0,0,2,0,27,0,Kh101:3;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,7,20,200,46,39,7,86,16,496,0,0,0,9,0,39,0,Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
near200,4b013fb7f30dbaa87a266b27a31911937fc523b4,8,20,200,46,38,8,73,15,585,0,0,0,4,0,34,0,Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
1 variant commit seed sams dist sent kills leaked missiles heavy ticks blocked scrubbed crashes fuse_miss expired orphaned energy_lost leaks_by_kind
2 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 10 500 46 37 9 62 9 812 0 0 0 4 1 23 0 Geran3:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
3 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 10 500 46 41 5 65 11 883 0 0 0 6 0 20 0 Shahed:1;Kh101:2;Kalibr:1;Iskander:1
4 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 10 500 46 39 7 56 6 740 0 0 0 4 0 18 0 Kalibr:2;Zircon:1;Iskander:3;Kinzhal:1
5 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 10 500 46 34 11 57 8 854 0 0 0 4 0 20 0 Geran3:2;Kh101:3;Kalibr:2;Kh22:1;Iskander:2;Kinzhal:1
6 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 10 500 46 39 7 67 6 914 0 0 0 7 0 26 0 Kh101:2;Kh22:1;Iskander:3;Kinzhal:1
7 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 10 500 46 36 10 73 11 977 0 0 0 7 0 30 0 Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:2;Kinzhal:2
8 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 10 500 46 35 11 63 6 802 0 0 0 7 0 23 0 Geran3:1;Kh101:2;Kalibr:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
9 batt10 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 10 500 46 40 6 61 8 979 0 0 0 3 0 21 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:2
10 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 10 500 46 36 10 58 9 825 0 0 0 4 0 20 0 Geran3:3;Kh101:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
11 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 10 500 46 38 8 64 10 892 0 0 0 4 0 23 0 Shahed:1;Kh101:2;Kalibr:2;Zircon:1;Iskander:2
12 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 10 500 46 38 8 62 8 714 0 0 0 7 0 23 0 Kalibr:2;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
13 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 10 500 46 35 10 61 8 902 0 0 0 4 0 24 0 Geran3:1;Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:2
14 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 10 500 46 36 9 62 6 896 0 0 0 6 0 27 0 Geran3:1;Kh101:2;Kh22:1;Iskander:4;Kinzhal:1
15 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 10 500 46 31 13 64 8 988 0 0 0 4 0 29 0 Geran3:1;Kh101:3;Kalibr:3;Zircon:1;Iskander:3;Kinzhal:2
16 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 10 500 46 36 9 60 9 921 0 0 0 5 0 20 0 Geran3:1;Kh101:3;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
17 batt10 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 10 500 46 40 6 63 7 979 0 0 0 5 0 22 0 Kh101:1;Zircon:1;Iskander:2;Kinzhal:2
18 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 20 500 46 42 4 75 13 578 0 0 0 10 1 22 0 Kalibr:1;Kh22:1;Iskander:1;Kinzhal:1
19 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 20 500 46 41 5 71 15 612 0 0 0 4 0 26 0 Kh101:2;Kalibr:1;Kinzhal:2
20 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 20 500 46 44 2 68 13 541 0 0 0 6 0 23 0 Zircon:1;Iskander:1
21 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 20 500 46 42 4 76 15 614 0 0 0 8 0 27 0 Kh22:1;Iskander:2;Kinzhal:1
22 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 20 500 46 42 4 73 15 748 0 0 0 6 0 25 0 Kh101:1;Iskander:2;Kinzhal:1
23 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 20 500 46 41 5 80 13 681 0 0 0 5 0 34 0 Kalibr:1;Zircon:1;Iskander:1;Kinzhal:2
24 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 20 500 46 40 6 68 13 619 0 0 0 6 0 23 0 Kh101:2;Kh22:1;Zircon:1;Kinzhal:2
25 batt20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 20 500 46 42 4 67 14 669 0 0 0 8 0 23 0 Kh101:1;Iskander:2;Kinzhal:1
26 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 20 500 46 40 6 79 12 555 0 0 0 10 0 31 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
27 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 20 500 46 40 6 71 14 626 0 0 0 4 0 29 0 Kh101:2;Kalibr:1;Zircon:1;Iskander:1;Kinzhal:1
28 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 20 500 46 42 4 65 14 528 0 0 0 5 0 22 0 Zircon:1;Iskander:1;Kinzhal:2
29 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 20 500 46 42 4 79 15 632 0 0 0 10 0 30 0 Kh22:1;Iskander:1;Kinzhal:2
30 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 20 500 46 41 5 74 14 687 0 0 0 6 0 27 0 Kh101:1;Iskander:2;Kinzhal:2
31 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 20 500 46 39 7 83 15 689 0 0 0 9 0 34 0 Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
32 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 20 500 46 40 6 70 12 606 0 0 0 6 0 26 0 Kh101:2;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
33 batt20 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 20 500 46 43 3 72 16 636 0 0 0 5 0 28 0 Iskander:2;Kinzhal:1
34 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 50 500 46 45 1 83 28 418 0 0 0 7 0 32 0 Kh22:1
35 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 50 500 46 46 0 82 28 514 0 0 0 6 0 35 0
36 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 50 500 46 46 0 77 27 523 0 0 0 3 0 35 0
37 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 50 500 46 46 0 82 31 607 0 0 0 7 0 32 0
38 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 50 500 46 46 0 87 29 707 0 0 0 10 0 40 0
39 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 50 500 46 46 0 94 29 584 0 0 0 11 0 39 0
40 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 50 500 46 42 4 82 31 523 0 0 0 4 0 37 0 Kh101:1;Kh22:1;Zircon:1;Kinzhal:1
41 batt50 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 50 500 46 46 0 75 26 695 0 0 0 4 0 33 0
42 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 50 500 46 45 1 81 29 481 0 0 0 3 0 32 0 Zircon:1
43 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 50 500 46 45 1 85 29 501 0 0 0 2 0 42 0 Kinzhal:1
44 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 50 500 46 45 1 76 26 474 0 0 0 6 0 35 0 Kinzhal:1
45 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 50 500 46 46 0 77 29 617 0 0 0 4 0 32 0
46 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 50 500 46 46 0 86 31 597 0 0 0 7 0 40 0
47 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 50 500 46 44 2 91 31 821 0 0 0 10 0 42 0 Kh22:1;Kinzhal:1
48 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 50 500 46 43 3 79 28 523 0 0 0 4 0 34 0 Kh101:1;Zircon:1;Kinzhal:1
49 batt50 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 50 500 46 44 2 77 27 678 0 0 0 6 0 35 0 Zircon:1;Kinzhal:1
50 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 20 1500 46 44 2 68 14 2218 0 0 0 4 0 24 0 Iskander:1;Kinzhal:1
51 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 20 1500 46 43 3 70 20 2342 0 0 0 7 0 20 0 Kh101:1;Kalibr:1;Iskander:1
52 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 20 1500 46 44 2 70 20 2363 0 0 0 5 0 21 0 Iskander:2
53 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 20 1500 46 42 4 68 16 2387 0 0 0 5 0 25 0 Kh101:1;Kh22:1;Iskander:1;Kinzhal:1
54 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 20 1500 46 42 4 69 19 2635 0 0 0 5 0 23 0 Kh101:2;Iskander:1;Kinzhal:1
55 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 20 1500 46 38 8 76 18 2575 0 0 0 2 0 36 0 Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
56 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 20 1500 46 43 3 73 18 2361 0 0 0 6 0 25 0 Kh101:1;Kalibr:1;Kinzhal:1
57 far1500 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 20 1500 46 42 4 68 20 2544 0 0 0 4 0 26 0 Kh101:1;Iskander:2;Kinzhal:1
58 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 20 1500 46 44 2 67 16 2145 0 0 0 4 0 26 0 Iskander:1;Kinzhal:1
59 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 20 1500 46 42 4 65 17 2346 0 0 0 6 0 18 0 Kh101:1;Kalibr:1;Iskander:1;Kinzhal:1
60 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 20 1500 46 43 3 68 18 2358 0 0 0 5 0 21 0 Iskander:3
61 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 20 1500 46 41 5 70 16 2386 0 0 0 5 0 28 0 Kh101:1;Kh22:1;Iskander:1;Kinzhal:2
62 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 20 1500 46 42 4 71 19 2551 0 0 0 5 0 24 0 Kh101:2;Iskander:1;Kinzhal:1
63 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 20 1500 46 37 9 78 19 2579 0 0 0 3 0 38 0 Kh101:2;Kalibr:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
64 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 20 1500 46 43 3 75 20 2365 0 0 0 7 0 26 0 Kh101:1;Kinzhal:2
65 far1500 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 20 1500 46 42 4 67 18 2548 0 0 0 4 0 25 0 Kh101:1;Iskander:2;Kinzhal:1
66 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 20 500 46 40 6 73 12 551 0 0 0 8 0 25 0 Geran3:1;Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:1
67 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 20 500 46 38 8 81 14 681 7 0 0 3 0 33 0 Kh101:2;Kalibr:1;Kh22:1;Iskander:3;Kinzhal:1
68 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 20 500 46 44 1 78 13 675 0 0 1 7 0 29 0 Kh101:1;Zircon:1;Iskander:1
69 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 20 500 46 42 4 77 15 515 3 2 0 8 0 24 0 Kh22:1;Iskander:3
70 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 20 500 46 42 4 65 15 469 1 0 0 4 0 22 0 Kh22:1;Iskander:2;Kinzhal:1
71 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 20 500 46 43 3 68 13 612 0 0 0 3 0 22 0 Zircon:1;Iskander:1;Kinzhal:1
72 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 20 500 46 43 3 64 15 546 0 0 0 5 0 16 0 Kh22:1;Zircon:1;Iskander:1;Kinzhal:1
73 hills20 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 20 500 46 42 4 77 14 712 3 0 0 13 0 20 0 Iskander:2;Kinzhal:2
74 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 20 500 46 38 8 75 14 541 0 0 0 6 0 31 0 Kalibr:1;Kh22:1;Zircon:1;Iskander:3;Kinzhal:2
75 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 20 500 46 39 6 77 14 633 5 0 1 3 0 31 0 Kh101:2;Iskander:3;Kinzhal:1
76 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 20 500 46 41 3 71 12 643 0 1 2 1 0 27 0 Kh101:1;Zircon:1;Iskander:2
77 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 20 500 46 39 7 75 16 520 3 2 0 3 0 28 0 Kh22:1;Iskander:4;Kinzhal:2
78 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 20 500 46 39 7 70 18 512 0 1 0 3 0 28 0 Kh101:1;Kh22:1;Iskander:3;Kinzhal:2
79 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 20 500 46 41 5 66 14 615 1 0 0 4 0 20 0 Kh101:1;Iskander:2;Kinzhal:2
80 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 20 500 46 41 5 76 14 579 0 0 0 8 0 28 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
81 hills20 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 20 500 46 41 5 70 14 653 0 0 0 6 0 26 0 Kh101:1;Zircon:1;Iskander:2;Kinzhal:2
82 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 1 20 200 46 41 5 75 16 350 0 0 0 2 0 32 0 Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
83 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 2 20 200 46 40 5 71 14 401 0 0 1 4 0 29 0 Kh101:2;Iskander:2;Kinzhal:1
84 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 3 20 200 46 39 6 60 12 344 0 0 1 2 0 22 0 Shahed:1;Kh101:2;Iskander:3
85 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 4 20 200 46 40 6 73 13 495 0 0 0 7 0 26 0 Geran3:1;Kh22:2;Iskander:2;Kinzhal:1
86 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 5 20 200 46 41 5 71 17 455 0 0 0 2 0 34 0 Kh101:1;Kh22:1;Iskander:2;Kinzhal:1
87 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 6 20 200 46 39 7 71 13 450 0 0 0 4 0 29 0 Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
88 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 7 20 200 46 40 6 84 14 465 0 0 0 11 0 33 0 Kh101:1;Kh22:1;Zircon:1;Iskander:1;Kinzhal:2
89 near200 dc36d67eb740e6a9fb56224b32b007e3bf2512b9 8 20 200 46 38 8 67 15 563 0 0 0 4 0 31 0 Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
90 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 1 20 200 46 41 5 84 16 404 0 0 0 8 0 35 0 Geran3:1;Kh22:1;Iskander:2;Kinzhal:2
91 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 2 20 200 46 38 7 70 15 393 0 0 1 4 0 30 0 Shahed:1;Kh101:2;Iskander:2;Kinzhal:2
92 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 3 20 200 46 39 6 61 13 338 0 0 1 4 0 27 0 Shahed:1;Kh101:2;Iskander:2;Kinzhal:2
93 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 4 20 200 46 38 7 74 14 467 0 0 0 3 0 36 0 Geran3:1;Kh22:2;Iskander:2;Kinzhal:2
94 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 5 20 200 46 40 6 73 13 481 0 0 0 8 0 32 0 Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:1
95 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 6 20 200 46 38 8 66 14 540 0 0 0 2 0 27 0 Kh101:3;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
96 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 7 20 200 46 39 7 86 16 496 0 0 0 9 0 39 0 Kh101:1;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
97 near200 4b013fb7f30dbaa87a266b27a31911937fc523b4 8 20 200 46 38 8 73 15 585 0 0 0 4 0 34 0 Kh101:2;Kh22:1;Zircon:1;Iskander:2;Kinzhal:2
+150
View File
@@ -0,0 +1,150 @@
{
"schema": 1,
"world": "ColdLaunch129",
"scenario": "pair129",
"scenario_seed": 965460218386186365,
"scenario_file": "scenario 1 / sam s400 1.5 72 8.5 / roles s400 31 / wave 0,0,0,0,0,0,1,0,0,0,0 0 900 0 1",
"director": "/airdef replay export <name> best fps=30 size=1280x720 crf=16 sec=24",
"launch_shot_start_frame": 94,
"launch_shot_start_seconds": 3.1,
"center_region": "x 590..689, y 300..419 in 1280x720",
"center_threshold": 100.0,
"before": {
"code_commit": "dc36d67eb740e6a9fb56224b32b007e3bf2512b9",
"artifact_sha256": "2d828aa8b865c8d5e6ba52be91c4d6b380811151fb85335cac80f3cbffbd9175",
"source_mp4": "/private/tmp/issue-129-pair-base/airdef-films/pair129-before.mp4",
"source_sha256": "fdc828199666fa986effd4feafb8e90b9d2646f64f7f4d4ac1afd90de5002301",
"source_size": 17268968,
"probe": {
"programs": [],
"stream_groups": [],
"streams": [
{
"codec_name": "h264",
"width": 1280,
"height": 720,
"r_frame_rate": "30/1",
"nb_frames": "403"
},
{
"codec_name": "aac",
"sample_rate": "48000",
"r_frame_rate": "0/0",
"nb_frames": "631"
}
],
"format": {
"duration": "13.433333",
"size": "17268968"
}
},
"center_illumination_frame": 101,
"center_illumination_seconds_after_launch": 0.23333333333333334,
"launch_shot_end_frame": 151,
"cold_ticks": 5,
"cold_spec_seconds": 0.25,
"audio_rms_window_s": 0.05,
"audio_onset_threshold_rms": 0.03,
"audio_onset_s": 3.45,
"audio_onset_after_launch_s": 0.35
},
"after": {
"code_commit": "00f0209942868a10624117abb799b56407e96d5f",
"artifact_sha256": "ca3bdd305f0149f627a8d733c148525421c987c5486fc246664ad6c980c1f680",
"source_mp4": "/private/tmp/issue-129-pair-after/airdef-films/pair129-after.mp4",
"source_sha256": "fb381cce5d83cb98eb43ba35d8434bc2f3e514970cf418fd301366a14f8c80ca",
"source_size": 17832718,
"probe": {
"programs": [],
"stream_groups": [],
"streams": [
{
"codec_name": "h264",
"width": 1280,
"height": 720,
"r_frame_rate": "30/1",
"nb_frames": "412"
},
{
"codec_name": "aac",
"sample_rate": "48000",
"r_frame_rate": "0/0",
"nb_frames": "645"
}
],
"format": {
"duration": "13.733333",
"size": "17832718"
}
},
"center_illumination_frame": 121,
"center_illumination_seconds_after_launch": 0.9,
"launch_shot_end_frame": 160,
"cold_ticks": 20,
"cold_spec_seconds": 1.0,
"audio_rms_window_s": 0.05,
"audio_onset_threshold_rms": 0.03,
"audio_onset_s": 4.15,
"audio_onset_after_launch_s": 1.05,
"code_commit_note": "hmod identity 00f020994; the code is the same as 4b013fb7 (only docs changed after it)"
},
"docs_copies": {
"before_mp4": {
"path": "docs/media/cold-launch/cold-launch-129-before.mp4",
"size": 5831407,
"sha256": "ef5fb96738d5092f0282ac1c5d0ab241eb2ba8dc2114a8f466b1151b2a9c639e",
"probe": {
"programs": [],
"stream_groups": [],
"streams": [
{
"codec_name": "h264",
"width": 1280,
"height": 720,
"r_frame_rate": "30/1",
"nb_frames": "403"
},
{
"codec_name": "aac",
"sample_rate": "48000",
"r_frame_rate": "0/0",
"nb_frames": "631"
}
],
"format": {
"duration": "13.433333",
"size": "5831407"
}
}
},
"after_mp4": {
"path": "docs/media/cold-launch/cold-launch-129-after.mp4",
"size": 6137154,
"sha256": "d165b2d2ac3c79dd8c57fb1cc477e1ae5ec43ab92b8bab6e9a6a5ffe3d315d98",
"probe": {
"programs": [],
"stream_groups": [],
"streams": [
{
"codec_name": "h264",
"width": 1280,
"height": 720,
"r_frame_rate": "30/1",
"nb_frames": "412"
},
{
"codec_name": "aac",
"sample_rate": "48000",
"r_frame_rate": "0/0",
"nb_frames": "645"
}
],
"format": {
"duration": "13.733333",
"size": "6137154"
}
}
},
"note": "re-encoded h264 crf 26 for storage; frame count, frame rate, duration and AAC track preserved"
}
}
@@ -0,0 +1,27 @@
{
"audio_ms_per_tick": 50,
"audio_sha256": "8b5eeabb2585e2d8b2524a9fe992b028b2eba8c413f5c822d2a68ef352689b25",
"capture_reset": "next capture produced exact zero samples",
"channels": 2,
"command": "HORIZON_ACOUSTICS_OUT=/scratch cargo test --release --manifest-path horizon/Cargo.toml -p horizon-client --no-default-features --lib -j 2 audio::tests::export_moving_mass_raid -- --ignored --nocapture",
"fixture_commit": "e44ad82a9",
"gpu_or_windows_fps_measured": false,
"machine": "Apple M5 / macOS arm64",
"max_direct_cells_per_tick": 4056,
"max_echo_cells_per_tick": 36835,
"max_sources": 116,
"output_device": false,
"profile": "release",
"rate": 48000,
"real_mp4_checked": false,
"rust": "1.99.1",
"sample_determinism": "two full runs compared sample-for-sample in the test",
"schema": 1,
"scope": "synthetic geometry and samples through production Audio::tick_acoustics and film_mix, excludes game snapshot construction and GPU/encoder",
"seconds": 6,
"step_plus_mix_ms_max": 5.573375,
"step_plus_mix_ms_p50": 3.551625,
"step_plus_mix_ms_p95": 4.297167,
"synthetic": true,
"ticks": 120
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 816 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 MiB

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