diff --git a/sdk/render/src/3d/detail.tsx b/sdk/render/src/3d/detail.tsx index f349f2a6..ecfd82f1 100644 --- a/sdk/render/src/3d/detail.tsx +++ b/sdk/render/src/3d/detail.tsx @@ -25,6 +25,10 @@ export interface Detail { /** true: the distances are to its nearest edge, not its middle: a big part a camera stands in or beside (a city's * tile, a terrain chunk), whose middle can be hundreds of metres from where the camera is (false by default) */ edge?: boolean; + /** the box its distances are measured to and its size taken from, in the part's own space: [x0, y0, z0, x1, y1, z1] + * (by default its meshes' bounds). Levels of one thing given one box switch at one distance however far each + * level's meshes reach, and code that holds levels by distance can measure exactly as raea does */ + box?: [number, number, number, number, number, number]; } const NUMS = ["near", "far", "minPx", "maxPx", "fade", "size"] as const; @@ -32,11 +36,12 @@ const NUMS = ["near", "far", "minPx", "maxPx", "fade", "size"] as const; /** a part's `detail` checked and made raea-sys-lod's component, every field given (raea reads a struct whole) */ export function detailNode(who: string, d: Detail | undefined) { if (d === undefined) return null; - if (typeof d !== "object" || d === null) throw new TypeError(`${who}: detail is { near, far, minPx, maxPx, fade, shadow, size }, got ${JSON.stringify(d)}`); + if (typeof d !== "object" || d === null) throw new TypeError(`${who}: detail is { near, far, minPx, maxPx, fade, shadow, size, edge, box }, got ${JSON.stringify(d)}`); for (const k of NUMS) if (d[k] !== undefined && !(Number.isFinite(d[k]) && (d[k] as number) >= 0)) throw new RangeError(`${who}: detail.${k} is 0 or more, got ${d[k]}`); if (d.fade !== undefined && d.fade > 1) throw new RangeError(`${who}: detail.fade is a share of the distance, 0 to 1, got ${d.fade}`); if (d.far !== undefined && d.near !== undefined && d.far > 0 && d.far <= d.near) throw new RangeError(`${who}: detail.far (${d.far}) must be past detail.near (${d.near})`); for (const k of ["shadow", "edge"] as const) if (d[k] !== undefined && typeof d[k] !== "boolean") throw new TypeError(`${who}: detail.${k} is true or false, got ${JSON.stringify(d[k])}`); - const value = { near: d.near ?? 0, far: d.far ?? 0, min_px: d.minPx ?? 0, max_px: d.maxPx ?? 0, fade: d.fade ?? 0.1, shadow: d.shadow ?? true, size: d.size ?? 0, edge: d.edge ?? false }; + if (d.box !== undefined && !(Array.isArray(d.box) && d.box.length === 6 && d.box.every(Number.isFinite) && d.box[0] <= d.box[3] && d.box[1] <= d.box[4] && d.box[2] <= d.box[5])) throw new RangeError(`${who}: detail.box is [x0, y0, z0, x1, y1, z1], each low corner at or below its high one, got ${JSON.stringify(d.box)}`); + const value = { near: d.near ?? 0, far: d.far ?? 0, min_px: d.minPx ?? 0, max_px: d.maxPx ?? 0, fade: d.fade ?? 0.1, shadow: d.shadow ?? true, size: d.size ?? 0, edge: d.edge ?? false, bounds: d.box ?? [] }; return ; } diff --git a/systems/lod/src/lib.rs b/systems/lod/src/lib.rs index 20334d72..34628990 100644 --- a/systems/lod/src/lib.rs +++ b/systems/lod/src/lib.rs @@ -26,7 +26,10 @@ use bevy::{ /// distances to the part's nearest edge rather than its middle: a big part (a city's tile, a terrain chunk) whose /// middle is far from a camera standing in it. Bevy measures to one point, so each mesh's range is shifted every frame /// by the gap between that point and the part's nearest edge, exact for the shot's camera (and its shadow passes, -/// which measure from it). +/// which measure from it). `bounds`, six numbers (the low corner, then the high, in the part's own space), is the box +/// the part is measured to and sized by in place of its meshes': a thing's levels given one box switch at one distance +/// however far each level's meshes reach, and a caller holding levels by distance can measure exactly as raea does +/// (City's tiles: a level's buildings overhang its tile by up to 100 m, and its LOD1 and LOD2 differ). #[derive(Component, Reflect, Clone, Debug, PartialEq)] #[reflect(Component, Default)] pub struct Detail { @@ -38,11 +41,12 @@ pub struct Detail { pub shadow: bool, pub size: f32, pub edge: bool, + pub bounds: Vec, } impl Default for Detail { fn default() -> Self { - Self { near: 0.0, far: 0.0, min_px: 0.0, max_px: 0.0, fade: 0.1, shadow: true, size: 0.0, edge: false } + Self { near: 0.0, far: 0.0, min_px: 0.0, max_px: 0.0, fade: 0.1, shadow: true, size: 0.0, edge: false, bounds: vec![] } } } @@ -79,13 +83,24 @@ fn timed(mut t: ResMut, changed: Query<(), Changed>, parts: Que } } -/// RAEA_LOD_DEBUG=1: each range's distances and whether Bevy kept it in range of each camera, on stderr -fn report(views: Query<(Entity, Option<&Camera>, &GlobalTransform), Or<(With, With)>>, ranged: Query<(Entity, &VisibilityRange, &GlobalTransform, &ViewVisibility)>, ranges: Res) { +/// RAEA_LOD_DEBUG=1: each range's distances and whether Bevy kept it in range of each camera, on stderr, each named by +/// its part (the nearest ancestor with a Detail and a Name); any other value but `time` reports only the parts whose +/// name holds it (RAEA_LOD_DEBUG=tile-) +#[allow(clippy::type_complexity)] +fn report(views: Query<(Entity, Option<&Camera>, &GlobalTransform), Or<(With, With)>>, ranged: Query<(Entity, &VisibilityRange, &GlobalTransform, &ViewVisibility, &InheritedVisibility, Option<&Aabb>)>, ranges: Res, parents: Query<&ChildOf>, named: Query<&Name, With>, frame: Res, vis: Query<(Option<&Visibility>, Option<&InheritedVisibility>, Option<&Name>)>) { + let only = std::env::var("RAEA_LOD_DEBUG").ok().filter(|v| v != "1"); let cams: Vec<_> = views.iter().collect(); - eprintln!("raea lod: {} views ({} active cameras)", cams.len(), cams.iter().filter(|(_, c, _)| c.is_some_and(|c| c.is_active)).count()); - for (e, r, gt, vv) in &ranged { + eprintln!("raea lod: frame {} {} views ({} active cameras)", frame.0, cams.len(), cams.iter().filter(|(_, c, _)| c.is_some_and(|c| c.is_active)).count()); + for (e, r, gt, vv, iv, aabb) in &ranged { + let part = std::iter::once(e).chain(parents.iter_ancestors(e)).find_map(|a| named.get(a).ok()).map_or("-", |n| n.as_str()); + if only.as_deref().is_some_and(|o| !part.contains(o)) { + continue; + } let seen: Vec = cams.iter().map(|(v, c, at)| format!("{v}{}:{:.1}m:{}", if c.is_some_and(|c| c.is_active) { "*" } else { "" }, at.translation().distance(gt.translation()), ranges.entity_is_in_range_of_view(e, *v))).collect(); - eprintln!("raea lod: {e} {:?}..{:?} shown={} {}", r.start_margin, r.end_margin, vv.get(), seen.join(" ")); + let bounds = aabb.map_or("-".to_string(), |a| format!("{:.0?}±{:.0?}", Vec3::from(a.center), Vec3::from(a.half_extents))); + // a hidden mesh: each ancestor's own visibility and what it inherited, up to the first that sees + let chain: String = if iv.get() { String::new() } else { parents.iter_ancestors(e).take(8).map(|a| vis.get(a).map_or(format!("{a}:?"), |(v, i, n)| format!("{a}:{}:{:?}:{:?}", n.map_or("", |n| n.as_str()), v, i.map(|i| i.get())))).collect::>().join(" < ") }; + eprintln!("raea lod: {part} {e} {:?}..{:?} shown={} inherited={} {} box={bounds} {chain}", r.start_margin, r.end_margin, vv.get(), iv.get(), seen.join(" ")); } } @@ -181,7 +196,7 @@ fn apply(cams: Query<(&Camera, &Projection, &GlobalTransform, Has 0.0 { d.size } else { h.bounds.map_or(0.0, |(lo, hi)| (hi - lo).length()) }; @@ -241,6 +256,14 @@ fn outside(a: &Aabb) -> bool { a.center.length() > a.half_extents.length() } +/// a Detail's own `bounds`, in the world (its eight corners through the part's transform), when it gives six numbers +fn given(d: &Detail, at: &GlobalTransform) -> Option<(Vec3, Vec3)> { + let [x0, y0, z0, x1, y1, z1] = d.bounds[..] else { return None }; + let m = at.affine(); + let corners = (0..8).map(|i| m.transform_point3(Vec3::new([x0, x1][i & 1], [y0, y1][(i >> 1) & 1], [z0, z1][i >> 2]))); + Some(corners.fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), c| (lo.min(c), hi.max(c)))) +} + /// the meshes' bounds together, in the world; None before any has bounds fn bounds(found: &[Entity], meshes: &Query>) -> Option<(Vec3, Vec3)> { let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); @@ -259,6 +282,16 @@ fn bounds(found: &[Entity], meshes: &Query>) -> Option<(Ve mod tests { use super::*; + /// A part's own box goes through its transform, corner by corner; without six numbers its meshes' are used. + #[test] + fn a_given_box_is_measured_in_the_world() { + let d = Detail { bounds: vec![0.0, 0.0, 0.0, 10.0, 2.0, 4.0], ..default() }; + let at = GlobalTransform::from(Transform::from_xyz(100.0, 0.0, 0.0).with_rotation(Quat::from_rotation_y(std::f32::consts::FRAC_PI_2))); + let (lo, hi) = given(&d, &at).unwrap(); + assert!(lo.abs_diff_eq(Vec3::new(100.0, 0.0, -10.0), 1e-4) && hi.abs_diff_eq(Vec3::new(104.0, 2.0, 0.0), 1e-4), "{lo} {hi}"); + assert!(given(&Detail::default(), &at).is_none()); + } + #[test] fn metres_alone_are_kept() { let d = Detail { near: 10.0, far: 120.0, ..default() };