Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LT21: detail for anything raea draws. A part's `detail` prop (<Model>, <Mesh3d>) is raea-sys-lod's reflected Detail, which each frame becomes Bevy's VisibilityRange on every mesh under the part (a glTF's meshes are its children). It is drawn between near and far metres, or between sizes on screen in px, converted for the shot's camera from its field of view and its target's height, with the part's size taken as its bounds' diagonal. Each edge cross-fades by Bevy's dither over `fade` of its distance; past the end nothing is drawn, in the view or the shadow passes; shadow: false keeps it out of the shadow maps. Checked on five spheres at minPx 30 (drawn to 133 m, culled at 302 and 617 m), a cube past its far, and four court pumps (far 3 at 5 m gone with its shadow, shadow false drawn without one). RAEA_LOD_DEBUG=1 prints each range and whether Bevy kept it in range of each camera. Mesh now finds its shape inside a fragment: shapeFromChildren and boundsFromChildren read only direct children, so <Mesh3d><><Sphere /><StandardMaterial /></></Mesh3d> was dropped from the scene without a word. Conformance: sdk/raea/conformance/detail.test.tsx.
shinyobjectzc5df492df82f
diff --git a/Cargo.lock b/Cargo.lockindex df171b92..0e6720a9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14884,6 +14884,7 @@ dependencies = ["raea-sys-grass","raea-sys-grid","raea-sys-hold",+ "raea-sys-lod","raea-sys-look","raea-sys-matchmove","raea-sys-material",@@ -15992,6 +15993,13 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-lod"+version = "0.1.0"+dependencies = [+ "bevy",+]+[[package]]name = "raea-sys-look"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex cad8a417..25ad0230 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -121,6 +121,7 @@ members = ["systems/screen","systems/matchmove","systems/grid",+ "systems/lod","systems/viewbox","systems/rendermap","systems/meshseq",diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.mdindex e5dc973d..a9f98fe4 100644--- a/docs/manual/reference/sdk/3d.md+++ b/docs/manual/reference/sdk/3d.md@@ -568,6 +568,7 @@ Bevy: `bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::look::LookMa| `look` | `"solid" \| "pixel" \| "site"` | how the model itself is drawn (the rest of the scene is unchanged): "solid" (its own surfaces, the default), "pixel" (pixel art: a cell per `pixelSize` frame pixels, outlined in `edgeColor`) or "site" (raea.io's grain: the cells' light ordered-dithered into the site's six greys). It may change from frame to frame. || `flat` | `boolean` | its surfaces without light: shape and colour alone, like a drawing (the site look keeps the light: its grain is made of it) || `shadow` | `boolean` | false: its meshes cast no shadow (true by default) |+| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) || `receiveShadow` | `boolean` | false: no shadow falls on its meshes, its own included (true by default): a furry coat of many cards that would otherwise speckle itself in the shadow maps || `pixelSize` | `number` | a cell's size in frame pixels for the pixel and site looks (6 by default) || `edgeColor` | `string` | the pixel look's one-cell outline, a hex colour ("#000000" by default), or "none" |diff --git a/docs/manual/reference/sdk/mesh.md b/docs/manual/reference/sdk/mesh.mdindex b79b4f5c..1de792a3 100644--- a/docs/manual/reference/sdk/mesh.md+++ b/docs/manual/reference/sdk/mesh.md@@ -120,6 +120,7 @@ shadow="only" draws it with the shadow-only material (engine/render shadow_only.| --- | --- | --- || `transform` | `TransformValue` | where it stands: translation, rotation (a quaternion) and scale, as Bevy's Transform || `visibility` | `"Visible" \| "Hidden" \| "Inherited"` | Bevy's Visibility: "Hidden" draws nothing; "Visible" and "Inherited" draw |+| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) || `children` | `ReactNode` | its material and child entities |Also takes the props of `MeshProps` (`animate`, `name`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`).diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.tomlindex 6d3042a5..7fd27f73 100644--- a/engine/render/Cargo.toml+++ b/engine/render/Cargo.toml@@ -56,6 +56,7 @@ raea-sys-fog-half = { path = "../../systems/fog-half" }raea-sys-volume = { path = "../../systems/volume" }# a field of grass made in tiles by distance (<Grass>)raea-sys-grass = { path = "../../systems/grass" }+raea-sys-lod = { path = "../../systems/lod" }serde_json = { version = "1", features = ["float_roundtrip"] }# the direct render's views, the 2D rows, clips' masks and the paint device (runtime/view)raea-runtime-view = { path = "../../runtime/view", optional = true }diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rsindex 6caed485..59b3e80f 100644--- a/engine/render/src/engine/raea_plugins.rs+++ b/engine/render/src/engine/raea_plugins.rs@@ -62,6 +62,7 @@ raea_plugin! {TracedAoPlugin: raea_sys_rt::passes, "Traced passes: ambient occlusion and raea GI's world probes (raea-sys-rt).";VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";+ DetailPlugin: raea_sys_lod::install, "Where each part is drawn: levels by distance or size on screen, cross-faded, draw distance and shadows left to a coarser level (raea-sys-lod, docs/realism.feature LT21).";ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";TintPlugin: raea_sys_material::tint::install, "A colour a copy over an <Instances>' surface, three's instanceColor (tint.rs).";diff --git a/sdk/raea/conformance/detail.test.tsx b/sdk/raea/conformance/detail.test.tsxnew file mode 100644index 00000000..53ad84e8--- /dev/null+++ b/sdk/raea/conformance/detail.test.tsx@@ -0,0 +1,31 @@+// docs/realism.feature LT21: a part's `detail` is raea-sys-lod's Detail on it, the mesh keeping its shape.+import { describe, expect, test } from "bun:test";+import { Cuboid, Model } from "../src/3d";+import { Mesh3d, StandardMaterial } from "@raea/render/bevy3d";+import { renderFrame } from "../src/test";++const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });+const props = (out: string, kind: string) => [...out.matchAll(new RegExp(`data-3d="${kind}" data-props="([^"]*)"`, "g"))].map((m) => JSON.parse(m[1]!.replaceAll(""", '"')));++describe("LT21: detail", () => {+ test("a Mesh3d's detail is a Detail component, every field given, and the mesh keeps its shape", () => {+ const out = html(<Mesh3d detail={{ far: 120, minPx: 4 }}><Cuboid /><StandardMaterial /></Mesh3d>);+ expect(out).toContain('data-shape="box(1, 1, 1)"');+ expect(props(out, "BevyComponent")).toEqual([{ type: "raea_sys_lod::Detail", value: { near: 0, far: 120, min_px: 4, max_px: 0, fade: 0.1, shadow: true, size: 0 } }]);+ });++ test("a Model's detail is a component inside it, and not a prop of its row", () => {+ const out = html(<Model src="a.glb" detail={{ near: 120, shadow: false }} />);+ expect(props(out, "Model")[0]).not.toHaveProperty("detail");+ expect(props(out, "BevyComponent")[0].value).toMatchObject({ near: 120, shadow: false });+ });++ test("a shape inside a fragment is the mesh's shape", () => {+ expect(html(<Mesh3d><><Cuboid /><StandardMaterial /></></Mesh3d>)).toContain('data-shape="box(1, 1, 1)"');+ });++ test("a detail that can't be is refused", () => {+ expect(() => html(<Mesh3d detail={{ near: 50, far: 20 }}><Cuboid /></Mesh3d>)).toThrow("must be past");+ expect(() => html(<Model src="a.glb" detail={{ fade: 2 }} />)).toThrow("0 to 1");+ });+});diff --git a/sdk/render/src/3d/all.ts b/sdk/render/src/3d/all.tsindex 0aa788d5..59d85d95 100644--- a/sdk/render/src/3d/all.ts+++ b/sdk/render/src/3d/all.ts@@ -4,6 +4,7 @@ export * from "./core";export * from "./materials";export * from "./lights";export * from "./model";+export * from "./detail";export * from "./effects";export * from "./volumetric";export * from "./post";diff --git a/sdk/render/src/3d/detail.tsx b/sdk/render/src/3d/detail.tsxnew file mode 100644index 00000000..ec81cb4f--- /dev/null+++ b/sdk/render/src/3d/detail.tsx@@ -0,0 +1,39 @@+// Where a part is drawn (docs/realism.feature LT21): its levels by distance or by size on screen, cross-faded, its+// draw distance and its shadow, as raea-sys-lod's Detail component on the part (systems/lod).+import { BevyComponent } from "./bevy";++/** Where a part is drawn. Distances in metres from the camera; sizes on screen are the part's size across in pixels,+ * at the camera's inside resolution, so a level looks the same at any output size. Drawn from the farther of `near`+ * and where it shrinks to `maxPx`, to the nearer of `far` and where it shrinks to `minPx`; past that it isn't drawn.+ * Levels of one thing are parts side by side, the end of one the start of the next:+ * `<Model src="a.glb" detail={{ far: 120 }} />` and `<Model src="a-far.glb" detail={{ near: 120 }} />`. */+export interface Detail {+ /** drawn from this distance, metres (0 by default) */+ near?: number;+ /** not drawn past this distance, metres (none by default) */+ far?: number;+ /** not drawn once smaller than this on screen, pixels across: a draw distance that scales with the part's size */+ minPx?: number;+ /** drawn only once smaller than this on screen, pixels across: a coarse level, after the fine one */+ maxPx?: number;+ /** each edge cross-fades over this share of its distance, half either side (0.1 by default; 0 switches at once) */+ fade?: number;+ /** false: this level casts no shadow, so a coarser level drawn for the shadows alone can (true by default) */+ shadow?: boolean;+ /** the part's size across, metres, for the sizes on screen (by default its meshes' bounds) */+ size?: number;+}++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)}`);+ 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})`);+ if (d.shadow !== undefined && typeof d.shadow !== "boolean") throw new TypeError(`${who}: detail.shadow is true or false, got ${JSON.stringify(d.shadow)}`);+ 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 };+ return <BevyComponent key="raea-detail" type="raea_sys_lod::Detail" value={value} />;+}diff --git a/sdk/render/src/3d/model.tsx b/sdk/render/src/3d/model.tsxindex a45320c1..0dcf01f5 100644--- a/sdk/render/src/3d/model.tsx+++ b/sdk/render/src/3d/model.tsx@@ -6,6 +6,7 @@ import { modelScreens, type ModelScreens } from "../screen";import { pageLayers } from "../layers";import { Place3d, useCamera3d, usePlace3d } from "../events3d";import { MeshStandardMaterialProps, PerspectiveCameraProps, Vec3, checkMaterial, checkPass, checkVec, colours, node3d, samplerSpec, type SamplerSpec } from "./all";+import { detailNode, type Detail } from "./detail";/** What a light or camera holds: Bevy's own reflected components on it (<BevyComponent>, or a generated wrapper such* as bevy_light's ShadowFilteringMethod or bevy_pbr's ScreenSpaceReflections), applied through Bevy's TypeRegistry. */@@ -222,6 +223,8 @@ export interface ModelProps {flat?: boolean;/** false: its meshes cast no shadow (true by default) */shadow?: boolean;+ /** where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) */+ detail?: Detail;/** false: no shadow falls on its meshes, its own included (true by default): a furry coat of many cards that would* otherwise speckle itself in the shadow maps */receiveShadow?: boolean;@@ -347,7 +350,8 @@ export function Model(props: ModelProps) {checkGrid("Model", p);if (props.nodes !== undefined) checkNodes(props.nodes);if (props.hide !== undefined && !(Array.isArray(props.hide) && props.hide.every((h) => typeof h === "string"))) throw new TypeError(`Model: hide is a list of node names, got ${JSON.stringify(props.hide)}`);- const kids = <InModel.Provider value={true}>{props.children}</InModel.Provider>;+ delete p.detail;+ const kids = <InModel.Provider value={true}>{props.children}{detailNode("Model", props.detail)}</InModel.Provider>;if (props.screens === undefined) return node3d("Model", p, kids);if (typeof props.screens !== "object" || props.screens === null) throw new TypeError("Model: screens maps a material's name to a screen: { monitor_screen: <Screen><Game /></Screen> }");const { specs, parts } = modelScreens("Model", props.name ?? props.src.split("/").pop()!.replace(/\.(glb|gltf)$/i, ""), props.screens);diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsxindex 90f1047a..f7dcd524 100644--- a/sdk/render/src/3d/shapes.tsx+++ b/sdk/render/src/3d/shapes.tsx@@ -1,5 +1,5 @@// Shapes and meshes: Bevy's primitives, buffer meshes, 3D text's props, and <Mesh> with its shape from its children.-import { Children, isValidElement, memo, useId, type ReactElement, type ReactNode } from "react";+import { Children, Fragment, isValidElement, memo, useId, type ReactElement, type ReactNode } from "react";import { Solid } from "../solid";import { useAnimation3d, type Keys, type Move, type TrackSpec } from "@raea/math/animate";import { Place3d, usePlace3d, usePointer3d, type LocalBounds, type PointerHandlers3d } from "../events3d";@@ -443,32 +443,25 @@ export function apply3d<T extends object>(props: T, v: Record<string, number | sreturn out as T;}+/** a mesh's element children with fragments opened: <><Sphere /><StandardMaterial /></> is the same mesh as its two */+const flat = (kids: ReactNode): ReactElement[] => Children.toArray(kids).flatMap((c) => (!isValidElement(c) ? [] : c.type === Fragment ? flat((c as ReactElement<{ children?: ReactNode }>).props.children) : [c]));+export function shapeFromChildren(children: ReactNode): string | undefined {- let found: string | undefined;- Children.forEach(children, (child) => {- if (found !== undefined || !isValidElement(child)) return;- if (child.type === Text3D) {- found = text3dShape((child as ReactElement<Text3DProps>).props);- return;- }- if (child.type === BufferMesh) {- found = bufferShape((child as ReactElement<BufferMeshProps>).props);- return;- }- const toShape = GEOMETRY_SHAPES.get(child.type);- if (toShape) found = toShape((child as ReactElement<Record<string, unknown>>).props);- });- return found;+ for (const child of flat(children)) {+ const props = child.props as Record<string, unknown>;+ const s = child.type === Text3D ? text3dShape(props as unknown as Text3DProps) : child.type === BufferMesh ? bufferShape(props as unknown as BufferMeshProps) : GEOMETRY_SHAPES.get(child.type)?.(props);+ if (s !== undefined) return s;+ }+ return undefined;}/** The first geometry child's bounds in its own space. */function boundsFromChildren(children: ReactNode): LocalBounds | undefined {- let found: LocalBounds | undefined;- Children.forEach(children, (child) => {- if (found !== undefined || !isValidElement(child)) return;- found = GEOMETRY_BOUNDS.get(child.type)?.((child as ReactElement<Record<string, unknown>>).props);- });- return found;+ for (const child of flat(children)) {+ const b = GEOMETRY_BOUNDS.get(child.type)?.(child.props as Record<string, unknown>);+ if (b !== undefined) return b;+ }+ return undefined;}/** A drawn object: a geometry child (or `shape`) and a material child, placed by position, rotation and scale. Itsdiff --git a/sdk/render/src/bevy3d/core.tsx b/sdk/render/src/bevy3d/core.tsxindex cba9fd66..ceb126fb 100644--- a/sdk/render/src/bevy3d/core.tsx+++ b/sdk/render/src/bevy3d/core.tsx@@ -1,6 +1,7 @@// Quat, Transform, Mesh3d and Camera3d.import { Children, cloneElement, isValidElement, useId, type ReactNode } from "react";import { meshLayers } from "../layers";+import { detailNode, type Detail } from "../3d/detail";import { BevyComponent, DepthOfField, Fog, dofOf, eulerOf, type DepthOfFieldProps, type FogProps, type Vec3 } from "../3d";import { AmbientLight as AmbientLight3, Mesh, OrthographicCamera, PerspectiveCamera, type MeshProps } from "../three";import { Transform as TransformComponent } from "@raea/app/bevy";@@ -181,6 +182,8 @@ export interface Mesh3dProps extends Omit<MeshProps, "position" | "rotation" | "transform?: TransformValue;/** Bevy's Visibility: "Hidden" draws nothing; "Visible" and "Inherited" draw */visibility?: "Visible" | "Hidden" | "Inherited";+ /** where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) */+ detail?: Detail;/** its material and child entities */children?: ReactNode;}@@ -194,9 +197,11 @@ export interface Mesh3dProps extends Omit<MeshProps, "position" | "rotation" | "* `layers` is its RenderLayers (a light's and a camera's too): @bevy bevy_camera::visibility::render_layers::RenderLayers* shadow="only" draws it with the shadow-only material (engine/render shadow_only.rs):* @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::shadow_only::ShadowOnlyMaterial> */-export function Mesh3d({ transform, visibility, children, ...rest }: Mesh3dProps) {+export function Mesh3d({ transform, visibility, detail, children: own, ...rest }: Mesh3dProps) {const id = useId();if (visibility === "Hidden") return null;+ // appended to the children as a list, not wrapped in a fragment: Mesh reads its shape from its own children+ const children = detail === undefined ? own : [...Children.toArray(own), detailNode("Mesh3d", detail)];const layers = meshLayers("Mesh3d", rest.name ?? `layer${id}`, children, true);const at = place(transform, rest.animate !== undefined);if (!layers.surface) return <Mesh {...rest} {...at}>{layers.children}</Mesh>;diff --git a/systems/lod/Cargo.toml b/systems/lod/Cargo.tomlnew file mode 100644index 00000000..662f7cda--- /dev/null+++ b/systems/lod/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "raea-sys-lod"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Detail by distance and size on screen: where each part is drawn, its levels cross-faded, its shadow left to a coarser level, nothing drawn past its last (docs/realism.feature LT21)"++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }diff --git a/systems/lod/src/lib.rs b/systems/lod/src/lib.rsnew file mode 100644index 00000000..7f537e6e--- /dev/null+++ b/systems/lod/src/lib.rs@@ -0,0 +1,169 @@+//! Detail by distance and size on screen (docs/realism.feature LT21). A part (a Model, a Mesh3d: anything raea draws)+//! carries a `Detail`, from a TSX `detail` prop through <BevyComponent>, saying where it is drawn. Each frame it becomes+//! Bevy's VisibilityRange on every mesh under the part (a glTF's meshes are its children, and a range acts only on the+//! entity it's on), so a level cross-fades into the next with Bevy's dither, and past its last range a part isn't drawn+//! at all, in the camera's view and in the shadow passes (they measure from the camera: raea sets ShadowLodOrigin).+//! A size on screen becomes a distance for the active 3D camera from the part's size across (its meshes' bounds), the+//! camera's vertical field of view and its target's height in pixels, so a level looks the same at any output size.+//! `shadow: false` keeps a level out of the shadow maps, for a coarser level to cast its shadow.++use bevy::{+ camera::{+ primitives::Aabb,+ visibility::{VisibilityRange, VisibilitySystems},+ },+ light::NotShadowCaster,+ prelude::*,+};++/// Where a part is drawn. Distances are metres from the camera, 0 for none; sizes on screen are the part's size across+/// in pixels, 0 for none. Drawn from the farther of `near` and the distance where it shrinks to `max_px`, to the nearer+/// of `far` and the distance where it shrinks to `min_px`. Each edge cross-fades over `fade` of its distance (0.1: 5%+/// either side). `size` is the part's size across in metres, 0 to take it from its meshes' bounds.+#[derive(Component, Reflect, Clone, Debug, PartialEq)]+#[reflect(Component, Default)]+pub struct Detail {+ pub near: f32,+ pub far: f32,+ pub min_px: f32,+ pub max_px: f32,+ pub fade: f32,+ pub shadow: bool,+ pub size: 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 }+ }+}++/// a mesh's shadow left off by its part's Detail, so only what this took away is given back+#[derive(Component)]+struct ShadowLeft;++pub fn install(app: &mut App) {+ app.register_type::<Detail>().add_systems(PostUpdate, apply.after(VisibilitySystems::CalculateBounds).after(bevy::transform::TransformSystems::Propagate).before(VisibilitySystems::CheckVisibility));+ if std::env::var_os("RAEA_LOD_DEBUG").is_some() {+ app.add_systems(PostUpdate, report.after(VisibilitySystems::CheckVisibility));+ }+}++/// 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>) {+ 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 {+ 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(" "));+ }+}++/// The distances a Detail is drawn between, for a camera `focal` pixels long (its target's height over twice the+/// tangent of half its field of view; None for an orthographic camera, where sizes on screen don't change with+/// distance and only the metres count). The end is infinite when nothing limits it.+pub fn span(d: &Detail, size: f32, focal: Option<f32>) -> (f32, f32) {+ let at = |px: f32| focal.filter(|_| px > 0.0 && size > 0.0).map(|f| size * f / px);+ let start = at(d.max_px).map_or(d.near, |s| s.max(d.near));+ let far = if d.far > 0.0 { d.far } else { f32::INFINITY };+ let end = at(d.min_px).map_or(far, |e| e.min(far));+ (start, end.max(start))+}++/// Bevy's range for a span: each edge cross-faded over `fade` of its distance, centred on it, so one level's end and+/// the next one's start fade across each other.+pub fn range(start: f32, end: f32, fade: f32, use_aabb: bool) -> VisibilityRange {+ let h = fade.clamp(0.0, 1.0) * 0.5;+ let e = if end.is_finite() { end * (1.0 - h)..end * (1.0 + h) } else { f32::MAX..f32::MAX };+ let s = if start > 0.0 { start * (1.0 - h)..start * (1.0 + h) } else { 0.0..0.0 };+ VisibilityRange { start_margin: s.start.min(e.start)..s.end.min(e.start), end_margin: e, use_aabb }+}++type MeshRow<'a> = (&'a GlobalTransform, Option<&'a Aabb>, Option<&'a VisibilityRange>, Has<NotShadowCaster>, Has<ShadowLeft>);++fn apply(cams: Query<(&Camera, &Projection, Has<bevy::camera::ShadowLodOrigin>), With<Camera3d>>, parts: Query<(Entity, &Detail)>, children: Query<&Children>, meshes: Query<MeshRow, With<Mesh3d>>, mut commands: Commands) {+ // the shot's camera (raea gives it the shadow LOD origin), else the first active 3D one: a range is one per mesh,+ // so sizes on screen are measured for one camera+ let shot = cams.iter().filter(|(c, ..)| c.is_active).max_by_key(|(.., origin)| *origin);+ let focal = shot.and_then(|(c, p, _)| match p {+ Projection::Perspective(p) => c.physical_target_size().map(|s| s.y as f32 / (2.0 * (p.fov * 0.5).tan())),+ _ => None,+ });+ for (part, d) in &parts {+ let found: Vec<Entity> = std::iter::once(part).chain(children.iter_descendants(part)).filter(|e| meshes.contains(*e)).collect();+ if found.is_empty() {+ continue;+ }+ let size = if d.size > 0.0 { d.size } else { across(&found, &meshes) };+ let (start, end) = span(d, size, focal);+ for e in found {+ let Ok((_, aabb, now, no_shadow, ours)) = meshes.get(e) else { continue };+ // measured from the mesh's origin, unless that lies outside its own bounds (a mesh baked in world+ // coordinates, as the city's tiles are): then from its bounds' centre+ let use_aabb = aabb.is_some_and(|a| a.center.length() > a.half_extents.length());+ let want = range(start, end, d.fade, use_aabb);+ if now != Some(&want) {+ commands.entity(e).insert(want);+ }+ match (d.shadow, no_shadow, ours) {+ (false, false, _) => {+ commands.entity(e).insert((NotShadowCaster, ShadowLeft));+ }+ (true, true, true) => {+ commands.entity(e).remove::<(NotShadowCaster, ShadowLeft)>();+ }+ _ => {}+ }+ }+ }+}++/// the meshes' bounds together, in the world, as a size across (their box's diagonal); 0 before any has bounds+fn across(found: &[Entity], meshes: &Query<MeshRow, With<Mesh3d>>) -> f32 {+ let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));+ for (gt, aabb, ..) in found.iter().filter_map(|e| meshes.get(*e).ok()) {+ let Some(a) = aabb else { continue };+ let m = gt.affine();+ let c = m.transform_point3(Vec3::from(a.center));+ let h = Vec3::from(m.matrix3.x_axis.abs() * a.half_extents.x + m.matrix3.y_axis.abs() * a.half_extents.y + m.matrix3.z_axis.abs() * a.half_extents.z);+ lo = lo.min(c - h);+ hi = hi.max(c + h);+ }+ if lo.x > hi.x { 0.0 } else { (hi - lo).length() }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn metres_alone_are_kept() {+ let d = Detail { near: 10.0, far: 120.0, ..default() };+ assert_eq!(span(&d, 5.0, Some(1000.0)), (10.0, 120.0));+ }++ #[test]+ fn a_size_on_screen_becomes_a_distance() {+ // 4 m across, a 1000 px focal length: 40 px at 100 m, 4 px at 1000 m+ let d = Detail { min_px: 4.0, max_px: 40.0, ..default() };+ let (s, e) = span(&d, 4.0, Some(1000.0));+ assert!((s - 100.0).abs() < 1e-3 && (e - 1000.0).abs() < 1e-3);+ // an orthographic camera keeps only the metres+ assert_eq!(span(&d, 4.0, None), (0.0, f32::INFINITY));+ }++ #[test]+ fn the_nearer_end_and_the_farther_start_win() {+ let d = Detail { near: 150.0, far: 500.0, min_px: 4.0, max_px: 40.0, ..default() };+ assert_eq!(span(&d, 4.0, Some(1000.0)), (150.0, 500.0));+ }++ #[test]+ fn one_levels_end_fades_across_the_next_ones_start() {+ let a = range(0.0, 120.0, 0.1, false);+ let b = range(120.0, 700.0, 0.1, false);+ assert_eq!(a.end_margin, b.start_margin);+ assert!((a.end_margin.start - 114.0).abs() < 1e-3 && (a.end_margin.end - 126.0).abs() < 1e-3);+ assert_eq!(range(0.0, f32::INFINITY, 0.1, false).end_margin, f32::MAX..f32::MAX);+ }+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 7e76bb4d..57ac4d2e 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -111,6 +111,7 @@ raea-sys-grab = "systems"raea-sys-splat = "systems"raea-sys-sprite = "systems"raea-sys-rt = "systems"+raea-sys-lod = "systems"raea-sys-text3d = "systems"raea-runtime-gpuframe = "runtime"raea-runtime-scene3d = "runtime"