Open the unit card from the visible model (#153)

This commit is contained in:
2026-12-01 23:43:14 +03:00
parent 5e3907aa99
commit b882dc3c2b
8 changed files with 375 additions and 15 deletions
+2
View File
@@ -203,6 +203,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру
`/airdef post Панцирь` или `/airdef post 12`. Нажатие на строку открывает карточку. В ней видны текущая причина,
отметка и её источник. Из карточки можно открыть карту, камеру, цепочки последнего повтора и закрепить технику.
Та же карточка доступна с выбранного маркера на карте **M** и по **I** при открытом мониторе **K**.
В мире от первого лица наведите прицел на видимую часть техники на расстоянии до 24 блоков и нажмите **I**.
Если между прицелом и моделью есть блок, карточка по наведению не откроется.
**Сетка камер** открывается отдельной кнопкой в списке или командой `/airdef grid`. В ней до восьми живых
камер со статусом, РЛС, прочностью и боекомплектом. Камеры подбираются по активности каждые две секунды.
+23
View File
@@ -14,6 +14,7 @@ version = "0.2.0"
dependencies = [
"airdef-core",
"glam",
"horizon-assets",
"horizon-mod-sdk",
"horizon-mods",
]
@@ -127,6 +128,22 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "horizon-assets"
version = "0.1.0"
dependencies = [
"horizon-core",
"serde",
"serde_json",
]
[[package]]
name = "horizon-core"
version = "0.1.0"
dependencies = [
"libm",
]
[[package]]
name = "horizon-mod-sdk"
version = "0.1.0"
@@ -175,6 +192,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "log"
version = "0.4.34"
+3
View File
@@ -17,6 +17,9 @@ airdef-core = { path = "../airdef-core" }
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
glam = "0.30"
[build-dependencies]
horizon-assets = { path = "../horizon/crates/horizon-assets" }
[dev-dependencies]
airdef-core = { path = "../airdef-core", features = ["test-fixtures"] }
# The host's own block tracer, so the saturation replica answers render rays exactly as the
+65
View File
@@ -0,0 +1,65 @@
use horizon_assets::{
bake::{BlockModelTransform, bake_block_model},
model::CuboidModel,
resolve::ModelLibrary,
};
use std::{collections::BTreeMap, env, fmt::Write, fs, path::PathBuf};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let models = PathBuf::from("assets/airdef/models/block");
println!("cargo:rerun-if-changed={}", models.display());
let output = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo sets OUT_DIR"));
let mut decoded = BTreeMap::new();
for entry in fs::read_dir(models)? {
let path = entry?.path();
if path.extension().is_some_and(|ext| ext == "json") {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.expect("UTF-8 model name");
let model = CuboidModel::from_json(&fs::read_to_string(&path)?)
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
decoded.insert(format!("airdef:block/{name}"), model);
}
}
// Use the same cuboid baker as the client so element rotations, omitted faces and
// model coordinates match. Include only positions, with offsets for the local AABBs.
let names: Vec<_> = decoded.keys().cloned().collect();
let library = ModelLibrary::new(decoded)?;
let transform = BlockModelTransform::new([0; 3], false);
let mut bytes = Vec::new();
let mut table = String::from("&[\n");
for name in names {
let model = library.resolve(&name)?;
let faces = bake_block_model(&model, transform)?;
if faces.is_empty() {
continue;
}
let start = bytes.len();
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for face in faces {
for position in face.positions {
for (i, coordinate) in position.into_iter().enumerate() {
let centred = coordinate - 0.5;
min[i] = min[i].min(centred);
max[i] = max[i].max(centred);
bytes.extend_from_slice(&centred.to_le_bytes());
}
}
}
let id = name.replace(":block/", ":");
let extent = std::array::from_fn::<_, 3, _>(|i| min[i].abs().max(max[i].abs()));
let radius = extent.iter().map(|value| value * value).sum::<f32>().sqrt();
writeln!(
table,
" ({id:?}, Mesh {{ min: {min:?}, max: {max:?}, radius: {radius:?}, start: {start}, end: {} }}),",
bytes.len()
)?;
}
table.push_str("]\n");
fs::write(output.join("inspect-meshes.rs"), table)?;
fs::write(output.join("inspect-faces.bin"), bytes)?;
Ok(())
}
+229
View File
@@ -0,0 +1,229 @@
//! Picking nearby AirDef models against the same block ray the client uses for its crosshair.
use crate::sim::Model;
use glam::{DVec3, Vec3};
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
pub const REACH: f32 = 24.0;
const FACE_BYTES: usize = 4 * 3 * size_of::<f32>();
const FACES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/inspect-faces.bin"));
const MESHES: &[(&str, Mesh)] = include!(concat!(env!("OUT_DIR"), "/inspect-meshes.rs"));
struct Mesh {
min: [f32; 3],
max: [f32; 3],
radius: f32,
start: usize,
end: usize,
}
pub struct Ray {
origin: DVec3,
direction: DVec3,
limit: f64,
}
impl Ray {
pub fn from_view(eye: DVec3, direction: DVec3, terrain: Option<DVec3>) -> Self {
let mut origin = eye;
let mut limit = f64::from(REACH);
if let Some(point) = terrain {
let horizontal = DVec3::new(direction.x, 0.0, direction.z);
let distance = if horizontal.length_squared() > 1e-8 {
// Feet and eye share X/Z. Recover the actual eye height from the host
// ray when it hit a block (the eye lowers while crouching or swimming).
let t = (point - eye).dot(horizontal) / horizontal.length_squared();
origin.y = point.y - direction.y * t;
t
} else {
(point - eye).dot(direction)
};
limit = distance.clamp(0.0, limit);
}
Self {
origin,
direction,
limit,
}
}
fn hits_bounds(&self, min: DVec3, max: DVec3) -> bool {
let (mut near, mut far) = (0.0f64, self.limit);
for i in 0..3 {
if self.direction[i].abs() < 1e-10 {
if self.origin[i] < min[i] || self.origin[i] > max[i] {
return false;
}
} else {
let a = (min[i] - self.origin[i]) / self.direction[i];
let b = (max[i] - self.origin[i]) / self.direction[i];
near = near.max(a.min(b));
far = far.min(a.max(b));
if near > far {
return false;
}
}
}
near < self.limit
}
fn triangle(&self, a: DVec3, b: DVec3, c: DVec3) -> Option<f64> {
let ab = b - a;
let ac = c - a;
let p = self.direction.cross(ac);
let determinant = ab.dot(p);
if determinant.abs() < 1e-10 {
return None;
}
let t = self.origin - a;
let u = t.dot(p) / determinant;
let q = t.cross(ab);
let v = self.direction.dot(q) / determinant;
let distance = ac.dot(q) / determinant;
(u >= 0.0 && v >= 0.0 && u + v <= 1.0 && distance >= 0.0 && distance < self.limit)
.then_some(distance)
}
}
/// Return the object that owns the closest visible face, including its rotated moving parts.
pub fn pick(
mut ray: Ray,
models: &[Model],
mut is_unit_model: impl FnMut(&Model) -> bool,
) -> Option<u32> {
let mut picked = None;
for model in models {
if model.glow || model.scale <= 0.0 {
continue;
}
let Ok(i) = MESHES.binary_search_by_key(&model.name, |(name, _)| *name) else {
continue;
};
let mesh = &MESHES[i].1;
let scale = f64::from(model.scale);
let reach = ray.limit + scale * f64::from(mesh.radius);
if model.at.distance_squared(ray.origin) > reach * reach || !is_unit_model(model) {
continue;
}
let unrotate = model.rotation.conjugate();
let mut local = Ray {
origin: unrotate * (ray.origin - model.at) / scale,
direction: unrotate * ray.direction / scale,
limit: ray.limit,
};
if !local.hits_bounds(
Vec3::from_array(mesh.min).as_dvec3(),
Vec3::from_array(mesh.max).as_dvec3(),
) {
continue;
}
for face in FACES[mesh.start..mesh.end].chunks_exact(FACE_BYTES) {
let [a, b, c, d] = std::array::from_fn(|vertex| {
DVec3::from_array(std::array::from_fn(|axis| {
let start = (vertex * 3 + axis) * size_of::<f32>();
let value = f32::from_le_bytes(
face[start..start + size_of::<f32>()].try_into().unwrap(),
);
f64::from(value)
}))
});
if let Some(hit) = local.triangle(a, b, c).or_else(|| local.triangle(a, c, d)) {
local.limit = hit;
picked = Some(model.object_id());
}
}
ray.limit = local.limit;
}
picked
}
pub fn hint(size: (f32, f32), text_width: f32, label: String) -> [Shape; 2] {
let (x, y) = (size.0 / 2.0, size.1 / 2.0 + 14.0);
[
Shape::Fill(FillShape {
rect: Rect {
x: x - text_width / 2.0 - 4.0,
y: y - 2.0,
w: text_width + 8.0,
h: 12.0,
},
color: 0xA0101518,
}),
Shape::Text(TextShape {
text: label,
at: Point { x, y },
color: 0xFFF0F4FA,
centered: true,
shadow: true,
}),
]
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DQuat;
fn radar(id: u32, at: DVec3) -> Model {
Model {
id,
name: "airdef:radar_truck",
at,
rotation: DQuat::from_rotation_y(0.4),
scale: 1.0,
glow: false,
}
}
#[test]
fn takes_the_closest_model_face_only_in_front_of_the_terrain() {
let eye = DVec3::new(0.0, 0.25, 0.0);
let models = [radar(16, 10.0 * DVec3::Z), radar(33, 6.0 * DVec3::Z)];
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |_| true),
Some(32)
);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, wall), &models, |_| true),
None
);
let wall_between_units = Some(DVec3::new(0.0, 0.25, 8.0));
assert_eq!(
pick(
Ray::from_view(eye, DVec3::Z, wall_between_units),
&models,
|_| true
),
Some(32)
);
assert_eq!(
pick(Ray::from_view(eye, DVec3::Z, None), &models, |m| m.id == 16),
Some(16)
);
}
#[test]
fn a_higher_visible_part_is_pickable_above_a_wall() {
let body = radar(16, 8.0 * DVec3::Z);
let antenna = Model {
name: "airdef:radar_panel",
..radar(18, DVec3::new(0.0, 1.8, 8.0))
};
let low_eye = DVec3::new(0.0, 0.25, 0.0);
let wall = Some(DVec3::new(0.0, 0.25, 3.0));
let high_eye = DVec3::new(0.0, 1.8, 0.0);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &[body], |_| true),
None
);
let models = [radar(16, 8.0 * DVec3::Z), antenna];
assert_eq!(
pick(Ray::from_view(low_eye, DVec3::Z, wall), &models, |_| true),
None
);
assert_eq!(
pick(Ray::from_view(high_eye, DVec3::Z, None), &models, |_| true),
Some(16)
);
}
}
+45 -15
View File
@@ -17,6 +17,7 @@ mod cinema;
mod capabilities;
mod engines;
mod commands;
mod inspect;
mod layout;
mod map;
pub mod film;
@@ -108,8 +109,8 @@ struct AirDef {
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,
/// The live overlays own the mod's `set-hud` until the last one goes away.
world_hud_shown: bool,
}
/// What `/airdef replay export` was asked for.
@@ -991,6 +992,20 @@ impl AirDef {
render::set_hud(&shapes);
}
fn inspect_target(&self, p: &game::Player, models: &[sim::Model]) -> Option<u32> {
if !self.presentation.is_live() || self.grid || self.map.open || self.menu.is_some()
|| self.monitor_index().is_some() || self.sim.sams.is_empty()
{
return None;
}
let block = game::raycast(inspect::REACH).map(|h| DVec3::new(h.x, h.y, h.z));
let ray = inspect::Ray::from_view(eye(p), view(p), block);
inspect::pick(ray, models, |m| {
self.model_ids.get(m.name) != Some(&None)
&& self.sim.sams.iter().any(|sam| sam.id == m.object_id())
})
}
// ------------------------------------------------ saving
/// The state as text, lines of words: the autosave's format, and the body of a scenario.
@@ -1342,7 +1357,7 @@ impl AirDef {
self.chain_view = ChainView::default();
// The overlay key lets go with the world: its camera projects nothing here anyway.
self.overlay_held = false;
self.overlay_shown = false;
self.world_hud_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.
@@ -1879,6 +1894,7 @@ impl AirDef {
}
let label = match (page, from) {
(Page::UnitChecks(_, _), _) => "К карточке",
(_, post::From::World) => "Закрыть карточку",
(_, post::From::Post) => "К списку",
(_, post::From::Map(_)) => "К карте",
(_, post::From::Monitor) => "К монитору",
@@ -2250,7 +2266,7 @@ impl Mod for AirDef {
by_id: Vec::new(),
map: map::MapUi::default(),
overlay_held: false,
overlay_shown: false,
world_hud_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.
@@ -2258,7 +2274,7 @@ impl Mod for AirDef {
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");
let _ = input::register_key("inspect", "Карточка комплекса на мониторе", "key.keyboard.i");
let _ = input::register_key("inspect", "Осмотреть комплекс", "key.keyboard.i");
let _ = input::register_key("replay", "Повтор налёта: карта / выход", "key.keyboard.r");
let _ = input::register_key("ew", "РЭБ: включить / выключить", "key.keyboard.u");
// The replay's own keys (they do nothing outside a replay).
@@ -2289,6 +2305,7 @@ impl Mod for AirDef {
self.sim.engine_tick = tick;
}
let Some(p) = player() else { return };
let mut inspect_requested = false;
for event in input::poll() {
match event {
Event::UseStart(u) => self.use_item(&u.item.id),
@@ -2319,7 +2336,7 @@ impl Mod for AirDef {
}
Event::KeyDown(k) if k == "monitor" => self.cycle_monitor(),
Event::KeyDown(k) if k == "grid" => self.open_post(),
Event::KeyDown(k) if k == "inspect" => self.open_monitor_card(),
Event::KeyDown(k) if k == "inspect" => inspect_requested = true,
Event::KeyDown(k) if k == "ew" => self.toggle_ew(),
Event::KeyDown(k) if k == "replay" => {
if self.presentation.playback().is_some() {
@@ -2452,6 +2469,14 @@ impl Mod for AirDef {
}
}
}
let aimed = self.inspect_target(&p, &out.models);
if inspect_requested && self.menu.is_none() && !self.grid && !self.map.open {
if let Some(id) = aimed {
self.open_menu(Page::Unit(id, post::From::World));
} else {
self.open_monitor_card();
}
}
self.emit(out);
self.map.sample(&self.sim);
// The map's events and shapes: at the tick's pace (a frame hook's budget is too small for it).
@@ -2470,11 +2495,11 @@ impl Mod for AirDef {
self.show_world_at(r.rec, r.time(), r.filming());
self.monitor_shown = true;
} else if self.post_open() {
if self.monitor_shown || self.overlay_shown {
if self.monitor_shown || self.world_hud_shown {
render::set_hud(&[]);
render::set_views(&[]);
self.monitor_shown = false;
self.overlay_shown = false;
self.world_hud_shown = false;
}
} else if self.grid {
let stale = self.grid_ids.iter().any(|id| !self.sim.sams.iter().any(|s| s.id == *id));
@@ -2500,14 +2525,18 @@ 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 {
self.world_hud_shown = true;
} else if let Some(id) = aimed
&& let Some(sam) = self.sim.sams.iter().find(|sam| sam.id == id)
{
let label = format!("{} · Осмотреть [I]", sam.kind.name());
render::set_hud(&inspect::hint(render::gui_size(), render::text_width(&label), label));
self.world_hud_shown = true;
} else if self.world_hud_shown {
render::set_hud(&[]);
self.overlay_shown = false;
self.world_hud_shown = false;
}
}
}
@@ -2583,6 +2612,7 @@ impl Mod for AirDef {
}
(Page::Unit(_, from), BTN_BACK) => {
match from {
post::From::World => self.close_menu(),
post::From::Post => self.open_post(),
post::From::Map(id) => self.open_unit_map(id, false),
post::From::Monitor => self.close_menu(),
@@ -2891,7 +2921,7 @@ impl Mod for AirDef {
// 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;
self.world_hud_shown = true;
}
return;
}
@@ -3379,7 +3409,7 @@ mod tests {
by_id: Vec::new(),
map: map::MapUi::default(),
overlay_held: false,
overlay_shown: false,
world_hud_shown: false,
}
}
+1
View File
@@ -62,6 +62,7 @@ impl Filter {
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum From {
World,
Post,
Map(u32),
Monitor,
+7
View File
@@ -80,6 +80,13 @@ pub struct Model {
pub glow: bool,
}
impl Model {
/// Multipart models use the IDs immediately after their owning object.
pub fn object_id(&self) -> u32 {
self.id - self.id % PARTS
}
}
pub struct Particle {
pub kind: &'static str,
pub at: DVec3,