The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
A posed rigid model is its parts' instances (#173)
Yujia7607447cc5de
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 460e214..daf3b28 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2776,6 +2776,33 @@ in-place tests' world, rows given back; two models in a shared pose posed again(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emittingsection that is not its first, the model a unit under software traversal).+**A posed rigid model is its parts' instances (2026-11-20).** A model posed by a clip that moves nodes, without+skins, was built in two ways at once: the nodes the clip leaves alone flattened into world-space triangles a+placement, each node it moves an instance of a mesh made a placement. Now the model is parts (`scene::RigidModel`),+each an instance of a mesh every placement of the model with the clip shares: the nodes left alone merged into one+mesh in the model's space, each moved node a mesh in its own. Nothing of it is flattened (but what+`flatten_coincident` takes out).+A movable one moved in place left the nodes its clip does not move where they were built: they move with the object+now (`repose_rigid`), and one that is not movable moves in place the same way. The part left alone has still+emitters, in the light tree, until the object first moves; that move makes them moving ones, as a still mesh's+first move does (`emitters_start_moving`).+Measured: every node an instance of a mesh of its own (no part merged; `THREERT_RIGID_NODES=all`) costs 4 % of GPU+time a frame on a street of 1,300 nodes and 8 to 10 % on an interior of 7,300, four alternated pairs each, so the+nodes that do not move relative to each other are merged. With them merged, against the build before: the street++0.2 to +1.1 % (six pairs), the interior -0.5 and -0.7 %, ten other scenes within 1.0 %. The two scenes hold+2.8 M and 3.5 M triangles fewer in world space; meshes, instances and memory otherwise as before.+Tried and set right: the part left alone with moving emitters from the build where the object is movable. An+interior's six thousand emitters were then sampled without the light tree: 7 % faster and worse against its+reference (two pairs).+Still a rebuild: such a model hidden, shown, removed or placed a second time; a pose change under software+traversal. Two nodes of one mesh of the file do not share it.+Tests: the parts' meshes shared by two placements, the part left alone in the model's space; a new pose, a move,+both at once, a move of one that is not movable, each against a build's light list and picture; a new pose of a+model under two groups (the build's product of its transforms and an update's differ in their last bits: it is+not taken for moved); the floor under a+panel on a node its clip leaves alone (`geometry/emitter-rigid`), and under one moved 300 m in place with its clip+playing (`geometry/emitter-rigid-moved-live`: it read nothing before).+**Materials are edited through the rows (2026-11-19, the material on the instance, third part).** With amaterial on its instances' rows, what changes one is no longer the triangles' business. In place now, each arebuild before:diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 156ab23..92b847a 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1193,8 +1193,9 @@ its BLASes, or the units), so the engine's path is the same under both traversal| a mesh is removed | its record cleared, its tree given back and filled, the top tree |The scene is rebuilt, as before this step, by: the first instanced mesh of a scene that has none (its kernel has no-unit walk: one rebuild, as hardware traversal's first instance is); an edit of a procedural object; a posed model or-a rigid group's pose (their triangles are in the still tree); an instance of a mesh that deforms; **room that is+unit walk: one rebuild, as hardware traversal's first instance is); an edit of a procedural object; a posed model's+pose (its triangles are in the still tree) and a rigid group's (its parts are units, placed again by a rebuild+still); an instance of a mesh that deforms; **room that isfull** (the edit room and the tree ranges are sized at the build, a quarter of the scene and at least 65,536triangles and 1,024 records, and do not grow under software traversal: under hardware traversal they do; what anedit replaces stays behind until the next rebuild, under both; a scene with units and no geometry of its own todiff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex 123b49a..a836960 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -877,42 +877,51 @@ impl LiveCore {if !sub.iter().all(held) {return false;}- let LoadedScene { tables, instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;+ let mut started = vec![];for k in sub {- let Some(scene::Draw::Instance(i)) = tables.retained.proxies.get_mut(&k).map(|p| &mut p.draw) else { continue };+ let Some(scene::Draw::Instance(i)) = self.sc.tables.retained.proxies.get_mut(&k).map(|p| &mut p.draw) else { continue };if std::mem::replace(&mut i.moves, true) {continue;}- let r = i.instance;- let old = emitter_run(&tables.emitter_tris, instances, r);- if old.is_empty() || tables.emitter_tris[old.clone()].iter().all(|e| e.moves) {- continue;- }- let (was, first) = (old.start as u32, tables.emitter_tris.len() as u32);- let inst = &mut instances[r as usize];// (Where this commit's move places it: `move_instances`, next.)- let (to, _) = scene::placed_world(world.world_matrix(k), inst.world.w_axis.truncate());- for j in old {- let e = crate::EmitterTri { moves: true, in_tree: false, ..tables.emitter_tris[j] };- tables.emitter_tris[j].area = 0.0;- let w = pool_tris[e.tri as usize - edit.pool_first].map(|v| glam::Vec3A::from(to.transform_point3(v.into())));- self.pending_emitters.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));- tables.emitter_tris.push(e);- }- inst.first_emitter = first;- // (Its rows say where its sections' emitters start: where the run is now.)- let at = inst.rows as usize..inst.rows as usize + meshes[inst.mesh as usize].sect_count as usize;- for row in rows[at.clone()].iter_mut().filter(|row| row[2] != scene::NO_EMITTER) {- row[2] = row[2] - was + first;- }- if !at.is_empty() {- up.words.write(&self.g.queue, Stream::Rows, (at.start * 16) as u64, bytemuck::cast_slice(&rows[at]));- }- self.emitters_reweigh = true;+ let (to, _) = scene::placed_world(world.world_matrix(k), self.sc.instances[i.instance as usize].world.w_axis.truncate());+ started.push((i.instance, to));+ }+ for (r, to) in started {+ self.emitters_start_moving(r, to);}true}+ /// Instance `r`'s emitters become moving ones, where it has some that are not: a new run of the light list, placed+ /// by `to` (where this commit moves the instance); the light tree keeps the old one where it stood, at no weight.+ fn emitters_start_moving(&mut self, r: u32, to: glam::Mat4) {+ let LoadedScene { tables, instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;+ let old = emitter_run(&tables.emitter_tris, instances, r);+ if old.is_empty() || tables.emitter_tris[old.clone()].iter().all(|e| e.moves) {+ return;+ }+ let (was, first) = (old.start as u32, tables.emitter_tris.len() as u32);+ let inst = &mut instances[r as usize];+ for j in old {+ let e = crate::EmitterTri { moves: true, in_tree: false, ..tables.emitter_tris[j] };+ tables.emitter_tris[j].area = 0.0;+ let w = pool_tris[e.tri as usize - edit.pool_first].map(|v| glam::Vec3A::from(to.transform_point3(v.into())));+ self.pending_emitters.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));+ tables.emitter_tris.push(e);+ }+ inst.first_emitter = first;+ // (Its rows say where its sections' emitters start: where the run is now.)+ let at = inst.rows as usize..inst.rows as usize + meshes[inst.mesh as usize].sect_count as usize;+ for row in rows[at.clone()].iter_mut().filter(|row| row[2] != scene::NO_EMITTER) {+ row[2] = row[2] - was + first;+ }+ if !at.is_empty() {+ up.words.write(&self.g.queue, Stream::Rows, (at.start * 16) as u64, bytemuck::cast_slice(&rows[at]));+ }+ self.emitters_reweigh = true;+ }+/// An object shown or hidden by its `visible`, in place: the meshes and still models under it (itself, if it is one) each by its/// instance's mask above the triangles, where no ray sees a hidden one, and its row's power (`Tables::apply`: a/// hidden mesh's emitters at no weight). False where something under it is drawn another way, or a mesh is not@@ -1065,7 +1074,7 @@ impl LiveCore {let Some(o) = world.objects.get(id) else { continue };let of: Vec<u32> = match &p.draw {scene::Draw::Instance(i) => vec![i.instance],- scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),+ scene::Draw::Rigid(r) => r.records(),scene::Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),_ => vec![],};@@ -1139,7 +1148,7 @@ impl LiveCore {.values().flat_map(|p| match &p.draw {scene::Draw::Instance(i) => vec![i.instance],- scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),+ scene::Draw::Rigid(r) => r.records(),scene::Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),_ => vec![],})@@ -1581,14 +1590,17 @@ impl LiveCore {}/// Posed rigid models (`scene::RigidModel`): each moving node's instance takes object x node transform from the clip- /// (previous rows kept for motion vectors) and their flattened triangles are re-transformed in place; the commit- /// builds the dynamic BLASes (if they have such triangles) and the TLAS. False when it cannot (no hardware RT, a- /// model hidden or changed): the caller rebuilds.+ /// (previous rows kept for motion vectors), the instance of the nodes left alone the object's where the object+ /// moved (its emitters moving ones from its first move, `emitters_start_moving`), and their flattened triangles+ /// are re-transformed in place; the commit builds the dynamic BLASes (if they have such triangles) and the TLAS.+ /// False when it cannot (no hardware RT, a model hidden or changed): the caller rebuilds.pub(super) fn repose_rigid(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> Result<bool> {if self.sc.up.accel.is_none() {return Ok(false);}let mut placements: Vec<(u32, glam::Mat4)> = vec![];+ // (Object, where it stands now, and the instance of its nodes left alone if this is its first move.)+ let mut worlds: Vec<(u32, glam::Mat4, Option<u32>)> = vec![];let (mut lo, mut hi) = (usize::MAX, 0usize);for id in ids {let Some(o) = world.objects.get(id) else { return Ok(false) };@@ -1599,14 +1611,20 @@ impl LiveCore {let globals = scene::model_gltf(uri, &self.assets)?.node_globals(animation.as_ref())?;let m = world.world_matrix(*id);let r = self.sc.tables.retained.rigid(*id).expect("a rigid model (`commit`)");+ // (The nodes its clip leaves alone move with the object alone.)+ let moved = m != r.world;placements.extend(r.instances.iter().map(|&(node, i)| (i, m * globals[node])));+ if moved {+ placements.extend(r.still.map(|i| (i, m)));+ worlds.push((*id, m, r.still.filter(|_| !r.still_moves)));+ }let d = &r.rest;if d.finals.len() != d.mats.len() {return Ok(false);}let (first, verts, attrs, blas) = &mut self.sc.dynamic;for (j, (node, p, n, uv, tg)) in r.rest_local.iter().enumerate() {- let (pw, nw, uvw, tw) = scene::placed_tri(m * globals[*node], p, n, uv, *tg);+ let (pw, nw, uvw, tw) = scene::placed_tri(scene::RigidModel::part_world(m, *node, &globals), p, n, uv, *tg);let a = scene::tri_attr(pw, nw, uvw, tw, d.mats[j]);let k = d.finals[j] as usize - *first;let (e1, e2) = (pw[1] - pw[0], pw[2] - pw[0]);@@ -1620,6 +1638,15 @@ impl LiveCore {let o = &mut self.sc.tables.objects[d.object as usize * self.sc.tables.stride];(o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);}+ for (id, m, first_move) in worlds {+ if let Some(scene::Draw::Rigid(r)) = self.sc.tables.retained.proxies.get_mut(&id).map(|p| &mut p.draw) {+ (r.world, r.still_moves) = (m, true);+ }+ if let Some(still) = first_move {+ let (to, _) = scene::placed_world(m, self.sc.instances[still as usize].world.w_axis.truncate());+ self.emitters_start_moving(still, to);+ }+ }// The instances: rows, previous rows (motion vectors), TLAS transforms.let size = std::mem::size_of::<scene::GpuInstance>() as u64;let accel = self.sc.up.accel.as_mut().unwrap();diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 233706e..4af16cf 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -2002,6 +2002,114 @@ fn a_material_turned_glass_stops_casting_its_shadow_in_place() {}}+/// A posed rigid model with nodes its clip leaves alone (tests/render/data/panel-slider.glb: a panel that emits on+/// a node 5 m along x, a grey quad on a node the clip moves) is posed and moved in place: a new pose moves the+/// node's instance alone; one moved takes the part left alone with it, whose emitters are moving ones from that+/// first move (still ones, in the light tree, until then), movable object or not. Each time the light list is its+/// triangles and the picture a build's.+#[test]+fn a_posed_rigid_model_is_posed_and_moved_in_place_with_the_nodes_its_clip_leaves_alone() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });+ let model = |time| Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: slide(time), functions: vec![] };+ let size = Vec3::splat(0.08);+ let mut w = world();+ w.set_object(32, "posed".into(), None, model(0.25), true, false).unwrap();+ w.set_transform(32, Vec3::new(-1.3, 0.6, 0.5), glam::Quat::IDENTITY, size).unwrap();+ w.set_object(33, "movable".into(), None, model(0.25), true, true).unwrap();+ w.set_transform(33, Vec3::new(0.2, -0.7, 0.6), glam::Quat::IDENTITY, size).unwrap();+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let rigid = |c: &LiveCore, id: u32| c.sc.tables.retained.rigid(id).expect("a posed rigid model").clone();+ let (a, b) = (rigid(&live, 32), rigid(&live, 33));+ assert_eq!((live.sc.meshes.len(), live.sc.instances[a.still.unwrap() as usize].mesh, live.sc.instances[a.instances[0].1 as usize].mesh), (live.sc.meshes.len(), live.sc.instances[b.still.unwrap() as usize].mesh, live.sc.instances[b.instances[0].1 as usize].mesh), "the two placements share their parts' meshes");+ let moves = |c: &LiveCore, record: u32| c.sc.tables.emitter_tris.iter().filter(|e| e.inst == record).map(|e| e.moves).collect::<Vec<bool>>();+ assert_eq!((moves(&live, a.still.unwrap()), moves(&live, b.still.unwrap())), (vec![false; 2], vec![false; 2]), "the panels' emitters are still ones as loaded");+ list_is_its_triangles("posed rigid models, as loaded", &live);+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {+ list_is_its_triangles(what, live);+ let mut fresh = open(w).unwrap();+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ a+ };+ let before = against_a_build("posed rigid models, as loaded", &mut live, &w);+ // A new pose: the node's instance, and no other.+ w.set_animation(32, slide(0.75)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a new pose: in place ({:?})", live.fallback);+ assert!(live.inst_moving.contains(&a.instances[0].1) && !live.inst_moving.contains(&a.still.unwrap()), "the node the clip moves is moved, the part it leaves alone is not");+ against_a_build("a posed rigid model's new pose", &mut live, &w);+ // The movable one moved, and turned: its panel with it.+ w.set_transform(33, Vec3::new(-0.6, -0.2, 0.9), glam::Quat::from_rotation_z(0.5), size).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a movable posed rigid model moved: in place ({:?})", live.fallback);+ assert!(live.inst_moving.contains(&b.still.unwrap()), "the part its clip leaves alone moves with the object");+ // (Its emitters: a new run of moving ones, the run it had at no weight.)+ let lit = |c: &LiveCore, record: u32| c.sc.tables.emitter_tris.iter().filter(|e| e.inst == record && e.area > 0.0).map(|e| e.moves).collect::<Vec<bool>>();+ assert_eq!((lit(&live, b.still.unwrap()), moves(&live, b.still.unwrap()).len(), lit(&live, a.still.unwrap())), (vec![true; 2], 4, vec![false; 2]), "the moved panel's emitters are moving ones now, the other's are not");+ let moving = live.sc.tables.retained.moving_records();+ assert!(moving.contains(&b.still.unwrap()) && !moving.contains(&a.still.unwrap()), "the moved panel is among the records an edit moves, the other is not");+ let moved = against_a_build("a movable posed rigid model moved", &mut live, &w);+ assert!(apart(&before, &moved) > 0.5, "the move is in the picture ({:.2} steps)", apart(&before, &moved));+ // Posed on where it stands now: the node alone again.+ w.set_animation(33, slide(0.6)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "posed where it stands now: in place ({:?})", live.fallback);+ assert!(!live.inst_moving.contains(&b.still.unwrap()), "the part left alone stays where the move put it");+ against_a_build("a moved posed rigid model posed on", &mut live, &w);+ // Moved and posed at once.+ w.set_transform(33, Vec3::new(0.4, 0.5, 0.7), glam::Quat::from_rotation_y(0.3), size).unwrap();+ w.set_animation(33, slide(0.1)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "moved and posed at once: in place ({:?})", live.fallback);+ assert_eq!(moves(&live, b.still.unwrap()).len(), 4, "a second move makes no new run of emitters");+ against_a_build("a posed rigid model moved and posed at once", &mut live, &w);+ // One that is not movable, moved: its panel as the movable one's.+ w.set_transform(32, Vec3::new(-1.0, -0.3, 0.8), glam::Quat::IDENTITY, size).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a posed rigid model that is not movable, moved: in place ({:?})", live.fallback);+ assert_eq!(lit(&live, a.still.unwrap()), vec![true; 2], "its panel's emitters are moving ones now");+ against_a_build("a posed rigid model that is not movable, moved", &mut live, &w);+}++/// A posed rigid model under groups is not moved by a new pose, though the build and an update multiply its+/// transforms in another order (their products differ in their last bits here): the part its clip leaves alone stays+/// where it is, its emitters still ones.+#[test]+fn a_posed_rigid_model_under_groups_is_not_moved_by_a_new_pose() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });+ let mut w = world();+ w.set_object(50, "a".into(), None, Kind::Group, true, false).unwrap();+ w.set_transform(50, Vec3::new(0.13, -0.27, 0.31), glam::Quat::from_euler(glam::EulerRot::XYZ, 0.37, -0.53, 0.71), Vec3::new(1.1, 0.9, 1.3)).unwrap();+ w.set_object(51, "b".into(), Some(50), Kind::Group, true, false).unwrap();+ w.set_transform(51, Vec3::new(-0.21, 0.17, 0.09), glam::Quat::from_euler(glam::EulerRot::XYZ, -0.29, 0.61, 0.23), Vec3::new(0.7, 1.2, 0.8)).unwrap();+ w.set_object(32, "posed".into(), Some(51), Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: slide(0.25), functions: vec![] }, true, false).unwrap();+ w.set_transform(32, Vec3::new(-0.9, 0.3, 0.4), glam::Quat::from_rotation_y(0.4), Vec3::splat(0.08)).unwrap();+ let local = |id: u32| w.objects[&id].local();+ assert_ne!((local(50) * local(51)) * local(32), w.world_matrix(32), "the test's transforms: the two products differ");+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let still = live.sc.tables.retained.rigid(32).expect("a posed rigid model").still.expect("it has nodes left alone");+ w.set_animation(32, slide(0.75)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a new pose: in place ({:?})", live.fallback);+ assert!(!live.sc.tables.retained.rigid(32).unwrap().still_moves && !live.inst_moving.contains(&still), "the object did not move: the part left alone is not placed again");+ let moves: Vec<bool> = live.sc.tables.emitter_tris.iter().filter(|e| e.inst == still).map(|e| e.moves).collect();+ assert_eq!(moves, vec![false; 2], "its emitters are still ones");+ list_is_its_triangles("a posed rigid model under groups, posed again", &live);+ let mut fresh = open(&w).unwrap();+ forget(&mut live);+ let (a, b) = (picture(&mut live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));+}+/// Models in a shared pose posed again in place (tests/render/data/arm.glb: a skinned strip, a dark half and a light/// half that a joint swings): their mesh is skinned where it lies, each triangle still in its section. The picture is/// a build's.diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 0076ff1..e093824 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -856,13 +856,13 @@ impl Retained {}/// The records of the instances an edit moves in place: a mesh's or a model's that moves (a body's, a movable- /// one's), a posed rigid model's nodes', an instanced object's copies.+ /// one's), a posed rigid model's parts that move (`RigidModel::moving`), an instanced object's copies.pub fn moving_records(&self) -> std::collections::HashSet<u32> {self.proxies.values().flat_map(|p| match &p.draw {Draw::Instance(i) if i.moves => vec![i.instance],- Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),+ Draw::Rigid(r) => r.moving(),Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),_ => vec![],})@@ -896,20 +896,58 @@ pub struct InstancedPlace {pub drawn: u32,}-/// A posed glTF model without skins whose clip moves some of its nodes (Zero Day's 551 moving objects): the nodes the-/// clip leaves alone are ordinary static triangles; each moving mesh node is an instance of its own mesh (its triangles-/// in the node's space, one BLAS built once), placed at object x node transform, so a new pose moves instances-/// only (a node's emitters are its instance's in the light list, filled again when it moves). What-/// `flatten_coincident` takes out of a node's mesh is flattened: `rest`, re-transformed in place from `rest_local`.+/// A posed glTF model without skins whose clip moves some of its nodes (Zero Day's 551 moving objects), in parts+/// (`RigidPart`), each an instance of a mesh every placement of the model shares: the nodes the clip leaves alone+/// merged into one mesh in the model's space, placed by the object's transform; each node it moves a mesh in the+/// node's space, placed at object x node transform, so a new pose moves instances only (a part's emitters are its+/// instance's in the light list, filled again when it moves). What `flatten_coincident` takes out of a part's mesh+/// is flattened: `rest`, re-transformed in place from `rest_local`.#[derive(Clone, Default)]pub struct RigidModel {- /// (glTF node, instance index).+ /// (glTF node, instance index): the nodes the clip moves.pub instances: Vec<(usize, u32)>,+ /// The instance of the nodes it leaves alone, if any is drawn. It moves with the object alone; its emitters are+ /// still ones until the object first moves (`still_moves`: live/edits.rs `repose_rigid`).+ pub still: Option<u32>,+ pub still_moves: bool,+ /// The object's transform its parts were last placed by, as `World::world_matrix` gives it (an update compares+ /// with it to tell a move from a new pose).+ pub world: Mat4,pub rest: DynamicModel,- /// Per `rest` triangle: its node and its node-space triangle (positions, normals, uvs, tangent).+ /// Per `rest` triangle: its node (`STILL_NODES`: the model's own space) and its triangle there (positions,+ /// normals, uvs, tangent).pub rest_local: Vec<(usize, [Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>)>,}+/// In place of a node: the nodes a rigid model's clip leaves alone, merged (their space is the model's).+pub const STILL_NODES: usize = usize::MAX;++impl RigidModel {+ /// The records of all its instances.+ pub fn records(&self) -> Vec<u32> {+ self.instances.iter().map(|&(_, i)| i).chain(self.still).collect()+ }++ /// Those whose emitters are moving ones: its nodes', and the still part's once the object has moved.+ pub fn moving(&self) -> Vec<u32> {+ self.instances.iter().map(|&(_, i)| i).chain(self.still.filter(|_| self.still_moves)).collect()+ }++ /// A part's transform for the object's `m` and the pose's node transforms.+ pub fn part_world(m: Mat4, node: usize, globals: &[Mat4]) -> Mat4 {+ if node == STILL_NODES { m } else { m * globals[node] }+ }+}++/// A part of a rigid model as the build makes it once for the placements of the model with a clip: its node+/// (`STILL_NODES`), its mesh (None: nothing of it stays in a mesh), and what `flatten_coincident` took out, in the+/// part's space with its material.+struct RigidPart {+ node: usize,+ mesh: Option<u32>,+ rest: Vec<([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>, u32)>,+}+/// Posed skinned models in the same pose (the same model, nodes, clip and time: a crowd whose game shares a few walk/// phases). One model-space mesh holds the pose, skinned once per new pose and its BLAS rebuilt; each model is an/// instance of it, moved by its transform (hardware RT). Only meshes without triangles flattened per placement.@@ -1474,6 +1512,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se.map(|(g, _, grouped)| (*g, grouped)).collect();let mut mesh_of: HashMap<(String, Option<Vec<String>>), Option<u32>> = HashMap::new();+ // A posed rigid model's parts, by (model, clip): its placements share their meshes.+ let mut rigid_parts: HashMap<(String, String), std::rc::Rc<Vec<RigidPart>>> = HashMap::new();// Posed skinned models that share a pose with another share its mesh (`PoseGroup`). THREERT_POSE_SHARE=0 skins// each model alone (A/B).let mut pose_key_of: HashMap<u32, PoseKey> = HashMap::new();@@ -1696,102 +1736,114 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet movable = w.movable(*id);let dynamic = posed || movable;let flags = if dynamic { flags | TRI_DYNAMIC } else { flags };- // Posed rigid model: static nodes as triangles, moving nodes as instances (`RigidModel`); a movable one- // too (each update re-places its instances from the object's transform).+ // Posed rigid model: its parts as instances (`RigidModel`: the nodes its clip leaves alone merged into+ // one mesh, each node it moves a mesh); a movable one too (each update re-places its instances from+ // the object's transform).if instancing && posed && nodes.is_none() && glb.rigid() {let a = animation.as_ref().unwrap();- let moving = glb.moving_nodes(&a.clip)?;let globals = glb.node_globals(Some(a))?;- let static_tris = glb.node_triangles(m, Some(a), &|ni| !moving[ni], false)?;- let base_flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };- for (_, t) in &static_tris {- let mat = resolve(t.material.and_then(|i| doc.materials().nth(i)))?.0;- push_tri(&mut tris, &mut tri_flags, &mut attrs, t.p, t.n, t.uv, t.tangent, mat, base_flags);- }- let local = glb.node_triangles(Mat4::IDENTITY, None, &|ni| moving[ni], true)?;- // Group by node (the order within a node is the file's).- let mut by_node: Vec<(usize, Vec<usize>)> = vec![];- for (k, (ni, _)) in local.iter().enumerate() {- match by_node.last_mut() {- Some((last, list)) if *last == *ni => list.push(k),- _ => by_node.push((*ni, vec![k])),+ let pkey = (key.clone(), a.clip.clone());+ if !rigid_parts.contains_key(&pkey) {+ let moving = glb.moving_nodes(&a.clip)?;+ // (THREERT_RIGID_NODES=all: no node merged, every one an instance of a mesh of its own: the A/B+ // against the merged still part.)+ let all = std::env::var("THREERT_RIGID_NODES").is_ok_and(|v| v == "all");+ let apart = |ni: usize| all || moving[ni];+ // The nodes left alone, in the model's space as the pose has them (the pose does not move+ // them); then each node apart, in its own (the order within a node is the file's).+ let mut lists: Vec<(usize, Vec<crate::skin::ModelTri>)> = vec![];+ let still: Vec<_> = glb.node_triangles(Mat4::IDENTITY, Some(a), &|ni| !apart(ni), false)?.into_iter().map(|(_, t)| t).collect();+ if !still.is_empty() {+ lists.push((STILL_NODES, still));}- }- let oi = (objects.len() / stride) as u32;- let (mut olo, mut ohi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));- for t in &tris[first as usize..] {- for v in t {- olo = olo.min(*v);- ohi = ohi.max(*v);- }- }- let mut rigid = RigidModel::default();- let rest_first = tris.len() as u32;- for (ni, list) in &by_node {- let w_n = m * globals[*ni];- let mut classed: [Vec<(usize, u32)>; 4] = Default::default();- let mut emitting: std::collections::HashSet<u32> = Default::default();- for &k in list {- let (mat, class, emits) = resolve(local[k].1.material.and_then(|i| doc.materials().nth(i)))?;- classed[class as usize].push((k, mat));- if emits {- emitting.insert(mat);+ for (ni, t) in glb.node_triangles(Mat4::IDENTITY, None, &apart, true)? {+ match lists.last_mut() {+ Some((last, list)) if *last == ni => list.push(t),+ _ => lists.push((ni, vec![t])),}}- flatten_coincident(&mut classed, &emitting, &|k| local[k].1.p);- if classed[..FLAT].iter().any(|l| !l.is_empty()) {- let first_pool = pool_tris.len() as u32;- let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));- let (order, sects, mine) = model_sections(&kept(&classed));- for &(k, section, rank) in &order {- let t = &local[k].1;- for v in t.p {- lo = lo.min(v.into());- hi = hi.max(v.into());+ let mut parts = vec![];+ for (node, local) in &lists {+ let mut classed: [Vec<(usize, u32)>; 4] = Default::default();+ let mut emitting: std::collections::HashSet<u32> = Default::default();+ for (k, t) in local.iter().enumerate() {+ let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;+ classed[class as usize].push((k, mat));+ if emits {+ emitting.insert(mat);}- pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);- pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));}- for c in 0..8 {- let p = Vec3A::new(if c & 1 == 0 { lo.x } else { hi.x }, if c & 2 == 0 { lo.y } else { hi.y }, if c & 4 == 0 { lo.z } else { hi.z });- let q = w_n.transform_point3a(p);- olo = olo.min(q);- ohi = ohi.max(q);+ flatten_coincident(&mut classed, &emitting, &|k| local[k].p);+ let mesh = classed[..FLAT].iter().any(|l| !l.is_empty()).then(|| {+ let first_pool = pool_tris.len() as u32;+ let (order, sects, mine) = model_sections(&kept(&classed));+ for &(k, section, rank) in &order {+ let t = &local[k];+ pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);+ pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));+ }+ meshes.push(InstMesh { sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first_pool as usize..], first_pool) });+ sections.extend(sects);+ retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);+ meshes.len() as u32 - 1+ });+ let rest = classed[FLAT].iter().map(|&(k, mat)| (local[k].p, local[k].n, local[k].uv, local[k].tangent, mat)).collect();+ parts.push(RigidPart { node: *node, mesh, rest });+ }+ if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {+ let (merged, rest) = (lists.iter().filter(|l| l.0 == STILL_NODES).map(|l| l.1.len()).sum::<usize>(), parts.iter().map(|p| p.rest.len()).sum::<usize>());+ eprintln!("rigid: {uri} ({}): {merged} triangles of the nodes left alone in one mesh, {} nodes apart, {rest} triangles flattened a placement", a.clip, lists.iter().filter(|l| l.0 != STILL_NODES).count());+ }+ rigid_parts.insert(pkey.clone(), std::rc::Rc::new(parts));+ }+ let parts = rigid_parts[&pkey].clone();+ let base_flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };+ let oi = (objects.len() / stride) as u32;+ let (mut olo, mut ohi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));+ // (Where the object stands as an update finds it, `World::world_matrix`: the same product as `m`,+ // multiplied in another order, so not always the same bits.)+ let mut rigid = RigidModel { world: w.world_matrix(*id), ..Default::default() };+ rigid.rest.first = tris.len() as u32;+ rigid.rest.object = oi;+ for part in parts.iter() {+ // (A part placed without size, a node its clip scales to nothing: at a point; `repose_rigid`+ // keeps it from the rays.)+ let (w_n, _) = placed_world(RigidModel::part_world(m, part.node, &globals), m.w_axis.truncate());+ if let Some(mesh) = part.mesh {+ let (lo, hi) = meshes[mesh as usize].placed_bounds(w_n);+ (olo, ohi) = (olo.min(lo.into()), ohi.max(hi.into()));+ let mine = retained.mesh_rows[&mesh].clone();+ let i = instances.len() as u32;+ if part.node == STILL_NODES {+ rigid.still = Some(i);+ } else {+ rigid.instances.push((part.node, i));}- meshes.push(InstMesh { sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first_pool as usize..], first_pool) });- sections.extend(sects);- rigid.instances.push((*ni, instances.len() as u32));- instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });+ instances.push(Instance { mesh, world: w_n, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });rows.extend(mine);}- for &(k, mat) in &classed[FLAT] {- let t = &local[k].1;- let (p, nn, uv, tg) = placed_tri(w_n, &t.p, &t.n, &t.uv, t.tangent);- push_tri(&mut tris, &mut tri_flags, &mut attrs, p, nn, uv, tg, mat, base_flags | TRI_DYNAMIC);- rigid.rest.mats.push(mat);- rigid.rest_local.push((*ni, t.p, t.n, t.uv, t.tangent));+ for (p, nn, uv, tg, mat) in &part.rest {+ let (p, nn, uv, tg) = placed_tri(w_n, p, nn, uv, *tg);+ push_tri(&mut tris, &mut tri_flags, &mut attrs, p, nn, uv, tg, *mat, base_flags | TRI_DYNAMIC);+ rigid.rest.mats.push(*mat);}+ rigid.rest_local.extend(part.rest.iter().map(|&(p, nn, uv, tg, _)| (part.node, p, nn, uv, tg)));}- for t in &tris[rest_first as usize..] {+ for t in &tris[first as usize..] {for v in t {olo = olo.min(*v);ohi = ohi.max(*v);}}let pivot = m.transform_point3(Vec3::ZERO);- let size = ohi - olo;+ let size = (ohi - olo).max(Vec3A::ZERO);objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);for a in &mut attrs[first as usize..] {a.x[1] = f32::from_bits(oi);}- rigid.rest.first = rest_first;- rigid.rest.object = oi;if tris.len() as u32 > first {tri_nodes.push((n.name.clone(), first, tris.len() as u32));}- if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {- eprintln!("rigid: {uri}: {} static triangles, {} moving nodes as instances, {} flattened moving triangles", static_tris.len(), rigid.instances.len(), rigid.rest.mats.len());- }*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Rigid(rigid) };continue;}@@ -3027,6 +3079,45 @@ mod instance_tests {assert_eq!((r.instances.len(), r.rest.mats.len()), (1, 4));}+ /// A posed rigid model is its parts (tests/render/data/panel-slider.glb: a node its clip leaves alone, a grey quad+ /// and an emitting one, and a node it moves, a grey quad): the nodes left alone one mesh in the model's space,+ /// the moved node a mesh in its own, both shared by the placements of the model with the clip, whatever its time.+ /// Nothing is flattened. The part left alone's emitters are still ones, movable object or not.+ #[test]+ fn a_posed_rigid_model_is_instances_of_its_parts_meshes() {+ let mut w = World::default();+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();+ w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });+ for (id, time, movable) in [(1, 0.25, false), (2, 0.75, true)] {+ let animation = Some(desc::Animation { clip: "slide".into(), time, r#loop: true });+ w.set_object(id, format!("model{id}"), None, Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation, functions: vec![] }, true, movable).unwrap();+ w.set_transform(id, Vec3::new(id as f32 * 20.0, 0.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ }+ let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();+ assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.rest_count)).collect::<Vec<_>>(), [(4, 2, 0), (2, 1, 0)], "the part left alone (two materials), the moved node");+ assert_eq!((sc.meshes[0].lo.x, sc.meshes[0].hi.x, sc.meshes[1].lo.x, sc.meshes[1].hi.x), (1.0, 9.0, -1.0, 1.0), "the part left alone in the model's space (its node 5 m along x), the moved node in its own");+ assert_eq!((sc.instances.len(), sc.tris.len()), (4, 0), "two instances a placement, nothing flattened");+ let rigid = |sc: &Scene, id: u32| match &sc.retained.proxies[&id].draw {+ Draw::Rigid(r) => r.clone(),+ _ => panic!("a posed rigid model"),+ };+ for (id, y, movable) in [(1, 0.75, false), (2, 2.25, true)] {+ let r = rigid(&sc, id);+ let (still, node) = (&sc.instances[r.still.expect("it has nodes left alone") as usize], &sc.instances[r.instances[0].1 as usize]);+ assert_eq!((r.instances.len(), r.instances[0].0, still.mesh, node.mesh), (1, 1, 0, 1), "model {id}: the meshes every placement shares");+ let at = id as f32 * 20.0;+ assert_eq!((still.world.w_axis.truncate(), node.world.w_axis.truncate()), (Vec3::new(at, 0.0, 0.0), Vec3::new(at + 11.0, y, 0.0)), "model {id}: the object's place, and the node's by the clip");+ assert_eq!((r.records().len(), r.moving(), movable), (2, vec![r.instances[0].1], id == 2), "model {id}: the node alone has moving emitters at the build");+ assert_eq!(&sc.rows[still.rows as usize..][..2], &sc.retained.mesh_rows[&0][..], "model {id}: its rows are the mesh's");+ }+ // Its emitters are its instances': the part left alone's two triangles a placement, still ones (in the light+ // tree) until the object first moves.+ let prep = crate::prepare_as(true, false, &mut sc, &mut vec![]);+ let of = |id: u32| { let r = rigid(&sc, id); prep.emitter_tris.iter().filter(|e| Some(e.inst) == r.still).map(|e| e.moves).collect::<Vec<bool>>() };+ assert_eq!((of(1), of(2)), (vec![false; 2], vec![false; 2]));+ }+#[test]fn node_ranges_returns_every_range() {let nodes = vec![("lamp".to_string(), 10, 12), ("box".to_string(), 12, 20), ("lamp".to_string(), 40, 90)];diff --git a/tests/render/data/panel-slider.glb b/tests/render/data/panel-slider.glbnew file mode 100644index 0000000..da950b3Binary files /dev/null and b/tests/render/data/panel-slider.glb differdiff --git a/tests/render/geometry-emitter-rigid-moved-live.ts b/tests/render/geometry-emitter-rigid-moved-live.tsnew file mode 100644index 0000000..9e34d46--- /dev/null+++ b/tests/render/geometry-emitter-rigid-moved-live.ts@@ -0,0 +1,33 @@+// A movable posed rigid model moved in place takes the nodes its clip leaves alone with it (live/edits.rs+// `repose_rigid`: their instance, and its emitters in the light list). geometry/emitter-rigid's panel is built 300 m+// away; from 0.08 s the frame script holds it 1 m above the floor point the camera looks at, posed on. The floor+// reads the same analytic value; with the panel left where it was built it would read nothing.+import { GLTFModel } from "@threert/scene";+import { defineGame } from "@threert/gameplay";+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";+import { E, URI, models } from "./geometry-emitter-rigid.ts";++export const test: TestMeta = {+ id: "geometry/emitter-rigid-moved-live", features: ["emitters", "instancing", "gltf", "animation", "movable", "edits"], reference: "analytic", temporal: true,+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },+ requires: [URI],+ live: 240,+ note: "the panel moved 300 m in place, its clip playing: the floor below its centre as geometry/emitter-rigid",+};++export default defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ const scene = sceneWithSky(0);+ const [far, panel] = models([300, 1, 0]);+ panel.id = "panel";+ panel.movable = true;+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), far, panel]);+ },+ frame(f) {+ const panel = f.object("panel") as GLTFModel;+ if (f.time >= 0.08) panel.position.set(-5, 1, 0);+ panel.animation = { clip: "slide", time: 0.25 + (f.time % 0.5) };+ },+ handlers: {},+});diff --git a/tests/render/geometry-emitter-rigid.ts b/tests/render/geometry-emitter-rigid.tsnew file mode 100644index 0000000..0411496--- /dev/null+++ b/tests/render/geometry-emitter-rigid.ts@@ -0,0 +1,38 @@+// A posed rigid model's nodes that its clip leaves alone are one mesh, an instance (scene.rs `RigidModel::still`),+// and its emitters are that instance's in the light list. tests/render/data/panel-slider.glb: panel.glb's panel (a+// small grey quad, then an 8 x 8 m quad of 1 nit) on a node 5 m along x that no clip moves, and a grey quad 6 m+// beside it that the clip "slide" moves. As geometry/emitter-model: the panel faces down 1 m above a Lambert 0.5+// floor, and the floor below its centre reads 0.5 / pi x 2.989 (below its node's origin, 5 m aside, next to+// nothing). A second placement far away holds the list's first entries.+import { GLTFModel } from "@threert/scene";+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";++const corner = (x: number, y: number) => (x / Math.sqrt(1 + x * x)) * Math.atan(y / Math.sqrt(1 + x * x)) + (y / Math.sqrt(1 + y * y)) * Math.atan(x / Math.sqrt(1 + y * y));+export const E = 4 * (1 / 2) * corner(4, 4);+export const URI = "tests/render/data/panel-slider.glb";+export const POSE = { clip: "slide", time: 0.25 };++export const test: TestMeta = {+ id: "geometry/emitter-rigid", features: ["emitters", "lambert", "instancing", "gltf", "animation"], reference: "analytic", temporal: false,+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },+ requires: [URI],+ spp: 256,+ note: "camera under the panel at (3, 0.8, 0) looking at the floor point below its centre; the model posed by its clip",+};++/** The model with its panel facing down at `at` (its node is 5 m along x), and one far away. */+export const models = (at: [number, number, number]) => {+ const far = new GLTFModel(URI, { animation: POSE });+ far.position.set(900, -50, 0);+ far.scale.setScalar(0.01);+ const panel = new GLTFModel(URI, { animation: POSE });+ panel.name = "panel";+ panel.rotation.x = Math.PI / 2;+ panel.position.set(at[0] - 5, at[1], at[2]);+ return [far, panel];+};++export default () => {+ const scene = sceneWithSky(0);+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), ...models([0, 1, 0])]);+};