From 502d94c52847f29dbf2192395a66f314c007c1f0 Mon Sep 17 00:00:00 2001 From: chexit Date: Sat, 21 Nov 2026 08:56:36 +0300 Subject: [PATCH] Spend the world overlay's marker budget on targets in frame (#141) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The overlay clipped the network's tracks to the nearest 64 by distance before projecting them, and the truth and interceptor layers the same way. A crowd behind the camera filled the budget, so a raid could show nothing even with a target right in front of the player; the native reproduction (one contact ahead, 64 behind) came out with zero markers and a header saying all 65 were out of frame. Now visibility comes before the draw budget. Each layer orders its candidates nearest first, projects at most MAX_SCAN = 4 x MAX_MARKERS of them (bounded work, no sort of the whole picture beyond that prefix), skips those the frame does not hold without spending a marker, and draws the nearest MAX_MARKERS visible ones. Each layer keeps its own draw budget, so the interceptors and the truth markers cannot crowd out the network's. The header separates the two ways a target stays unmarked: "за кадром" (behind the camera or past an edge) and "сверх бюджета" (past the scan or draw budget), alongside "в кадре". Regression tests: 64 behind plus one ahead for the network, truth and interceptor layers; a mixed crowd proving the nearest visible keep the markers and the farthest is budget-capped, not offscreen; the projection count bounded by MAX_SCAN; every case stays inside the HUD's 1024 shapes. Co-Authored-By: Kimi Code --- README.md | 4 +- airdef-mod/src/overlay.rs | 213 +++++++++++++++++++++++++++++++------- 2 files changed, 178 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 3ea9723..f3a5a05 100644 --- a/README.md +++ b/README.md @@ -193,7 +193,9 @@ API мода `render.set-lights` (до 512, плавно интерполиру трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил -клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`, +клавишу — метки исчезли. Метки достаются ближайшим из видимых целей: цель за камерой или за краем +экрана бюджет кадра не тратит, а заголовок показывает, сколько целей в кадре, сколько за кадром и сколько +не поместилось в бюджет. Метки проектируются через камеру последнего отрисованного кадра (`render.project`, API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется. **Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто diff --git a/airdef-mod/src/overlay.rs b/airdef-mod/src/overlay.rs index 38c1264..fbc3bc8 100644 --- a/airdef-mod/src/overlay.rs +++ b/airdef-mod/src/overlay.rs @@ -5,14 +5,22 @@ //! 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. +//! Visibility comes before the draw budget (#141): each layer projects at most a bounded number +//! of its nearest candidates, keeps the markers of the nearest visible ones, and counts a target +//! that leaves the frame without spending a slot. use crate::panel::distance; use crate::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. +/// The most markers of one picture (the network's, the truth's and the interceptors' each): a full +/// raid still fits the HUD's 1024 shapes — a marker is four sides and a label. const MAX_MARKERS: usize = 64; +/// The most candidates of one layer the frame looks at: the nearest ones by distance. The draw +/// budget is spent on what is in frame, but the projection work stays bounded — a crowd the frame +/// does not hold cannot buy an unbounded scan, and what the scan never reaches counts as past the +/// budget rather than out of the frame. +const MAX_SCAN: usize = 4 * MAX_MARKERS; /// A marker's side thickness, pixels. const LINE: f32 = 1.0; /// A label line's height (the HUD font with its shadow). @@ -86,6 +94,50 @@ fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 { } } +/// What one layer shows this frame: the markers to draw (the nearest visible candidates), how +/// many of the scanned candidates left the frame, and how many the budgets left out. +struct Pick { + marks: Vec<(T, Point, f32)>, + offscreen: usize, + capped: usize, +} + +/// The markers one layer gets this frame. The candidates are ordered nearest the player first and +/// at most [`MAX_SCAN`] of them are projected; a candidate the frame does not hold (behind the +/// camera or past an edge) is counted and its slot stays free for the next, so the nearest +/// [`MAX_MARKERS`] visible candidates are drawn. Work stays bounded by the scan, not the picture. +fn pick( + items: impl Iterator, + at: impl Fn(T) -> DVec3, + half_at: impl Fn(T) -> f32, + player: DVec3, + gui: (f32, f32), + project: &impl Fn(DVec3) -> Option, +) -> Pick { + let near = |a: &T, b: &T| at(*a).distance(player).total_cmp(&at(*b).distance(player)); + let mut items: Vec = items.collect(); + let total = items.len(); + // Only the nearest candidates are ever projected: no sort of the whole picture is needed. + if items.len() > MAX_SCAN { + items.select_nth_unstable_by(MAX_SCAN, near); + items.truncate(MAX_SCAN); + } + items.sort_by(near); + let mut marks = Vec::new(); + let mut offscreen = 0usize; + for it in items { + if marks.len() >= MAX_MARKERS { + break; + } + let h = half_at(it); + match project(at(it)) { + Some(p) if p.x >= h && p.x <= gui.0 - h && p.y >= h && p.y <= gui.1 - h => marks.push((it, p, h)), + _ => offscreen += 1, + } + } + Pick { capped: total - marks.len() - offscreen, marks, offscreen } +} + /// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn /// 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. @@ -97,20 +149,17 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) - 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))); + // The frame's counts: what got a marker and what did not — out of the frame (behind the camera + // or past an edge) or past the budget. The header keeps the two apart (#141). 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; - } + let mut offscreen = 0usize; + let mut capped = 0usize; + // The network's tracks: the nearest visible keep the markers; a target behind the camera no + // longer spends one, so a crowd behind cannot crowd out the target in frame. + let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project); + offscreen += net.offscreen; + capped += net.capped; + for (t, p, h) in net.marks { // 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) @@ -128,16 +177,17 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) - // with the actual type the network never shows. A tracked drone wears both: the network's // 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; - } + let real = pick( + sim.drones.iter().filter(|d| d.alive()), + |d| d.pos, + |d| half(d.pos.distance(player)) + 2.0, + player, + gui, + &project, + ); + offscreen += real.offscreen; + capped += real.capped; + for (d, p, h) in real.marks { 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)); @@ -145,24 +195,18 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) - } } // The player's own interceptors: small yellow squares, no label — they are not targets, and - // the 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; - } + // the network never hid them (the radar has always shown them). They keep their own budget. + let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project); + for (_, p, h) in own.marks { 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. + // explicitly marked. The counts say what the frame holds, what left it, and what the budget cut. + let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}"); let head = if truth { - format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}") + format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}") } else { - format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}") + format!("ОБЗОР · данные сети РЛС · {counts}") }; s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true)); s @@ -201,6 +245,17 @@ mod tests { }).collect() } + fn head(shapes: &[Shape]) -> String { + texts(shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).expect("no header").text.clone() + } + + /// `n` targets in a row right behind the camera, each nearer than anything the tests put ahead. + fn crowd_behind(sim: &mut Sim, n: u32) { + for i in 0..n { + sim.launch(DroneKind::Shahed, DVec3::new(i as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default()); + } + } + #[test] 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)); @@ -282,6 +337,88 @@ mod tests { assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS); } + /// #141: 64 targets behind the camera and one in frame. The budget used to be spent on the + /// crowd before the visibility check, so the picture came out empty; the target in frame must + /// keep its marker, and the crowd is out of frame, not past the budget. + #[test] + fn a_crowd_behind_the_camera_leaves_the_network_budget_to_the_target_in_frame() { + let mut sim = Sim::new(1); + crowd_behind(&mut sim, 64); + sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default()); + let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead); + assert_eq!(fills(&shapes, RED), 4, "the target in frame got no marker"); + assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 1, за кадром 64, сверх бюджета 0"); + assert!(shapes.len() <= 1024, "{} shapes", shapes.len()); + } + + /// The truth layer keeps its own budget the same way: the real drone in frame is drawn, the + /// crowd behind the camera costs no white marker. + #[test] + fn a_crowd_behind_the_camera_leaves_the_truth_budget_to_the_target_in_frame() { + let mut sim = Sim::new(1); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0)); + sim.truth = true; + crowd_behind(&mut sim, 64); + sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default()); + let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead); + assert_eq!(fills(&shapes, WHITE), 4, "the drone in frame got no truth marker"); + assert_eq!(fills(&shapes, RED), 0, "the network drew a track it does not hold"); + assert_eq!(head(&shapes), "ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре 1, за кадром 64, сверх бюджета 0"); + assert!(shapes.len() <= 1024, "{} shapes", shapes.len()); + } + + /// The interceptors keep their own budget too: a salvo behind the camera leaves the marker + /// to the one in frame. + #[test] + fn a_crowd_behind_the_camera_leaves_the_interceptor_budget_to_the_one_in_frame() { + let mut sim = Sim::new(1); + for i in 0..64 { + sim.missiles.push(crate::sim::Missile::test_at(i + 1, DVec3::new(i as f64, 64.0, -50.0), 0)); + } + sim.missiles.push(crate::sim::Missile::test_at(100, DVec3::new(0.0, 64.0, 100.0), 0)); + let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead); + assert_eq!(fills(&shapes, MISSILE), 4, "the interceptor in frame got no marker"); + assert!(shapes.len() <= 1024, "{} shapes", shapes.len()); + } + + /// The header tells what really left the frame from what the draw budget cut, and the markers + /// go to the nearest of the visible: 64 behind the camera, 65 in frame. + #[test] + fn the_header_separates_the_frames_edge_from_the_draw_budget() { + let mut sim = Sim::new(1); + crowd_behind(&mut sim, 64); + for i in 0..65 { + let z = 100.0 + i as f64 * 10.0; + sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, z), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default()); + } + let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead); + // The 64 nearest in frame are drawn; the farthest one is past the draw budget, not out of frame. + assert_eq!(fills(&shapes, RED), 4 * MAX_MARKERS); + assert!(texts(&shapes).iter().any(|t| t.text.contains("100 м")), "the nearest visible lost its marker"); + assert!(!texts(&shapes).iter().any(|t| t.text.contains("740 м")), "the farthest visible took a nearer one's marker"); + assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 64, за кадром 64, сверх бюджета 1"); + assert!(shapes.len() <= 1024, "{} shapes", shapes.len()); + } + + /// The projection work itself is bounded: with more candidates than the scan budget, only the + /// nearest `MAX_SCAN` are looked at, and the rest are counted as past the budget. + #[test] + fn the_projection_work_is_bounded_by_the_scan_budget() { + let mut sim = Sim::new(1); + for i in 0..1000 { + sim.launch(DroneKind::Shahed, DVec3::new((i % 100) as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default()); + } + let calls = std::cell::Cell::new(0usize); + let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, |p| { + calls.set(calls.get() + 1); + ahead(p) + }); + assert_eq!(calls.get(), MAX_SCAN, "one layer projected more than its scan budget"); + assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 0, за кадром 256, сверх бюджета 744"); + assert!(shapes.len() <= 1024, "{} shapes", shapes.len()); + } + #[test] fn interceptors_wear_small_yellow_squares_without_labels() { let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));