Skip to content

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.

Live commit: the acceleration structures built once, at its end (#137)

Yujia4882d401a15e
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index bcebb5e..4497e6a 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2591,6 +2591,23 @@ headless runner takes `{"cmd":"resize"}`. A test holds a resized view to one bui
frames). Left: the browser host's view is still fixed; the merged layout keeps the cache in one buffer with the
size's buffers, so a resize there empties it; a drag makes every buffer again at each step.
+**One build above the triangles a commit (2026-11-16, scene step B, first part).** Each edit a commit applies in
+place (moved instances, an instanced object's copies, procedural geometry, a rigid model's pose, a shared pose's
+mesh, re-transformed triangles, a geometry edit) built the acceleration structures it had touched itself, in its
+own submit, and was told by an argument whether a later one would build the TLAS for it; a geometry edit always
+built it, so an edit with a move built it twice. They now write their data and note what is to build
+(`gpu::TopBuild`), and the commit builds once at its end (`LiveCore::build_top`): every BLAS named and the TLAS in
+one call, or software traversal's top tree; its CPU time is the frame log's `build`, and `edit`, `instanced`,
+`skin` and `upload` no longer hold a build's share (numbers read before this are not comparable there). That call
+is also the only safe shape on Metal, where a TLAS built
+apart from a BLAS it references can see it unbuilt and lose its instance, in the next submit too: a shared pose
+that changed with nothing moving built its mesh in one submit and the TLAS in the next, and in a process that had
+rendered other scenes before the models were gone. `tests/render/skinning-shared-pose-live` passed through it
+(where the old arm was, there was sky: with no model too); it now holds the chest against that place, and fails on
+the code before. A test holds moves and edits in place, alone and several in a commit, to a view built from the
+world as it is then (`live::inplace_tests::moves_in_place_leave_what_a_build_does`: 0.02–0.08 of an 8-bit step;
+0.9 with nothing built), with one build a commit. No other picture changes (render-identity: 239 outputs).
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index a0021b0..687f6d0 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -46,7 +46,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:
| Engine API | `packages/scene/src/engine.ts` (`Engine`), `renderer/src/script.rs` (`__engine` natives) | Handles (u32) for geometries (typed arrays), textures (asset path, encoded image or RGBA8 pixels), material-function code, materials, objects (group / mesh / model / light / camera) and their transform, visibility, power, light / camera parameters; the environment and render settings. Descriptors are JSON-shaped (`renderer/src/desc.rs`). |
| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. |
| World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). |
-| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs`, `live/state.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. What is not the scene's data is held beside it and derived whole from the world, by the same function at load and on an edit (`live/state.rs`): the view's state (`ViewState`: the scene camera's lens, depth of field and exposure, which camera is the scene's, the render preset) and the environment (`Environment`: wetness, rain, fog or a background, appearing or going with another variant of the kernel; its sky, baked and put in place by `apply_sky`). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. The view's size is the view's: `LiveCore::resize` makes the buffers that follow it again (`live/targets.rs`) and leaves the scene's data and the radiance cache; the window (`play`) follows its size and its display's density, the headless runner takes `{"cmd":"resize"}`. |
+| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs`, `live/state.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. What is not the scene's data is held beside it and derived whole from the world, by the same function at load and on an edit (`live/state.rs`): the view's state (`ViewState`: the scene camera's lens, depth of field and exposure, which camera is the scene's, the render preset) and the environment (`Environment`: wetness, rain, fog or a background, appearing or going with another variant of the kernel; its sky, baked and put in place by `apply_sky`). What the edits of a commit change above the triangles (instances moved, meshes built again, triangles re-transformed) is built once at its end, every BLAS named and the TLAS in one call (`gpu::TopBuild`, `LiveCore::build_top`). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. The view's size is the view's: `LiveCore::resize` makes the buffers that follow it again (`live/targets.rs`) and leaves the scene's data and the radiance cache; the window (`play`) follows its size and its display's density, the headless runner takes `{"cmd":"resize"}`. |
| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. Every entry ends by running the promise jobs it left, inside its budget ("Promises", below). The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |
| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), `sync()` (the engine follows the scene once more: after an entry's promise jobs), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |
| World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index e9d41cc..ba3283c 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -191,11 +191,85 @@ impl EditRoom {
}
}
-/// A procedural BLAS an edit made, to be built with the edit's TLAS (`Gpu::proc_blas`, `build_edit`).
+/// A procedural BLAS an edit made, to be built with its commit's TLAS (`Gpu::proc_blas`, `TopBuild`): kept by its
+/// blob's hash for reuse once built (`bytes`: its size).
pub struct PendingProc {
+ hash: [u8; 32],
blas: wgpu::Blas,
boxes: wgpu::Buffer,
size: wgpu::BlasAABBGeometrySizeDescriptor,
+ bytes: u64,
+}
+
+/// What a commit's edits leave to build above the triangles (live/edits.rs `commit`): each writes its data and notes
+/// here what is to build, and the commit builds once at its end (`Gpu::build_top`).
+#[derive(Default)]
+pub struct TopBuild {
+ /// Instances (hardware traversal's TLAS instances, software traversal's units) moved, came or went.
+ pub instances: bool,
+ /// The dynamic groups' BLASes: their triangles were re-transformed.
+ pub dynamic: bool,
+ /// Instanced meshes' BLASes: new meshes, a new shared pose.
+ pub meshes: Vec<u32>,
+ /// Procedural BLASes an edit made.
+ pub procs: Vec<PendingProc>,
+}
+
+impl TopBuild {
+ pub fn any(&self) -> bool {
+ self.instances || self.dynamic || !self.meshes.is_empty() || !self.procs.is_empty()
+ }
+}
+
+/// The build entries of instanced meshes' BLASes over their pool triangles as they are now.
+fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec<wgpu::BlasBuildEntry<'a>> {
+ meshes
+ .iter()
+ .map(|&m| {
+ let (parts, sizes) = &accel.mesh_geo[m as usize];
+ wgpu::BlasBuildEntry {
+ blas: &accel.meshes[m as usize],
+ geometry: wgpu::BlasGeometries::TriangleGeometries(
+ sizes
+ .iter()
+ .zip(parts)
+ .map(|(size, &(first, _, _))| wgpu::BlasTriangleGeometry {
+ size,
+ vertex_buffer: &accel.verts,
+ first_vertex: ((accel.pool_first + first as usize) * 3) as u32,
+ vertex_stride: 12,
+ index_buffer: None,
+ first_index: None,
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ })
+ .collect(),
+ ),
+ }
+ })
+ .collect()
+}
+
+/// The build entries of the dynamic groups' BLASes (groups 4 and up) over their triangles as they are now.
+fn dynamic_entries(accel: &Accel) -> Vec<wgpu::BlasBuildEntry<'_>> {
+ accel
+ .blases
+ .iter()
+ .filter(|b| b.1 >= 4)
+ .map(|(blas, _, first, size)| wgpu::BlasBuildEntry {
+ blas,
+ geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
+ size,
+ vertex_buffer: &accel.verts,
+ first_vertex: (*first * 3) as u32,
+ vertex_stride: 12,
+ index_buffer: None,
+ first_index: None,
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ }]),
+ })
+ .collect()
}
/// The acceleration structure's binding in the scene's group (trace_hw.wgsl `acc`): the last, after every buffer.
@@ -705,7 +779,7 @@ pub struct Accel {
blases: Vec<(wgpu::Blas, usize, usize, wgpu::BlasTriangleGeometrySizeDescriptor)>,
/// One per instanced mesh (model space), referenced by the TLAS's model instances.
meshes: Vec<wgpu::Blas>,
- /// Per mesh: its (first pool triangle, count, opaque) geometries and their sizes (`rebuild_meshes`).
+ /// Per mesh: its (first pool triangle, count, opaque) geometries and their sizes (`mesh_entries`).
mesh_geo: Vec<(Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)>,
/// The first pool triangle in the GPU order.
pool_first: usize,
@@ -3023,7 +3097,7 @@ impl Gpu {
}
/// A new instanced mesh over `count` triangles from GPU-order index `first` (in the edit room; live/edits.rs
- /// `edit_geometry`), its first `opaque` ones opaque: its BLAS, which `rebuild_meshes` builds. Returns its index.
+ /// `edit_geometry`), its first `opaque` ones opaque: its BLAS, which the commit's build builds (`TopBuild::meshes`). Returns its index.
pub fn add_mesh(&self, accel: &mut Accel, first: usize, count: u32, opaque: u32) -> u32 {
// Built fast rather than traced fast (edits come every frame under destruction; the batches of pieces are rebuilt
// every frame); THREERT_EDIT_BLAS=trace for the A/B (`mesh_blas_for`).
@@ -3038,36 +3112,24 @@ impl Gpu {
&accel.meshes[k as usize]
}
- /// The AABB BLAS of a procedural geometry's boxes (live/edits.rs `edit_geometry`): the one kept by its hash or built
- /// earlier in this edit (`fresh`), or a new one whose build goes into `e` and into `fresh`. The edit keeps `fresh`
- /// (`keep_proc_blases`) only once `e` is submitted: an edit that falls back never submits, and a BLAS never built
- /// must not be reused.
- /// Its BLAS (kept by hash, or made now: its build added to `pending`, which `build_meshes` builds with the TLAS).
- pub fn proc_blas(&self, blob: &crate::procasset::ProcBlob, pending: &mut Vec<PendingProc>, fresh: &mut Vec<([u8; 32], wgpu::Blas, u64)>) -> wgpu::Blas {
+ /// The AABB BLAS of a procedural geometry's boxes (live/edits.rs `edit_geometry`): the one kept by its hash, the
+ /// one this commit already made (`pending`), or a new one added to `pending` (`TopBuild::procs`).
+ pub fn proc_blas(&self, blob: &crate::procasset::ProcBlob, pending: &mut Vec<PendingProc>) -> wgpu::Blas {
if let Some((blas, _)) = self.proc_blases.lock().unwrap().get(&blob.hash) {
return blas.clone();
}
- if let Some((_, blas, _)) = fresh.iter().find(|f| f.0 == blob.hash) {
- return blas.clone();
+ if let Some(p) = pending.iter().find(|p| p.hash == blob.hash) {
+ return p.blas.clone();
}
let d = &self.device;
let size = wgpu::BlasAABBGeometrySizeDescriptor { primitive_count: (blob.boxes.len() / 6) as u32, flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE };
let blas = d.create_blas(&wgpu::CreateBlasDescriptor { label: Some("proc"), flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::AABBs { descriptors: vec![size.clone()] });
let boxes = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("proc boxes"), contents: bytemuck::cast_slice(&blob.boxes), usage: wgpu::BufferUsages::BLAS_INPUT });
let bytes = self.aabb_blas_bytes(&boxes, size.primitive_count).unwrap_or(0);
- fresh.push((blob.hash, blas.clone(), bytes));
- pending.push(PendingProc { blas: blas.clone(), boxes, size });
+ pending.push(PendingProc { hash: blob.hash, blas: blas.clone(), boxes, size, bytes });
blas
}
- /// Keeps the procedural BLASes an edit built (`proc_blas`), once its builds are submitted.
- pub fn keep_proc_blases(&self, fresh: Vec<([u8; 32], wgpu::Blas, u64)>) {
- let mut built = self.proc_blases.lock().unwrap();
- for (hash, blas, bytes) in fresh {
- built.insert(hash, (blas, bytes));
- }
- }
-
/// The scene's bind group (group 0: pathtrace.wgsl's declarations, the layout `Gpu::new` makes).
fn scene_bind_group(&self, b: &SceneBuffers) -> wgpu::BindGroup {
let view = |binding: u32, v| wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::TextureView(v) };
@@ -3161,7 +3223,7 @@ impl Gpu {
}
/// Software traversal's top tree again, over the units as they are now, written to its range of the node buffer
- /// (what `rebuild_tlas` is to hardware traversal). Err: no tree can be made (more units than its range holds, a
+ /// (what the TLAS's build is to hardware traversal). Err: no tree can be made (more units than its range holds, a
/// unit that is nowhere); nothing was written, and the caller rebuilds the scene.
pub fn retop(&self, units: &mut crate::units::Units, nodes: &wgpu::Buffer) -> std::result::Result<(), String> {
let top = units.top()?;
@@ -3183,74 +3245,39 @@ impl Gpu {
self.queue.write_buffer(nodes, root as u64 * 32, bytemuck::cast_slice(&vec![crate::units::FILL; len as usize]));
}
- pub fn rebuild_tlas(&self, accel: &Accel, e: &mut wgpu::CommandEncoder) {
- e.build_acceleration_structures(std::iter::empty::<&wgpu::BlasBuildEntry>(), [&accel.tlas]);
- }
-
- /// Rebuilds the BLASes of instanced meshes whose triangles changed (a new shared pose, `scene::PoseGroup`), not the
- /// TLAS: the caller rebuilds it after (it holds their bounds).
- pub fn rebuild_meshes(&self, accel: &Accel, meshes: &[u32], e: &mut wgpu::CommandEncoder) {
- self.build_meshes(accel, meshes, e, false);
- }
-
- /// The BLASes of instanced meshes `meshes` and, with `tlas`, the TLAS in the same build (the TLAS reads the BLASes'
- /// bounds through their resource ids, which Metal does not order a later build after: a TLAS built apart from a
- /// BLAS it references, in the same encoder, could see it unbuilt and lose its instance; live/edits.rs `edit_geometry`).
- pub fn build_meshes(&self, accel: &Accel, meshes: &[u32], e: &mut wgpu::CommandEncoder, tlas: bool) {
- self.build_edit(accel, meshes, &[], e, tlas);
- }
-
- /// `build_meshes` with the procedural BLASes `proc_blas` left pending, all in the one build.
- pub fn build_edit(&self, accel: &Accel, meshes: &[u32], procs: &[PendingProc], e: &mut wgpu::CommandEncoder, tlas: bool) {
- let mut entries: Vec<wgpu::BlasBuildEntry> = meshes
- .iter()
- .map(|&m| {
- let (parts, sizes) = &accel.mesh_geo[m as usize];
- wgpu::BlasBuildEntry {
- blas: &accel.meshes[m as usize],
- geometry: wgpu::BlasGeometries::TriangleGeometries(
- sizes
- .iter()
- .zip(parts)
- .map(|(size, &(first, _, _))| wgpu::BlasTriangleGeometry {
- size,
- vertex_buffer: &accel.verts,
- first_vertex: ((accel.pool_first + first as usize) * 3) as u32,
- vertex_stride: 12,
- index_buffer: None,
- first_index: None,
- transform_buffer: None,
- transform_buffer_offset: None,
- })
- .collect(),
- ),
+ /// What a commit left to build above the triangles, once. Hardware traversal: the BLASes named and the TLAS in one
+ /// call: on Metal a TLAS built apart from a BLAS it references, in the next submit too, can see it unbuilt and
+ /// lose its instance until the TLAS is next built (tests/render/skinning-shared-pose-live). Software traversal:
+ /// the top tree over the units as they are now; Err: none can be made (`retop`), nothing was written, and the
+ /// caller rebuilds the scene.
+ pub fn build_top(&self, up: &mut Uploaded, b: TopBuild) -> std::result::Result<(), String> {
+ match Top::of(&mut up.accel, &mut up.units) {
+ Some(Top::Hw(accel)) => {
+ let mut meshes = b.meshes;
+ meshes.sort_unstable();
+ meshes.dedup();
+ let mut entries = mesh_entries(accel, &meshes);
+ entries.extend(b.procs.iter().map(|p| wgpu::BlasBuildEntry { blas: &p.blas, geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size: &p.size, stride: 24, aabb_buffer: &p.boxes, primitive_offset: 0 }]) }));
+ if b.dynamic {
+ entries.extend(dynamic_entries(accel));
}
- })
- .collect();
- entries.extend(procs.iter().map(|p| wgpu::BlasBuildEntry { blas: &p.blas, geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size: &p.size, stride: 24, aabb_buffer: &p.boxes, primitive_offset: 0 }]) }));
- e.build_acceleration_structures(entries.iter(), tlas.then_some(&accel.tlas));
+ let mut e = self.device.create_command_encoder(&Default::default());
+ e.build_acceleration_structures(entries.iter(), [&accel.tlas]);
+ self.queue.submit([e.finish()]);
+ drop(entries);
+ // Built: kept for reuse (a commit that falls back never builds, and a BLAS never built must not be).
+ self.proc_blases.lock().unwrap().extend(b.procs.into_iter().map(|p| (p.hash, (p.blas, p.bytes))));
+ Ok(())
+ }
+ Some(Top::Sw(units)) => self.retop(units, &up.bg_parts.nodes),
+ None => Ok(()),
+ }
}
+ /// The dynamic groups' BLASes and the TLAS, in a frame's encoder (the particle passes: their triangles are placed
+ /// by the GPU every frame).
pub fn rebuild_dynamic(&self, accel: &Accel, e: &mut wgpu::CommandEncoder) {
- let entries: Vec<wgpu::BlasBuildEntry> = accel
- .blases
- .iter()
- .filter(|b| b.1 >= 4)
- .map(|(blas, _, first, size)| wgpu::BlasBuildEntry {
- blas,
- geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
- size,
- vertex_buffer: &accel.verts,
- first_vertex: (*first * 3) as u32,
- vertex_stride: 12,
- index_buffer: None,
- first_index: None,
- transform_buffer: None,
- transform_buffer_offset: None,
- }]),
- })
- .collect();
- e.build_acceleration_structures(entries.iter(), [&accel.tlas]);
+ e.build_acceleration_structures(dynamic_entries(accel).iter(), [&accel.tlas]);
}
#[cfg(not(target_arch = "wasm32"))]
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index f0ec612..db26cf6 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -55,8 +55,8 @@ impl Gather {
}
/// Where an in-place edit's CPU time goes (ms) and what it did: building the triangles' GPU form, uploading them,
-/// creating and recording BLASes and the TLAS; meshes added and rewritten in place, objects added or removed. Frame log
-/// `edit_split`.
+/// making its BLASes (software traversal: its trees; their build is the commit's, `LiveCore::build_ms`); meshes added
+/// and rewritten in place, objects added or removed. Frame log `edit_split`.
#[derive(Default, Clone, Copy, Debug)]
pub struct EditSplit {
pub tris: f64,
@@ -309,6 +309,8 @@ impl LiveCore {
self.cpu_skin_ms = 0.0;
self.cpu_upload_ms = 0.0;
self.gpu_blas_ms = 0.0;
+ // What the edits below leave to build above the triangles: built once, at the end (`build_top`).
+ let mut top = gpu::TopBuild::default();
// The game's particle spawns, for the next frame's pass; the voxel occupancy grid's changes, uploaded.
for (id, v) in std::mem::take(&mut world.particle_spawns) {
self.particle_spawns.entry(id).or_default().extend(v);
@@ -375,21 +377,19 @@ impl LiveCore {
eprintln!("edit: rebuild (an object added in place moved)");
}
}
- // Instanced objects rewrite their instances in place (`update_instanced`); one that cannot rebuilds the scene. Before
- // the geometry edits, whose TLAS build (always, or the rebuild they fall back to) then carries the instances too
- // (a voxel scene's debris and batches: one build of a 20 k instance TLAS a frame, not two); else they build it.
+ // Instanced objects rewrite their instances in place (`update_instanced`); one that cannot rebuilds the scene.
// (The instances the last update moved, taken first: what this one moves, from here on, keeps its motion.)
let moved_before = std::mem::take(&mut self.inst_moving);
let mut instanced_early = false;
// (Not those added this commit: the geometry edits place them with their instances as they are.)
let early: Vec<u32> = std::mem::take(&mut changes.instanced).into_iter().filter(|id| !changes.added.contains(id)).collect();
if !early.is_empty() && !changes.structural {
- instanced_early = self.instanced_in_place(world, &early, !changes.edits(), &mut changes);
+ instanced_early = self.instanced_in_place(world, &early, &mut changes, &mut top);
}
// Geometry edits in place when nothing else is structural; what they cannot apply rebuilds the scene.
if changes.edits() && !changes.structural {
let t = Instant::now();
- let r = self.edit_geometry(world, &changes);
+ let r = self.edit_geometry(world, &changes, &mut top);
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
eprintln!("edit: {} geometries, {} added, {} removed: {}", changes.geometries.len(), changes.added.len(), changes.removed.len(), r.as_ref().map_or_else(|e| format!("rebuild ({e})"), |_| "in place".into()));
}
@@ -461,12 +461,10 @@ impl LiveCore {
}
// Instanced objects under a moved ancestor (or movable themselves) rewrite their instances too, unless the update
// above did (with the same world matrices; twice would take the new rows for the previous frame's: no motion).
- // The TLAS is built by whatever moves after them, or there.
let mut instanced_done = instanced_early;
instanced_moved.retain(|k| !early.contains(k));
if !instanced_moved.is_empty() && !changes.structural {
- let others = !placed.is_empty() || !dynamic.is_empty() || !procs_moved.is_empty();
- instanced_done |= self.instanced_in_place(world, &instanced_moved, !others, &mut changes);
+ instanced_done |= self.instanced_in_place(world, &instanced_moved, &mut changes, &mut top);
}
// Posed rigid models move their nodes' instances (`repose_rigid`), not triangles.
let rigid: Vec<u32> = dynamic.iter().copied().filter(|k| self.sc.tables.retained.rigid.contains_key(k)).collect();
@@ -478,14 +476,14 @@ impl LiveCore {
for k in &shared {
dynamic.remove(k);
}
- let shared_ok = shared.is_empty() || (!changes.structural && self.repose_groups(world, &shared)?);
- // Procedural geometry moves its records and TLAS transforms; the TLAS is built by whatever moves after it, or here.
+ let shared_ok = shared.is_empty() || (!changes.structural && self.repose_groups(world, &shared, &mut top)?);
+ // Procedural geometry moves its records and TLAS transforms.
if !procs_moved.is_empty() && !changes.structural {
- self.move_procs(world, &procs_moved, placed.is_empty() && dynamic.is_empty() && rigid.is_empty() && shared.is_empty());
+ self.move_procs(world, &procs_moved, &mut top);
}
- let placed_ok = shared_ok && (placed.is_empty() || (!changes.structural && self.move_instances(world, &placed, dynamic.is_empty() && rigid.is_empty())));
+ let placed_ok = shared_ok && (placed.is_empty() || (!changes.structural && self.move_instances(world, &placed, &mut top)));
let t_rigid = Instant::now();
- let rigid_ok = placed_ok && (rigid.is_empty() || (!changes.structural && self.repose_rigid(world, &rigid, dynamic.is_empty())?));
+ let rigid_ok = placed_ok && (rigid.is_empty() || (!changes.structural && self.repose_rigid(world, &rigid, &mut top)?));
self.cpu_skin_ms += t_rigid.elapsed().as_secs_f32() * 1000.0;
// Instances the last update moved and this one does not: their motion ends, the previous-frame rows catch up
// (written merged: an instanced object's thousands of records are contiguous).
@@ -501,15 +499,7 @@ impl LiveCore {
}
catch_up.flush_section(&self.g.queue, &self.sc.up.heap, Table::Instances);
}
- if rigid_ok && (dynamic.is_empty() || (!changes.structural && self.repose(world, &dynamic)?)) {
- // A new shared pose and nothing else that rebuilds the TLAS (no move): rebuild it for the meshes' new bounds.
- if !shared.is_empty() && placed.is_empty() && rigid.is_empty() && dynamic.is_empty() {
- if let Some(accel) = self.sc.up.accel.as_ref() {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- self.g.queue.submit([e.finish()]);
- }
- }
+ if rigid_ok && (dynamic.is_empty() || (!changes.structural && self.repose(world, &dynamic, &mut top)?)) {
// Moved emitters: the light tree's moving subtree around them, once (after every in-place update).
if std::mem::take(&mut self.emitters_moved) {
self.refit_moving_tree();
@@ -549,7 +539,12 @@ impl LiveCore {
changes.structural = true;
}
let now = shader_time(self.time);
- let applied = self.sc.tables.apply(world, &changes, now).ok().flatten();
+ // The tables' edits, then what the edits above left to build, once. Either may say the scene is to be rebuilt,
+ // and the rebuild builds all of it.
+ let mut applied = self.sc.tables.apply(world, &changes, now).ok().flatten();
+ if applied.is_some() && !self.build_top(top) {
+ applied = None;
+ }
let Some(d) = applied else {
let t = Instant::now();
self.rebuild(world)?;
@@ -595,6 +590,33 @@ impl LiveCore {
Ok(false)
}
+ /// What a commit's edits left to build above the triangles, in one build (`Gpu::build_top`). False: software
+ /// traversal's top tree cannot be made, and the caller rebuilds the scene. Its CPU time is `build_ms`;
+ /// THREERT_PROFILE_BLAS=1: its GPU time (the queue drained before and after; frame log `blas`).
+ fn build_top(&mut self, b: gpu::TopBuild) -> bool {
+ if !b.any() {
+ return true;
+ }
+ let profile = std::env::var("THREERT_PROFILE_BLAS").is_ok_and(|v| v == "1");
+ if profile {
+ let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
+ }
+ let t = Instant::now();
+ let built = self.g.build_top(&mut self.sc.up, b);
+ self.build_ms += t.elapsed().as_secs_f32() * 1e3;
+ if profile {
+ let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
+ self.gpu_blas_ms += t.elapsed().as_secs_f32() * 1e3;
+ }
+ self.top_builds += 1;
+ if let Err(why) = &built {
+ eprintln!("units: {why}: rebuilding the scene");
+ self.fallback = Some(why.clone());
+ self.fallbacks += 1;
+ }
+ built.is_ok()
+ }
+
/// The kernel features the scene needs as it is now: what its materials and the environment ask for (edits change
/// them), with the structural ones the build found (textures, material functions, the traversal groups;
/// `gpu::instance_features`). A new variant is compiled once, then cached.
@@ -707,11 +729,10 @@ impl LiveCore {
}
/// Moves movable instances: their kernel records (the old transform kept as the previous frame's, for motion
- /// vectors), their object entries' pivots and their TLAS transforms (hardware traversal; with `build_tlas` it
- /// rebuilds the TLAS, otherwise the dynamic rebuild that follows does) or their units and the top tree over them
- /// (software traversal, units.rs). No triangles change. False when it cannot (software traversal without units,
- /// or an instance that is no unit; a top tree that cannot be made): the caller rebuilds.
- pub(super) fn move_instances(&mut self, world: &World, placed: &[(u32, u32)], build_tlas: bool) -> bool {
+ /// vectors), their object entries' pivots and their TLAS transforms (hardware traversal) or their units (software
+ /// traversal, units.rs); the commit builds what is above them (`build_top`). No triangles change. False when it
+ /// cannot (software traversal without units, or an instance that is no unit): the caller rebuilds.
+ pub(super) fn move_instances(&mut self, world: &World, placed: &[(u32, u32)], build: &mut gpu::TopBuild) -> bool {
// (Hardware traversal's TLAS instances, or software traversal's units; neither: the caller rebuilds.)
let Some(mut top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return false };
let size = std::mem::size_of::<scene::GpuInstance>() as u64;
@@ -757,19 +778,8 @@ impl LiveCore {
}
self.sc.up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
self.inst_moved = true;
- match top {
- gpu::Top::Hw(accel) => {
- if build_tlas {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- q.submit([e.finish()]);
- }
- true
- }
- // (The top tree is built here whoever else changes units this commit: it is CPU work and one write, and a
- // tree that cannot be made must send the caller to a rebuild now.)
- gpu::Top::Sw(units) => self.g.retop(units, &self.sc.up.bg_parts.nodes).map_err(|e| eprintln!("units: {e}: rebuilding the scene")).is_ok(),
- }
+ build.instances = true;
+ true
}
/// The material table to the GPU: written in place; with more materials than its section holds (materials added
@@ -793,9 +803,9 @@ impl LiveCore {
/// `update_instanced` with its fallback (the reason in the frame log, the scene rebuilt) and its CPU time; whether it
/// changed anything.
- pub(super) fn instanced_in_place(&mut self, world: &World, ids: &[u32], build_tlas: bool, changes: &mut crate::world::Changes) -> bool {
+ pub(super) fn instanced_in_place(&mut self, world: &World, ids: &[u32], changes: &mut crate::world::Changes, build: &mut gpu::TopBuild) -> bool {
let t = Instant::now();
- let r = self.update_instanced(world, ids, build_tlas);
+ let r = self.update_instanced(world, ids, build);
self.instanced_ms += t.elapsed().as_secs_f32() * 1e3;
let log = std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1");
match r {
@@ -1022,11 +1032,11 @@ impl LiveCore {
/// Instanced objects whose instances changed (`World::instanced`, the node's transform, power or customData): their
/// kernel records (the old transforms kept as the previous frame's, for motion vectors), object entries (pivot,
/// bounds, power, data, colour), TLAS transforms and masks (`scene::instance_world`: a hidden instance 0), each
- /// object's records and entries written as one range; with `build_tlas` the TLAS is rebuilt here. No triangles or
+ /// object's records and entries written as one range; the commit builds what is above them. No triangles or
/// BLASes change. Returns how many objects it updated; Err: why it cannot (software traversal, an object the build
/// flattened or did not place this way, an instance now mirrored), and the caller rebuilds.
/// `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
- pub(super) fn update_instanced(&mut self, world: &World, ids: &[u32], build_tlas: bool) -> std::result::Result<usize, String> {
+ pub(super) fn update_instanced(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> std::result::Result<usize, String> {
use crate::world::Kind;
if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {
return Err("THREERT_EDIT_REBUILD=1".into());
@@ -1096,24 +1106,15 @@ impl LiveCore {
}
if done > 0 {
self.inst_moved = true;
- match top {
- gpu::Top::Hw(accel) => {
- if build_tlas {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- self.g.queue.submit([e.finish()]);
- }
- }
- gpu::Top::Sw(units) => self.g.retop(units, &sc.up.bg_parts.nodes)?,
- }
+ build.instances = true;
}
Ok(done)
}
/// Moves procedural objects: their kernel records (the old transform kept as the previous frame's, for motion
- /// vectors), object pivots and, with hardware RT, TLAS transforms (`build_tlas`: the TLAS rebuilt here). Software
+ /// vectors), object pivots and, with hardware RT, TLAS transforms (the commit builds the TLAS). Software
/// traversal reads the records alone, so neither path rebuilds the scene.
- pub(super) fn move_procs(&mut self, world: &World, ids: &[u32], build_tlas: bool) {
+ pub(super) fn move_procs(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) {
let size = std::mem::size_of::<scene::GpuInstance>() as u64;
for id in ids {
let Some(&j) = self.sc.proc_of.get(id) else { continue };
@@ -1138,19 +1139,16 @@ impl LiveCore {
self.inst_moving.push(i as u32);
}
self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- if let (true, Some(accel)) = (build_tlas, self.sc.up.accel.as_ref()) {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- self.g.queue.submit([e.finish()]);
- }
+ // (Software traversal reads the records alone: no unit moved.)
+ build.instances |= self.sc.up.accel.is_some();
self.inst_moved = true;
}
/// 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; then the dynamic
- /// BLASes (if they have such triangles) and, when `build_tlas`, the TLAS are rebuilt (`repose` rebuilds both after
- /// it otherwise). 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_tlas: bool) -> Result<bool> {
+ /// (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.
+ 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);
}
@@ -1231,25 +1229,17 @@ impl LiveCore {
q.write_buffer(&up.attrs, k * 96, bytemuck::cast_slice(&attrs[lo..hi]));
q.write_buffer(&accel.verts, k * 36, bytemuck::cast_slice(&blas[lo * 3..hi * 3]));
}
- if build_tlas {
- let accel = self.sc.up.accel.as_ref().unwrap();
- let mut e = self.g.device.create_command_encoder(&Default::default());
- if lo < hi {
- self.g.rebuild_dynamic(accel, &mut e);
- } else {
- self.g.rebuild_tlas(accel, &mut e);
- }
- self.g.queue.submit([e.finish()]);
- }
+ build.instances = true;
+ build.dynamic |= lo < hi;
Ok(true)
}
/// Models in a shared pose (`scene::PoseGroup`): each group whose pose changed is skinned once, in model space (the
- /// groups in parallel), into its mesh's pool triangles, and their BLASes are rebuilt; the TLAS is left to the moves
- /// that follow (or `commit`). False when a group's members no longer share one pose, or one is hidden or changed:
+ /// groups in parallel), into its mesh's pool triangles; the commit builds their BLASes and the TLAS over their
+ /// new bounds. False when a group's members no longer share one pose, or one is hidden or changed:
/// the caller rebuilds, which groups them again. (Deforming meshes get no motion vectors of their own yet: an
/// instance's are its transform's.)
- pub(super) fn repose_groups(&mut self, world: &World, members: &[u32]) -> Result<bool> {
+ pub(super) fn repose_groups(&mut self, world: &World, members: &[u32], build: &mut gpu::TopBuild) -> Result<bool> {
use rayon::prelude::*;
if self.sc.up.accel.is_none() {
return Ok(false);
@@ -1332,27 +1322,16 @@ impl LiveCore {
pg.animation = a;
meshes.push(pg.mesh);
}
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_meshes(accel, &meshes, &mut e);
- let profile_blas = std::env::var("THREERT_PROFILE_BLAS").is_ok_and(|v| v == "1");
- if profile_blas {
- let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
- }
- let t_blas = Instant::now();
- q.submit([e.finish()]);
- if profile_blas {
- let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
- self.gpu_blas_ms += t_blas.elapsed().as_secs_f32() * 1000.0;
- }
+ build.meshes.extend(meshes);
self.cpu_upload_ms += t_up.elapsed().as_secs_f32() * 1000.0;
Ok(true)
}
- /// Re-skins posed models and re-transforms movable objects in place (hardware RT): their triangles, shading
- /// attributes and dynamic BLASes, then the TLAS. Their directly seen surfaces keep a short history for a moment,
+ /// Re-skins posed models and re-transforms movable objects in place (hardware RT): their triangles and shading
+ /// attributes; the commit builds the dynamic BLASes and the TLAS. Their directly seen surfaces keep a short history for a moment,
/// like a power edit (no per-object motion vectors). False when it cannot (not dynamic at build, no hardware RT, a
/// different triangle count): the caller rebuilds.
- pub(super) fn repose(&mut self, world: &World, ids: &std::collections::HashSet<u32>) -> Result<bool> {
+ pub(super) fn repose(&mut self, world: &World, ids: &std::collections::HashSet<u32>, build: &mut gpu::TopBuild) -> Result<bool> {
if self.sc.up.accel.is_none() || ids.iter().any(|id| !self.sc.tables.retained.dynamic.contains_key(id)) {
return Ok(false);
}
@@ -1370,7 +1349,7 @@ impl LiveCore {
self.keep_prev(both);
self.prev_span = Some((lo, hi));
self.reposed = true;
- // Upload the touched span of the dynamic tail, then rebuild the dynamic BLASes and the TLAS.
+ // Upload the touched span of the dynamic tail; the commit builds the dynamic BLASes and the TLAS.
let (q, up, (first, verts, attrs, blas)) = (&self.g.queue, &self.sc.up, &self.sc.dynamic);
let accel = up.accel.as_ref().unwrap();
let k = (first + lo) as u64;
@@ -1378,18 +1357,7 @@ impl LiveCore {
q.write_buffer(&up.attrs, k * 96, bytemuck::cast_slice(&attrs[lo..hi]));
q.write_buffer(&accel.verts, k * 36, bytemuck::cast_slice(&blas[lo * 3..hi * 3]));
up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_dynamic(accel, &mut e);
- let profile_blas = std::env::var("THREERT_PROFILE_BLAS").is_ok_and(|v| v == "1");
- if profile_blas {
- let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
- }
- let t_blas = Instant::now();
- q.submit([e.finish()]);
- if profile_blas {
- let _ = self.g.device.poll(wgpu::PollType::wait_indefinitely());
- self.gpu_blas_ms += t_blas.elapsed().as_secs_f32() * 1000.0;
- }
+ build.dynamic = true;
self.cpu_upload_ms += t_up.elapsed().as_secs_f32() * 1000.0;
Ok(true)
}
@@ -1531,7 +1499,7 @@ impl LiveCore {
/// rebuilt, one submit. Nothing is moved: what an edit replaces stays behind until the next rebuild. Err: why it
/// cannot (software traversal, the room is full, a kernel feature the scene lacks, an emitting / glass / function
/// material, ...); the caller rebuilds the scene then. `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
- pub(super) fn edit_geometry(&mut self, world: &World, ch: &crate::world::Changes) -> std::result::Result<(), String> {
+ pub(super) fn edit_geometry(&mut self, world: &World, ch: &crate::world::Changes, build: &mut gpu::TopBuild) -> std::result::Result<(), String> {
use crate::world::Kind;
if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {
return Err("THREERT_EDIT_REBUILD=1".into());
@@ -1573,7 +1541,6 @@ impl LiveCore {
}
};
let q = &g.queue;
- let mut e = g.device.create_command_encoder(&Default::default());
// An emitter mesh's entries go (area 0: their weight; the light tree keeps its shape) when it is removed, hidden
// or placed again.
let mut emitters_changed = false;
@@ -1641,7 +1608,6 @@ impl LiveCore {
proc_of.remove(id);
}
let mut new_meshes = vec![];
- let mut fresh_blases = vec![];
let mut pending_procs = vec![];
let mut split = EditSplit::default();
let (mut w_cdf, mut w_verts, mut w_attrs, mut w_blas, mut w_records, mut w_objects) = (Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default());
@@ -1739,7 +1705,7 @@ impl LiveCore {
}
w_cdf.put((header * 4) as u64, bytemuck::cast_slice(&words));
edit.word += words.len();
- let blas = g.proc_blas(&p.blob, &mut pending_procs, &mut fresh_blases);
+ let blas = g.proc_blas(&p.blob, &mut pending_procs);
let entry = p.object_entry(o);
let gpu = p.gpu(header as u32);
let record = at.map(|(_, r)| r);
@@ -2102,40 +2068,24 @@ impl LiveCore {
w_objects.flush_section(q, &up.heap, Table::Objects);
split.upload += tw.elapsed().as_secs_f64() * 1e3;
let t3 = Instant::now();
- new_meshes.sort_unstable();
- new_meshes.dedup();
- // The new meshes' and procedural BLASes and the TLAS in one build (`Gpu::build_meshes`).
- match &mut top {
- gpu::Top::Hw(accel) => g.build_edit(accel, &new_meshes, &pending_procs, &mut e, true),
- // The trees are written; the meshes this edit freed give theirs back; the top tree over the units as they
- // are now (one that cannot be made: the scene is rebuilt).
- gpu::Top::Sw(units) => {
- for &k in &edit.dead_meshes {
- if let Some(old) = units.drop_tree(k) {
- g.fill_tree(&up.bg_parts.nodes, old);
- }
+ // Software traversal: the trees are written; the meshes this edit freed give theirs back.
+ if let gpu::Top::Sw(units) = &mut top {
+ for &k in &edit.dead_meshes {
+ if let Some(old) = units.drop_tree(k) {
+ g.fill_tree(&up.bg_parts.nodes, old);
}
- g.retop(units, &up.bg_parts.nodes)?;
}
}
split.blas += t3.elapsed().as_secs_f64() * 1e3;
- // THREERT_PROFILE_BLAS=1: the BLAS / TLAS builds' GPU time (the queue drained before and after; frame log
- // `blas`), as for the dynamic rebuilds.
- let profile_blas = std::env::var("THREERT_PROFILE_BLAS").is_ok_and(|v| v == "1");
- if profile_blas {
- let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
- }
- let t = Instant::now();
- q.submit([e.finish()]);
- g.keep_proc_blases(fresh_blases);
+ // The new meshes' and procedural BLASes and the TLAS (or the top tree over the units as they are now): the
+ // commit's one build (`build_top`).
+ build.instances = true;
+ build.meshes.extend(new_meshes);
+ build.procs.extend(pending_procs);
// Buffers that grew: the scene bind group over them.
if std::mem::take(&mut edit.rebind) {
g.rebind_scene(up);
}
- if profile_blas {
- let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
- self.gpu_blas_ms += t.elapsed().as_secs_f32() * 1000.0;
- }
// The uniform tables: entries the edits placed past what a uniform buffer holds read as its last one.
if g.uniform_tables && !edit.uniform_said {
let notes = gpu::uniform_overflow([0, (edit.objects.end * tables.stride) as u64, edit.records.end as u64, 0]);
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 7f226e8..1fd3d03 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -253,3 +253,72 @@ fn a_resized_view_is_a_view_built_at_that_size() {
live.set_display_scale(1.0);
assert!(!live.dynamic_res && live.render_scale == 0.75, "a fixed scale through another density");
}
+
+/// Moves and geometry edits a view takes in place, alone and several in one commit, against a view built from the
+/// world as it is then: the same picture, so the acceleration structures hold what moved, built once a commit
+/// (`LiveCore::build_top`). Each kind of object that
+/// moves its own way: triangles re-transformed (a movable mesh), an instance's transform (a mesh a body drives), an
+/// instanced object's copies, a mesh added and removed in place.
+#[test]
+fn moves_in_place_leave_what_a_build_does() {
+ 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 mut w = world();
+ let mesh = |own_blas| Kind::Mesh { geometry: 3, material: 1, own_blas, materials: vec![] };
+ w.set_object(13, "mover".into(), None, mesh(false), true, true).unwrap();
+ w.set_transform(13, Vec3::new(0.35, -0.45, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(14, "driven".into(), None, mesh(true), true, false).unwrap();
+ w.set_driven(14).unwrap();
+ w.set_transform(14, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(15, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![1], capacity: 2 }, true, false).unwrap();
+ let copies = |x: f32| [glam::Mat4::from_translation(Vec3::new(x, -0.5, 0.4)).to_cols_array(), glam::Mat4::from_translation(Vec3::new(0.6, 0.6, 0.8)).to_cols_array()].concat();
+ w.set_instances(15, 2, Some(copies(-0.7)), None, None).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let at = |x: f32, y: f32, z: f32| Vec3::new(x, y, z);
+ type Edit = (&'static str, Box<dyn Fn(&mut World)>);
+ let edits: Vec<Edit> = vec![
+ ("a movable mesh moved", Box::new(move |w| w.set_transform(13, at(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap())),
+ ("a driven mesh moved", Box::new(move |w| assert!(w.place_driven(14, at(-0.2, 0.3, 1.0), glam::Quat::from_rotation_z(-0.4))))),
+ ("an instanced object's copy moved", Box::new(move |w| w.set_instances(15, 2, Some(copies(-0.2)), None, None).unwrap())),
+ (
+ "all three moved at once",
+ Box::new(move |w| {
+ w.set_transform(13, at(0.5, -0.1, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ assert!(w.place_driven(14, at(-0.7, 0.1, 0.6), glam::Quat::IDENTITY));
+ w.set_instances(15, 2, Some(copies(-0.9)), None, None).unwrap();
+ }),
+ ),
+ (
+ "a mesh added, the driven one moved",
+ Box::new(move |w| {
+ w.set_object(16, "added".into(), None, mesh(true), true, false).unwrap();
+ w.set_transform(16, at(0.0, 0.65, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ assert!(w.place_driven(14, at(-0.3, -0.1, 1.1), glam::Quat::IDENTITY));
+ }),
+ ),
+ (
+ "the added mesh removed, the movable one moved",
+ Box::new(move |w| {
+ w.remove(16);
+ w.set_transform(13, at(0.2, 0.2, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }),
+ ),
+ ];
+ for (what, edit) in &edits {
+ edit(&mut w);
+ let builds = live.top_builds;
+ let rebuilt = live.commit(&mut w).unwrap();
+ // (Software traversal places some of these another way, and may rebuild: the picture holds either way.)
+ assert!(!(rebuilt && live.g.hwrt), "{what}: in place ({:?})", live.fallback);
+ assert_eq!(live.top_builds - builds, u32::from(!rebuilt), "{what}: one build above the triangles a commit, whatever moved");
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 24), picture(&mut fresh, 24));
+ // (0.02 to 0.08 steps as measured; 0.9 after a move with nothing built above the triangles.)
+ assert!(apart(&a, &b) < 0.2, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ }
+}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index a5f2157..72b3009 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -262,17 +262,22 @@ pub struct LiveCore {
/// That frame's trace pass alone (the path-tracing kernel: intersection and shading), ms; 0 without timestamps.
/// Frame log `trace`: the per-frame cost a geometry representation changes, without THREERT_PROFILE's stalls.
pub gpu_trace_ms: f32,
- /// This frame's geometry edits applied in place (`edit_geometry`: CPU ms, its BLAS / TLAS builds submitted), and
- /// scene rebuilds (ms) and, when edits fell back to one, why: summed over the frame's commits (a game event's and the
- /// frame script's), reset when the frame is logged. Fallbacks since the viewport opened.
+ /// This frame's geometry edits applied in place (`edit_geometry`: CPU ms), and scene rebuilds (ms) and, when
+ /// edits fell back to one, why: summed over the frame's commits (a game event's and the frame script's), reset
+ /// when the frame is logged. Fallbacks since the viewport opened.
/// Frame log `edit`, `rebuild`, `fallback`, `fallbacks`.
pub edit_ms: f32,
/// CPU time of this frame's in-place instance updates (`update_instanced`), ms.
pub instanced_ms: f32,
+ /// CPU time of this frame's builds above the triangles (`build_top`: one a commit, for whatever its edits
+ /// changed; none of their own times holds it), ms: summed and reset as `edit_ms`. Frame log `build`.
+ pub build_ms: f32,
pub edit_split: EditSplit,
pub rebuild_ms: f32,
pub fallback: Option<String>,
pub fallbacks: u32,
+ /// The commits that built above the triangles (`build_top`): one build each, whatever moved.
+ pub(super) top_builds: u32,
/// Path-tracing bounces for real-time frames (the offline preset uses more).
pub bounces: u32,
/// Ray tracing (true). Off (`set_rays`), the kernel traces the camera ray of each pixel and no other: no shadows,
@@ -353,10 +358,10 @@ pub struct LiveCore {
/// Samples per pixel of the last frame rendered (the kernel's sample buffer holds their sums).
shown_spp: u32,
/// CPU time of the last commit (ms): skinning and re-transforming moving objects (`reskin`, rigid instance poses), and
- /// uploading them with the dynamic BLAS / TLAS rebuild submitted (frame log `skin`, `upload`).
+ /// uploading them (frame log `skin`, `upload`; the build they leave is `build_ms`).
pub cpu_skin_ms: f32,
pub cpu_upload_ms: f32,
- /// THREERT_PROFILE_BLAS=1: GPU time of the last dynamic BLAS / TLAS rebuild (ms; frame log `blas`), measured by draining
+ /// THREERT_PROFILE_BLAS=1: GPU time of the last commit's build above the triangles (ms; frame log `blas`), measured by draining
/// the queue before it and waiting for it after (it stalls the frame: measurement runs only). The pass profile has
/// no timestamps for it (Metal cannot write them between acceleration-structure builds).
pub gpu_blas_ms: f32,
@@ -530,7 +535,7 @@ impl LiveCore {
// brings it, `gpu::loop_guard_of`.)
let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
.then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));
- let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ let mut core = LiveCore { top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.apply_post();
Ok(core)
diff --git a/renderer/src/live/session.rs b/renderer/src/live/session.rs
index 8787456..a54e66e 100644
--- a/renderer/src/live/session.rs
+++ b/renderer/src/live/session.rs
@@ -179,12 +179,12 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
use std::io::Write;
let line = serde_json::json!({
"t": start.elapsed().as_secs_f64() * 1e3, "interval": last_frame.elapsed().as_secs_f64() * 1e3, "start": t_frame.duration_since(prev_start).as_secs_f64() * 1e3,
- "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "top": core.top_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved, "kicks": s.kicks }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "build": core.build_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "top": core.top_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved, "kicks": s.kicks }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
});
writeln!(l, "{line}")?;
}
// (Summed over the frame's commits, a game event's and the frame script's: reset once logged.)
- (core.edit_ms, core.instanced_ms, core.edit_split, core.rebuild_ms, core.fallback) = (0.0, 0.0, EditSplit::default(), 0.0, None);
+ (core.edit_ms, core.instanced_ms, core.build_ms, core.edit_split, core.rebuild_ms, core.fallback) = (0.0, 0.0, 0.0, EditSplit::default(), 0.0, None);
prev_start = t_frame;
last_frame = Instant::now();
core.govern_resolution(opts.fps);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index c96ee70..270d16d 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -610,8 +610,8 @@ pub struct InstancedPlace {
/// 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 and
-/// rebuilds the TLAS only. Their glass / emissive / function triangles are flattened (shadow rays, emitter sampling):
+/// in the node's space, one BLAS built once), placed at object x node transform, so a new pose moves instances
+/// only. Their glass / emissive / function triangles are flattened (shadow rays, emitter sampling):
/// `rest`, re-transformed in place from `rest_local`.
#[derive(Clone, Default)]
pub struct RigidModel {
diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rs
index 8be0834..87daa65 100644
--- a/renderer/web/src/lib.rs
+++ b/renderer/web/src/lib.rs
@@ -542,7 +542,7 @@ pub fn frame_end(dt: f32) -> Result<String, JsValue> {
// (The frame's rebuilds and why, summed over its commits, an event's included; then cleared, as the native
// runner does when it logs a frame.)
let (rebuild_ms, fallback) = (std::mem::take(&mut v.core.rebuild_ms), v.core.fallback.take());
- (v.core.edit_ms, v.core.instanced_ms) = (0.0, 0.0);
+ (v.core.edit_ms, v.core.instanced_ms, v.core.build_ms) = (0.0, 0.0, 0.0);
Ok(json!({
"physics": physics.map(|s| json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved })),
"physics_ms": p1 - p0,
diff --git a/tests/render/skinning-shared-pose-live.ts b/tests/render/skinning-shared-pose-live.ts
index ead8d0b..0600f8b 100644
--- a/tests/render/skinning-shared-pose-live.ts
+++ b/tests/render/skinning-shared-pose-live.ts
@@ -1,14 +1,17 @@
// Shared poses follow the pose: two mannequins built in one pose (A_TPose) share one skinned mesh (scene::PoseGroup).
// From 0.08 s the frame script poses both Idle_Loop at 0.5 s, so the shared mesh is re-skinned live: the region where
-// the T pose's arm was (screen left, the forearm) shows the 1-nit sky behind it. A mesh left in its build pose keeps
-// the arm there. The second mannequin stands behind the camera.
+// the T pose's arm was (screen left, the forearm) shows the 1-nit sky behind it, and the chest is still there. The
+// ratio of the two: 2.13 in the offline render of this pose (skinning-pose.ts: the chest 0.47 nit under the sky); a
+// mesh left in its build pose keeps the arm there (about 1.1), a model that is no longer drawn shows sky in both
+// (1.0: its mesh built apart from the TLAS lost its instance, 2026-11-16). The second mannequin stands behind the
+// camera.
import { GLTFModel } from "@threert/scene";
import { defineGame } from "@threert/gameplay";
import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
export const test: TestMeta = {
- id: "animation/shared-pose-live", features: ["skinning", "animation", "movable"], reference: "analytic", temporal: true,
- metric: { kind: "radiance", region: [0.33, 0.45, 0.39, 0.48], expected: 1, tolerance: 0.02 },
+ id: "animation/shared-pose-live", features: ["skinning", "animation", "movable"], reference: "converged", temporal: true,
+ metric: { kind: "ratio", a: [0.33, 0.45, 0.39, 0.48], b: [0.47, 0.5, 0.53, 0.58], expected: 2.13, tolerance: 0.3 },
requires: ["assets/quaternius/ual/UAL1_Standard.glb"],
live: 30,
note: "both built in A_TPose (one group), both posed Idle_Loop at 0.5 s by the frame script; the other at z = 8",