LT21: a part's Detail can name the box it is measured to, so a thing's levels switch at one distance

A Detail with edge measured each level to its own meshes' bounds. A city tile's levels overhang the tile by up to
100 m, and each level reaches differently. The code holding the levels measured to the tile's map box, so the two
disagreed by up to 62 m. On the 540p detail fly a tile's LOD2 faded out by its bounds with LOD1 not yet held
(raea had it 90% faded in), the sky showed through it, and LOD1 then appeared at once in frame 35.

Detail's bounds (TSX detail.box, six numbers 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, and code holding levels by
distance can measure exactly as raea does. RAEA_LOD_DEBUG's report now names each range's part and gives the frame,
each mesh's bounds and inherited visibility, and a hidden mesh's ancestors. Any value but 1 or time keeps only the
parts whose name holds it. That is how the hidden LOD1 was found.

With every tile measured to one box (gambit's City), the fly's frame 35 goes from 29 popped 8x8 tiles to 2, frame
226 from 12 to none, and the shot from 199 to 160. The rest were there before. It changes what is drawn at a
distance, not light or shading, and no LT1 scene draws a Detail, so LT1's numbers are unchanged. lod tests: 8 pass.
This commit is contained in:
shinyobjectz committed 2026-11-22 09:15:58 -08:00
1 parent da31c4b3c6
commit ca161bcb73
2 files changed
+48 -10

No files matched your search

+7 -2
View File
@@ -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 <BevyComponent key="raea-detail" type="raea_sys_lod::Detail" value={value} />;
}
+41 -8
View File
@@ -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<f32>,
}
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<LodTime>, changed: Query<(), Changed<Detail>>, 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<Camera>, With<bevy::camera::ShadowLodOrigin>)>>, ranged: Query<(Entity, &VisibilityRange, &GlobalTransform, &ViewVisibility)>, ranges: Res<bevy::camera::visibility::VisibleEntityRanges>) {
/// 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<Camera>, With<bevy::camera::ShadowLodOrigin>)>>, ranged: Query<(Entity, &VisibilityRange, &GlobalTransform, &ViewVisibility, &InheritedVisibility, Option<&Aabb>)>, ranges: Res<bevy::camera::visibility::VisibleEntityRanges>, parents: Query<&ChildOf>, named: Query<&Name, With<Detail>>, frame: Res<bevy::diagnostic::FrameCount>, 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<String> = 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::<Vec<_>>().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<bevy::camera::
continue;
}
if walk || at.is_changed() {
h.bounds = bounds(&h.meshes, &meshes);
h.bounds = given(d, &at).or_else(|| bounds(&h.meshes, &meshes));
h.outside = h.meshes.iter().filter_map(|e| meshes.get(*e).ok()).any(|(_, a, ..)| a.is_some_and(outside));
}
let size = if d.size > 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<MeshRow, With<Mesh3d>>) -> 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<MeshRow, With<Mesh3d>>) -> 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() };