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
Scene: one proxy an object (#146)
Yujiae7d3cff0f946
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 4497e6a..a4ab955 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2608,6 +2608,24 @@ the code before. A test holds moves and edits in place, alone and several in a cworld 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).+**One proxy an object (2026-11-17, scene step B, second part).** Where what an object draws landed was spread over+fourteen maps keyed by the object: nine the build filled (its object-table entry, its card, its dynamic triangles,+its instance, whether its moves are the instance's, its rigid model, its pose group, whether its mesh is its own,+its emitter mesh, its instanced copies), four the edits kept beside them for what they placed (its record, its+value as picks test it, an instanced range, the mesh it draws) and one for procedural objects. They are one table,+`scene::Retained::proxies`: `Proxy { object, card, draw }`, `Draw` = Fixed | Dynamic | Instance | Procedural |+Rigid | Instanced. A proxy holds the object's record; the record's value is in `instances[record]` or+`procs[record - the first procedural record]`, for what an edit places as for the build's, and a record's slot is+`inst_base` + it for all of them. "An edit placed it" is its record being the room's (`EditState::in_room`); a+mesh a body drives moves as an instance because its proxy says so, whoever placed it. Lights, media and particles+keep their tables' own indices (a table a kind). No picture changes (render-identity: 239 outputs), the voxel+level's debris and batch routes time as before. Two faults went with the maps, each shown by a test first: an+instanced object the build flattened had an entry in none of them, so removing it in place did nothing and it+stayed in the picture (it has a proxy now, and is rebuilt out); an instanced object an edit added had an object+entry of its own beside its copies', so its node's power or customData wrote over copy 0's. Still two mechanisms+in what they can do: what the build flattened or placed as a model's instance is rebuilt to change, what an edit+placed is not moved unless a body drives it (step E).+## 2. Temporal fixesTargets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); thediff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex f1904ae..477a193 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`). 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"}`. |+| 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`. Where what an object draws landed is its proxy (`scene::Retained::proxies`: its object-table entry and how its geometry is held, with its record), for what the build placed and what an edit placed alike; edits in place read and keep it. 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.rsindex 8cea2c1..595e066 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -167,7 +167,7 @@ impl EditRoom {/// Whether the scene gets room (`for_scene`): editable geometry under hardware RT, or under software traversal/// with units (`hwrt` true for them too: `lib.rs prepare`).pub fn editable(scene: &Scene, hwrt: bool) -> bool {- hwrt && Self::reserve() > 0.0 && (!scene.procs.is_empty() || !scene.retained.own_instance.is_empty())+ hwrt && Self::reserve() > 0.0 && (!scene.procs.is_empty() || scene.retained.has_own_instances())}/// `units`: software traversal with units, whose room does not grow (hardware traversal's does, from nothing): a@@ -175,7 +175,7 @@ impl EditRoom {/// it has (a mesh it has not rebuilds the scene: no triangles).pub(crate) fn for_scene(scene: &Scene, tris: usize, records: usize, hwrt: bool, units: bool) -> EditRoom {let k = Self::reserve();- let (procs, meshes) = (!scene.procs.is_empty(), !scene.retained.own_instance.is_empty());+ let (procs, meshes) = (!scene.procs.is_empty(), scene.retained.has_own_instances());let part = |n: usize, min: usize| ((n as f64 * 0.25 * k) as usize).max((min as f64 * k) as usize);if !Self::editable(scene, hwrt || units) {return if units && k > 0.0 {@@ -823,14 +823,6 @@ impl<'a> Top<'a> {}}- /// The slot of the first procedural object (`proc_first`: its record).- pub fn proc_base(&self, proc_first: usize) -> usize {- match self {- Top::Hw(a) => a.proc_base,- Top::Sw(_) => proc_first,- }- }-pub fn sw(&self) -> bool {matches!(self, Top::Sw(_))}diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 8b1469e..bcc9f8e 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -546,10 +546,10 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutv};// Posed models: where each of their triangles landed (they are re-skinned in place, hardware RT only).- if hwrt && (!sc.retained.dynamic.is_empty() || !sc.retained.rigid.is_empty() || !sc.particles.is_empty() || !sc.gpu_particles.is_empty()) {+ if hwrt && (sc.retained.dynamics_mut().next().is_some() || !sc.particles.is_empty() || !sc.gpu_particles.is_empty()) {let first_dynamic: usize = groups[..4].iter().sum();let finals: std::collections::HashMap<u32, u32> = bvh.order[first_dynamic..].iter().enumerate().map(|(k, &i)| (i, (first_dynamic + k) as u32)).collect();- for d in sc.retained.dynamic.values_mut().chain(sc.retained.rigid.values_mut().map(|r| &mut r.rest)) {+ for d in sc.retained.dynamics_mut() {d.finals = (0..d.mats.len() as u32).map(|j| finals[&(d.first + j)]).collect();}// A particle system's triangles stay together (one group, the order within a group is the build order).diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex db26cf6..4ec181b 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -87,10 +87,9 @@ pub(super) struct EditState {/// The next procedural word, and where the region (grown as needed) ends.pub(super) word: usize,pub(super) word_cap: usize,- /// The instanced mesh each object edits manage draws (`own_blas`: the build's and theirs), each mesh's objects, the- /// meshes edits may free (own-BLAS meshes: shared only by objects of one geometry and material), and the slots of- /// freed ones, reused by the next new mesh.- pub(super) mesh_of: std::collections::HashMap<u32, u32>,+ /// How many objects draw each instanced mesh (an instanced object counts once), the meshes edits may free+ /// (own-BLAS meshes: shared only by objects of one geometry and material), and the slots of freed ones, reused by+ /// the next new mesh.pub(super) users: std::collections::HashMap<u32, u32>,pub(super) managed: std::collections::HashSet<u32>,pub(super) dead_meshes: Vec<u32>,@@ -106,14 +105,13 @@ pub(super) struct EditState {pub(super) pool_first: usize,/// Procedural blobs in the region by hash: their first word (the build's and those edits wrote).pub(super) blobs: std::collections::HashMap<[u8; 32], usize>,- /// Objects edits added: their (TLAS instance, record); instanced meshes edits added: their first record, capacity- /// and first object entry (contiguous, as `update_instanced` rewrites them).- pub(super) placed: std::collections::HashMap<u32, (usize, usize)>,- pub(super) instanced: std::collections::HashMap<u32, (usize, usize, usize)>,- /// The build's model instances (records below are theirs, in `LoadedScene::instances` order).- pub(super) inst_at_load: usize,- /// What clicks pick among the objects edits added (`LiveCore::pick`; the build's are `instances` and `procs`).- pub(super) added: std::collections::BTreeMap<u32, Picked>,+}++impl EditState {+ /// Whether `record` is one of the room's: an edit placed what is there (the build's are below).+ pub(super) fn in_room(&self, record: usize) -> bool {+ record >= self.base.1+ }}/// Ranges of one kind of the edit room: free holes (start -> length; first fit, neighbours merged) below `end`, the@@ -173,16 +171,11 @@ impl Holes {}}-/// An object an edit placed, as `LiveCore::pick` tests it.-pub(super) enum Picked {- Mesh(scene::Instance),- Proc(scene::ProcObject),-}--/// What an edit places at an object's slot: a procedural object's BLAS (hardware traversal), or instanced mesh `k`.+/// What an edit places at an object's record: a procedural object with its BLAS (hardware traversal), or an instance+/// of a mesh.pub(super) enum Placed {- Proc(wgpu::Blas),- Mesh(u32),+ Proc(wgpu::Blas, scene::ProcObject),+ Mesh(scene::Instance),}/// One object fewer draws instanced mesh `k`: a mesh edits manage that none draws any more is freed (its triangles a@@ -289,14 +282,18 @@ impl Grow<'_> {}}-/// An object removed or hidden in place: no longer picked until the next rebuild (`LiveCore::pick`).-pub(super) fn unpick(id: u32, edit: &mut EditState, tables: &tables::Tables, instances: &mut [scene::Instance], procs: &mut [scene::ProcObject], proc_of: &std::collections::HashMap<u32, usize>) {- edit.added.remove(&id);- if let Some(i) = tables.retained.own_instance.get(&id).and_then(|&k| instances.get_mut(k as usize)) {- i.hidden = true;- }- if let Some(p) = proc_of.get(&id).and_then(|&j| procs.get_mut(j)) {- p.hidden = true;+/// An object removed or hidden in place is no longer drawn: hidden where its record's value is (`LiveCore::pick`+/// skips it). The mesh it was an instance of, if it was drawn as one: a user fewer (`drop_mesh_user`).+pub(super) fn undraw(draw: Option<&scene::Draw>, instances: &mut [scene::Instance], procs: &mut [scene::ProcObject]) -> Option<u32> {+ match draw? {+ scene::Draw::Instance(i) => instances.get_mut(i.instance as usize).and_then(|i| (!std::mem::replace(&mut i.hidden, true)).then_some(i.mesh)),+ scene::Draw::Procedural(j) => {+ if let Some(p) = procs.get_mut(*j as usize) {+ p.hidden = true;+ }+ None+ }+ _ => None,}}@@ -367,9 +364,14 @@ impl LiveCore {changes.structural = true;}}- // Objects added in place are not in the move tables (their records follow the scene's): a move rebuilds. Not a- // mesh a body drives: it is an instance, and its record moves as the build's do (`placed_movable`).- if !changes.structural && changes.moved.iter().any(|id| self.sc.edit.placed.contains_key(id) && self.placed_movable(world, *id).is_none()) {+ // An object an edit placed (its record is the room's) moves in place only as an instance does: a mesh a body+ // drives, while it is drawn. Any other rebuilds.+ let stuck = |id: &u32| match self.sc.tables.retained.proxies.get(id).map(|p| &p.draw) {+ Some(scene::Draw::Instance(i)) => self.sc.edit.in_room(i.instance as usize) && !(i.moves && self.sc.instances.get(i.instance as usize).is_some_and(|i| !i.hidden)),+ Some(scene::Draw::Procedural(j)) => self.sc.edit.in_room(self.sc.proc_first + *j as usize),+ _ => false,+ };+ if !changes.structural && changes.moved.iter().any(stuck) {self.fallback = Some("an object added in place moved".into());self.fallbacks += 1;changes.structural = true;@@ -428,9 +430,9 @@ impl LiveCore {if world.shown(k) {// Movable models placed as instances move their transform (with a shared pose too); the rest// re-transform triangles.- let r = &self.sc.tables.retained;- match r.instance_of.get(&k).copied().or_else(|| self.placed_movable(world, k)) {- Some(i) if !changes.poses.contains(&k) || r.pose_member.contains_key(&k) => placed.push((k, i)),+ let inst = self.sc.tables.retained.instance(k).filter(|i| i.moves).copied();+ match inst.map(|i| i.instance) {+ Some(i) if !changes.poses.contains(&k) || inst.is_some_and(|i| matches!(i.mesh, scene::MeshKind::Pose(_))) => placed.push((k, i)),_ => {dynamic.insert(k);}@@ -467,12 +469,12 @@ impl LiveCore {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();+ let rigid: Vec<u32> = dynamic.iter().copied().filter(|k| self.sc.tables.retained.rigid(*k).is_some()).collect();for k in &rigid {dynamic.remove(k);}// Models in a shared pose re-skin their group's mesh (`repose_groups`, its BLAS only); their moves place instances.- let shared: Vec<u32> = dynamic.iter().copied().filter(|k| self.sc.tables.retained.pose_member.contains_key(k)).collect();+ let shared: Vec<u32> = dynamic.iter().copied().filter(|k| self.sc.tables.retained.instance(*k).is_some_and(|i| matches!(i.mesh, scene::MeshKind::Pose(_)))).collect();for k in &shared {dynamic.remove(k);}@@ -744,12 +746,7 @@ impl LiveCore {// (Instances the last update moved and this one does not catch up in `commit`.)for &(node, i) in placed {let w = world.world_matrix(node);- // (A mesh an edit added in place keeps its instance with the edit's, `placed_movable`; its record and TLAS- // instance are where the build's are.)- let inst = match self.sc.edit.added.get_mut(&node) {- Some(Picked::Mesh(inst)) => inst,- _ => &mut self.sc.instances[i as usize],- };+ let inst = &mut self.sc.instances[i as usize];// (Software traversal: an instance of a mesh that deforms is no unit; its triangles are among the still// scene's, in the world, and a rebuild moves them.)if !top.has_mesh(inst.mesh) {@@ -793,14 +790,6 @@ impl LiveCore {self.sc.up.heap.write(&self.g.queue, Table::Materials, 0, bytes);}- /// The record of a mesh an edit added in place that moves as an instance does (`move_instances`): one a rigid body- /// drives, placed by its node's transform (an emitter mesh's triangles are in world space: it cannot).- pub(super) fn placed_movable(&self, world: &World, id: u32) -> Option<u32> {- let &(_, record) = self.sc.edit.placed.get(&id)?;- let mesh = matches!(self.sc.edit.added.get(&id), Some(Picked::Mesh(_)));- (mesh && world.objects.get(&id).is_some_and(|o| o.driven) && !self.sc.tables.retained.emitter_mesh.contains_key(&id)).then_some(record as u32)- }-/// `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], changes: &mut crate::world::Changes, build: &mut gpu::TopBuild) -> bool {@@ -1051,8 +1040,8 @@ impl LiveCore {// (Removed or hidden: nothing is drawn; a structural change rebuilds.)let Some(n) = world.objects.get(&id).filter(|_| world.shown(id)) else { continue };let Kind::Instanced { capacity, procedural, .. } = n.kind else { continue };- let Some(&place) = sc.tables.retained.instanced.get(&id) else { return Err("an instanced mesh the build flattened".into()) };- if place.capacity != capacity || place.procedural != procedural {+ let Some(&place) = sc.tables.retained.instanced(id) else { return Err("an instanced mesh the build flattened".into()) };+ if place.capacity != capacity || place.mesh.is_none() != procedural {return Err("an instanced mesh the build placed otherwise".into());}let t = world.instanced.get(&id).unwrap_or(&empty);@@ -1064,7 +1053,9 @@ impl LiveCore {if procedural && top.sw() {return Err("a procedural instanced mesh (software traversal)".into());}- let (rec0, slot0) = if procedural { (sc.proc_first + first, top.proc_base(sc.proc_first) + first) } else { (first, top.inst_base() + first) };+ // (A record's slot is `inst_base` + it, a procedural copy's record the first procedural one + its index.)+ let rec0 = if procedural { sc.proc_first + first } else { first };+ let slot0 = top.inst_base() + rec0;for i in 0..cap {let (wm, hidden) = scene::instance_world(m, t, i);if !procedural && !hidden && wm.determinant() < 0.0 {@@ -1101,7 +1092,9 @@ impl LiveCore {let at = place.object as usize * st;sc.up.heap.write(q, Table::Objects, (at * 16) as u64, bytemuck::cast_slice(&sc.tables.objects[at..at + cap * st]));self.inst_moving.extend(rec0 as u32..(rec0 + cap) as u32);- sc.tables.retained.instanced.get_mut(&id).unwrap().drawn = t.count;+ if let Some(scene::Draw::Instanced(place)) = sc.tables.retained.proxies.get_mut(&id).map(|p| &mut p.draw) {+ place.drawn = t.count;+ }done += 1;}if done > 0 {@@ -1117,7 +1110,8 @@ impl LiveCore {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 };+ let Some(&scene::Draw::Procedural(j)) = self.sc.tables.retained.proxies.get(id).map(|p| &p.draw) else { continue };+ let j = j as usize;let w = world.world_matrix(*id);let p = &mut self.sc.procs[j];p.world = w;@@ -1132,7 +1126,7 @@ impl LiveCore {let o = &mut self.sc.tables.objects[p.object as usize * st];(o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);if let Some(accel) = self.sc.up.accel.as_mut() {- if let Some(t) = accel.tlas[accel.proc_base + j].as_mut() {+ if let Some(t) = accel.tlas[accel.inst_base + i].as_mut() {t.transform = gpu::tlas_rows(w);}}@@ -1162,7 +1156,7 @@ 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];+ let r = self.sc.tables.retained.rigid(*id).expect("a rigid model (`commit`)");placements.extend(r.instances.iter().map(|&(node, i)| (i, m * globals[node])));let d = &r.rest;if d.finals.len() != d.mats.len() {@@ -1245,7 +1239,11 @@ impl LiveCore {return Ok(false);}let r = &self.sc.tables.retained;- let mut touched: Vec<u32> = members.iter().map(|k| r.pose_member[k]).collect();+ let group = |k: &u32| match r.instance(*k).map(|i| i.mesh) {+ Some(scene::MeshKind::Pose(g)) => g,+ _ => unreachable!("a pose group's member (`commit`)"),+ };+ let mut touched: Vec<u32> = members.iter().map(group).collect();touched.sort_unstable();touched.dedup();let mut jobs: Vec<(u32, crate::desc::Animation)> = vec![];@@ -1332,14 +1330,19 @@ impl LiveCore {/// 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>, 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);- }- let models = std::mem::take(&mut self.sc.tables.retained.dynamic);+ let dynamic = |p: &mut scene::Proxy| match &mut p.draw {+ scene::Draw::Dynamic(d) => Some(std::mem::take(d)),+ _ => None,+ };+ // (Their models out of the proxies while `reskin` has the scene, then back.)+ let proxies = &mut self.sc.tables.retained.proxies;+ let models: std::collections::HashMap<u32, scene::DynamicModel> = ids.iter().filter_map(|id| Some((*id, dynamic(proxies.get_mut(id)?)?))).collect();let t_skin = Instant::now();- let res = self.reskin(world, ids, &models);+ let res = if self.sc.up.accel.is_none() || models.len() < ids.len() { Ok(None) } else { self.reskin(world, ids, &models) };self.cpu_skin_ms += t_skin.elapsed().as_secs_f32() * 1000.0;- self.sc.tables.retained.dynamic = models;+ for (id, d) in models {+ self.sc.tables.retained.proxy(id).draw = scene::Draw::Dynamic(d);+ }let Some((lo, hi)) = res? else { return Ok(false) };self.emitters_moved = true;let t_up = Instant::now();@@ -1504,7 +1507,7 @@ impl LiveCore {if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {return Err("THREERT_EDIT_REBUILD=1".into());}- let LoadedScene { up, tables, edit, meshes, pool_tris, instances, gpu_instances, procs, proc_of, proc_first, .. } = &mut self.sc;+ let LoadedScene { up, tables, edit, meshes, pool_tris, instances, gpu_instances, procs, proc_first, moving_instances, .. } = &mut self.sc;let (g, assets) = (&self.g, &self.assets);let features = up.kernel.features;let grow = Grow { g: &self.g, ok: up.particles.is_none() && up.gpu_particles.is_none() };@@ -1530,22 +1533,24 @@ impl LiveCore {}}}- let (inst_base, proc_base, proc_first) = (top.inst_base(), top.proc_base(*proc_first), *proc_first);- let slot_of = |id: u32, edit: &EditState, tables: &tables::Tables, proc_of: &std::collections::HashMap<u32, usize>| -> Option<(usize, usize)> {- if let Some(&v) = edit.placed.get(&id) {- Some(v)- } else if let Some(&k) = tables.retained.own_instance.get(&id) {- Some((inst_base + k as usize, k as usize))- } else {- proc_of.get(&id).map(|&j| (proc_base + j, proc_first + j))- }+ let (inst_base, proc_first) = (top.inst_base(), *proc_first);+ // An object's (slot, record), where an edit can place it again or take it out: an instance of a mesh that is+ // its own, or that an edit placed (a model the build placed is the build's to change), or procedural geometry.+ let slot_of = |id: u32, edit: &EditState, tables: &tables::Tables| -> Option<(usize, usize)> {+ let record = match &tables.retained.proxies.get(&id)?.draw {+ scene::Draw::Instance(i) if i.mesh.own() || edit.in_room(i.instance as usize) => i.instance as usize,+ scene::Draw::Procedural(j) => proc_first + *j as usize,+ _ => return None,+ };+ Some((inst_base + record, record))};let q = &g.queue;// 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;let release = |id: u32, tables: &mut tables::Tables, meshes: &[scene::InstMesh], pool_first: usize| -> bool {- let Some(k) = tables.retained.emitter_mesh.remove(&id) else { return false };+ let Some(scene::Draw::Instance(inst)) = tables.retained.proxies.get_mut(&id).map(|p| &mut p.draw) else { return false };+ let scene::MeshKind::Emitter(k) = std::mem::replace(&mut inst.mesh, scene::MeshKind::Own) else { return false };let im = meshes[k as usize];let (lo, hi) = ((pool_first + im.first as usize) as u32, (pool_first + (im.first + im.count) as usize) as u32);for e in tables.emitter_tris.iter_mut().filter(|e| (lo..hi).contains(&e.tri)) {@@ -1554,58 +1559,45 @@ impl LiveCore {true};for id in &ch.removed {- // An instanced mesh an edit added: its instances, records and entries.- if let Some((r0, cap, o0)) = edit.instanced.remove(id) {+ // An instanced mesh: its instances out. One an edit placed gives its records and entries back to the room+ // and its mesh a user fewer (the build's stay until the next rebuild).+ if let Some((place, mesh)) = tables.retained.instanced(*id).and_then(|p| Some((*p, p.mesh?))) {+ let (r0, cap) = (place.first as usize, place.capacity as usize);for r in r0..r0 + cap {top.clear(inst_base + r);if let Some(i) = instances.get_mut(r) {i.hidden = true;}}- edit.records.give(r0, cap);- edit.objects.give(o0, cap);- tables.retained.instanced.remove(id);- tables.retained.objects.remove(id);- if let Some(k) = edit.mesh_of.remove(id) {- drop_mesh_user(k, edit, tables, meshes);- }- continue;- }- // An instanced mesh the build placed: its instances out (records and entries stay until the next rebuild).- if let Some(place) = tables.retained.instanced.get(id).filter(|p| !p.procedural) {- for r in place.first as usize..(place.first + place.capacity) as usize {- top.clear(inst_base + r);- if let Some(i) = instances.get_mut(r) {- i.hidden = true;- }+ if edit.in_room(r0) {+ edit.records.give(r0, cap);+ edit.objects.give(place.object as usize, cap);+ drop_mesh_user(mesh, edit, tables, meshes);}- tables.retained.instanced.remove(id);- tables.retained.objects.remove(id);+ tables.retained.proxies.remove(id);continue;}emitters_changed |= release(*id, tables, meshes, edit.pool_first);- let at = slot_of(*id, edit, tables, proc_of);- // Placed by the build otherwise (a model, a procedural instanced mesh): a rebuild takes it out.- if at.is_none() && tables.retained.objects.contains_key(id) {- return Err("an object the build placed otherwise (a model, a procedural instanced mesh) removed".into());+ let at = slot_of(*id, edit, tables);+ // Drawn, and not at a record an edit can clear (a model the build placed, anything it flattened): a rebuild+ // takes it out.+ if at.is_none() && tables.retained.proxies.contains_key(id) {+ return Err("an object the build placed otherwise (a model, something it flattened) removed".into());}- if let Some((slot, _)) = at {+ let proxy = tables.retained.proxies.remove(id);+ if let Some((slot, record)) = at {top.clear(slot);+ if let Some(k) = undraw(proxy.as_ref().map(|p| &p.draw), instances, procs) {+ drop_mesh_user(k, edit, tables, meshes);+ }+ // What it held goes back to the room (the build's records and entries stay until the next rebuild).+ if edit.in_room(record) {+ edit.records.give(record, 1);+ }}- unpick(*id, edit, tables, instances, procs, proc_of);- // What it held goes back to the room (the build's records and entries stay until the next rebuild).- if let Some((_, r)) = edit.placed.remove(id) {- edit.records.give(r, 1);- }- if let Some(k) = edit.mesh_of.remove(id) {- drop_mesh_user(k, edit, tables, meshes);- }- tables.retained.own_instance.remove(id);- tables.retained.instance_of.remove(id);- if let Some(k) = tables.retained.objects.remove(id).filter(|&k| k as usize >= edit.base.2) {+ if let Some(k) = proxy.and_then(|p| p.object).filter(|&k| k as usize >= edit.base.2) {edit.objects.give(k as usize, 1);}- proc_of.remove(id);}let mut new_meshes = vec![];let mut pending_procs = vec![];@@ -1619,28 +1611,31 @@ impl LiveCore {let mask = |shadow: bool| if shadow { 1 } else { 2 };for id in todo {let Some(o) = world.objects.get(&id) else { continue };- let at = slot_of(id, edit, tables, proc_of);+ let at = slot_of(id, edit, tables);emitters_changed |= release(id, tables, meshes, edit.pool_first);if !world.shown(id) {if let Some((slot, _)) = at {top.clear(slot);}- if edit.instanced.contains_key(&id) {+ if tables.retained.instanced(id).is_some_and(|p| edit.in_room(p.first as usize)) {return Err("an instanced mesh added in place hidden".into());}- unpick(id, edit, tables, instances, procs, proc_of);- if let Some(k) = edit.mesh_of.remove(&id) {+ if let Some(k) = undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs) {drop_mesh_user(k, edit, tables, meshes);}continue;}+ // The mesh it draws now, as an instance at its record: a user fewer once it is placed again (below).+ let was = at.and_then(|(_, r)| instances.get(r)).filter(|i| !i.hidden).map(|i| i.mesh);// Drawn but not by a TLAS instance of its own: the build flattened it (movable, or a material instances skip).- if at.is_none() && tables.retained.objects.contains_key(&id) {+ if at.is_none() && tables.retained.proxies.contains_key(&id) {return Err("an object the build flattened".into());}let m = world.world_matrix(id);- let object = match tables.retained.objects.get(&id) {- Some(&k) => k as usize,+ // (The emitter mesh it is placed as, if it is one: its proxy's, below.)+ let mut emitter = None;+ let object = match tables.retained.object(id) {+ Some(k) => k as usize,None => match edit.objects.take(1) {Some(k) => k,None if grow.objects(&mut edit.objects, 1, &mut up.heap, tables.stride) => {@@ -1667,7 +1662,7 @@ impl LiveCore {if let Some((slot, _)) = at {top.clear(slot);}- unpick(id, edit, tables, instances, procs, proc_of);+ undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs);continue;};placement = m;@@ -1708,14 +1703,7 @@ impl LiveCore {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);- match proc_of.get(&id) {- Some(&j) => procs[j] = p,- None => {- edit.added.insert(id, Picked::Proc(p));- }- }- (record, gpu, Placed::Proc(blas), entry)+ (at.map(|(_, r)| r), gpu, Placed::Proc(blas, p), entry)}Kind::Mesh { materials, .. } if materials.len() > 1 => return Err("a mesh with several materials".into()),Kind::Model { uri, nodes, animation, functions } => {@@ -1736,15 +1724,14 @@ impl LiveCore {return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into());}*edit.users.entry(mesh).or_default() += 1;- if let Some(k) = edit.mesh_of.insert(id, mesh) {+ if let Some(k) = was {drop_mesh_user(k, edit, tables, meshes);}let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false };let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);let (lo, hi) = im.placed_bounds(m);let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);- edit.added.insert(id, Picked::Mesh(inst));- (at.map(|(_, r)| r), gpu, Placed::Mesh(mesh), entry)+ (at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)}Kind::Mesh { own_blas: true, .. } | Kind::Instanced { procedural: false, .. } => {// An own-BLAS mesh, or (added in place) an instanced mesh: their mesh made alike.@@ -1793,7 +1780,10 @@ impl LiveCore {if let Some((slot, _)) = at {top.clear(slot);}- unpick(id, edit, tables, instances, procs, proc_of);+ // (No longer drawn: its mesh a user fewer now, as when it is hidden.)+ if let Some(k) = undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs) {+ drop_mesh_user(k, edit, tables, meshes);+ }continue;}// Software traversal: the mesh's tree, and its triangles (their attributes, further down their@@ -1922,7 +1912,7 @@ impl LiveCore {}}}- tables.retained.emitter_mesh.insert(id, k);+ emitter = Some(k);tables.emissive.insert(mat);emitters_changed = true;}@@ -1936,7 +1926,7 @@ impl LiveCore {let im = meshes[mesh as usize];// It draws `mesh` now (and no longer the one it drew, if another).*edit.users.entry(mesh).or_default() += 1;- if let Some(k) = edit.mesh_of.insert(id, mesh) {+ if let Some(k) = was {drop_mesh_user(k, edit, tables, meshes);}if let Some(cap) = capacity {@@ -1951,9 +1941,8 @@ impl LiveCore {if placed.iter().any(|(wm, hidden)| !hidden && wm.determinant() < 0.0) {return Err("a mirrored instance (the build flattens them)".into());}- if !tables.retained.objects.contains_key(&id) {- edit.objects.give(object, 1);- }+ // (An entry a copy, below: not the one an object has.)+ edit.objects.give(object, 1);let r0 = match edit.records.take(cap) {Some(r) => r,None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {@@ -1995,9 +1984,7 @@ impl LiveCore {tables.objects[(o0 + i) * st..(o0 + i + 1) * st].copy_from_slice(&entry[..st]);instances[r0 + i] = inst;}- tables.retained.instanced.insert(id, scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, procedural: false, drawn: t.count });- tables.retained.objects.insert(id, o0 as u32);- edit.instanced.insert(id, (r0, cap, o0));+ *tables.retained.proxy(id) = scene::Proxy { object: None, card: None, draw: scene::Draw::Instanced(scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, mesh: Some(mesh), drawn: t.count }) };continue;}if emits {@@ -2007,14 +1994,7 @@ impl LiveCore {let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);let (lo, hi) = im.placed_bounds(placement);let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);- let record = at.map(|(_, r)| r);- match record.filter(|&r| r < edit.inst_at_load) {- Some(r) => instances[r] = inst,- None => {- edit.added.insert(id, Picked::Mesh(inst));- }- }- (record, gpu, Placed::Mesh(mesh), entry)+ (at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)}_ => return Err("not an object with its own BLAS".into()),};@@ -2031,9 +2011,7 @@ impl LiveCore {}None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: records (software traversal's does not grow)" } else { "edit room: records (particles, or the device's limits)" }.into()),};- let v = (inst_base + r, r);- edit.placed.insert(id, v);- v+ (inst_base + r, r)}};w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));@@ -2041,11 +2019,33 @@ impl LiveCore {gpu_instances.resize(record + 1, scene::GpuInstance::default());}gpu_instances[record] = gpu;- let custom = if matches!(o.kind, Kind::Procedural { .. }) { record as u32 } else { gpu::INSTANCE_BIT | record as u32 };- match blas {- Placed::Proc(blas) => top.place_blas(slot, &blas, placement, custom, mask(o.cast_shadow)),- Placed::Mesh(k) => top.place(slot, k, placement, custom, o.cast_shadow, false),- }+ // Above the triangles, and the record's value where the build's are: `instances[record]`, or `procs` at the+ // record less the first procedural one (hidden fillers at the records between, which are other objects').+ let draw = match blas {+ Placed::Proc(blas, p) => {+ top.place_blas(slot, &blas, placement, record as u32, mask(o.cast_shadow));+ let j = record - proc_first;+ if procs.len() <= j {+ procs.resize(j + 1, scene::ProcObject { name: String::new(), materials: vec![], hidden: true, ..p.clone() });+ }+ procs[j] = p;+ scene::Draw::Procedural(j as u32)+ }+ Placed::Mesh(inst) => {+ top.place(slot, inst.mesh, placement, gpu::INSTANCE_BIT | record as u32, o.cast_shadow, false);+ if instances.len() <= record {+ instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() });+ }+ let mesh = match (&o.kind, emitter) {+ (_, Some(k)) => scene::MeshKind::Emitter(k),+ (Kind::Model { .. }, _) => scene::MeshKind::Model,+ _ => scene::MeshKind::Own,+ };+ instances[record] = inst;+ // (A mesh a body drives moves as an instance does, as the build's: `commit`.)+ scene::Draw::Instance(scene::InstanceRef { instance: record as u32, mesh, moves: o.driven })+ }+ };let st = tables.stride;w_objects.put((object * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));let at = object * st;@@ -2053,7 +2053,7 @@ impl LiveCore {tables.objects.resize(at + st, [0.0; 4]);}tables.objects[at..at + st].copy_from_slice(&entry[..st]);- tables.retained.objects.insert(id, object as u32);+ *tables.retained.proxy(id) = scene::Proxy { object: Some(object as u32), card: None, draw };}// The gathered writes, merged, before the builds that read them.let tw = Instant::now();@@ -2082,6 +2082,7 @@ impl LiveCore {build.instances = true;build.meshes.extend(new_meshes);build.procs.extend(pending_procs);+ *moving_instances = tables.retained.moves_instances();// Buffers that grew: the scene bind group over them.if std::mem::take(&mut edit.rebind) {g.rebind_scene(up);diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex 5d8410f..087e7b6 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -368,6 +368,8 @@ impl LiveCore {self.light_tiles = None;}let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));+ // Something moves (triangles re-transformed, instances' transforms): the kernel writes motion vectors.+ let moving = !self.sc.dynamic.1.is_empty() || self.sc.moving_instances;for k in 0..spp.max(1) {let mut p = self.sc.base;if let Some((row, at, size, cam)) = self.light_tiles {@@ -381,7 +383,7 @@ impl LiveCore {}p.raster = [(self.raster.is_some() && !self.sc.instanced) as u32 as f32, jitter.0, jitter.1, 0.0];p.raster[3] = if self.rays { 0.0 } else { 1.0 };- if !self.sc.dynamic.1.is_empty() || !self.sc.tables.retained.instance_of.is_empty() || !self.sc.tables.retained.rigid.is_empty() {+ if moving {// The kernel finds the first dynamic triangle in Params::group_first (group 4), a u32.p.motion[0] = 1.0;}diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 1fd3d03..20bf5ff 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -322,3 +322,59 @@ fn moves_in_place_leave_what_a_build_does() {assert!(apart(&a, &b) < 0.2, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));}}++/// An instanced object the build flattened (an emitting material: its copies are triangles of the static groups)+/// is gone from the picture once it is removed: nothing takes it out in place, so the scene is rebuilt.+#[test]+fn a_flattened_instanced_object_removed_is_gone() {+ 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();+ w.set_object(15, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![5], capacity: 2 }, true, false).unwrap();+ let copies = [glam::Mat4::from_translation(Vec3::new(-0.6, -0.5, 0.4)).to_cols_array(), glam::Mat4::from_translation(Vec3::new(0.5, 0.6, 0.8)).to_cols_array()].concat();+ w.set_instances(15, 2, Some(copies), None, None).unwrap();+ let mut live = match open(&w) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let with = picture(&mut live, 24);+ w.remove(15);+ live.commit(&mut w).unwrap();+ let mut fresh = open(&w).unwrap();+ forget(&mut live);+ let (a, b) = (picture(&mut live, 24), picture(&mut fresh, 24));+ assert!(apart(&with, &b) > 1.0, "the copies were in the picture ({:.2} steps)", apart(&with, &b));+ assert!(apart(&a, &b) < 0.2, "removed: the picture is {:.2} steps from a build's without it", apart(&a, &b));+}++/// An instanced object an edit added in place keeps each copy's own data when its node's data changes, as one the+/// build placed does: the objects table's entries of its copies against a build's.+#[test]+fn an_instanced_object_added_in_place_keeps_its_copies_data() {+ 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();+ // (A mesh with its own BLAS: the scene has instances, so another instanced mesh is added in place.)+ w.set_object(14, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();+ w.set_transform(14, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).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();+ w.set_object(17, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![1], capacity: 2 }, true, false).unwrap();+ let copies = [glam::Mat4::from_translation(Vec3::new(-0.6, -0.5, 0.4)).to_cols_array(), glam::Mat4::from_translation(Vec3::new(0.5, 0.6, 0.8)).to_cols_array()].concat();+ w.set_instances(17, 2, Some(copies), None, Some(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "added in place ({:?})", live.fallback);+ w.set_custom(17, [9.0; 4]).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "its node's data: in place");+ let fresh = open(&w).unwrap();+ let entries = |c: &LiveCore| {+ let (place, st) = (*c.sc.tables.retained.instanced(17).expect("placed as instances"), c.sc.tables.stride);+ (0..place.capacity as usize).map(|i| c.sc.tables.objects[(place.object as usize + i) * st + 2]).collect::<Vec<_>>()+ };+ assert_eq!(entries(&live), entries(&fresh), "each copy's data, in place against a build's");+ assert_eq!(entries(&fresh), [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]);+}diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex da7f88c..8d2464f 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -18,10 +18,13 @@ pub(super) struct LoadedScene {/// The instances' kernel records as uploaded (movable ones are rewritten when they move), then the procedural/// objects' (from `proc_first`).pub(super) gpu_instances: Vec<scene::GpuInstance>,- /// Procedural geometry (moves, picking), by node in `proc_of`; its records start at `proc_first`.+ /// Procedural geometry (moves, picking): the record `proc_first` + j is `procs[j]`'s, as record i is+ /// `instances[i]`'s. Both hold what edits place too, at its record (hidden fillers at the records between).pub(super) procs: Vec<scene::ProcObject>,- pub(super) proc_of: std::collections::HashMap<u32, usize>,pub(super) proc_first: usize,+ /// Some object's move is an instance's transform (`Retained::moves_instances`: kept where the proxies change,+ /// here and in a geometry edit): the frame's kernel then writes motion vectors.+ pub(super) moving_instances: bool,/// The scene has instanced meshes or procedural geometry (the raster experiment draws only flattened triangles:/// primary visibility is traced).pub(super) instanced: bool,@@ -241,7 +244,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet proc_first = gpu_instances.len();gpu_instances.extend_from_slice(&sc.proc_records);let procs = std::mem::take(&mut sc.procs);- let proc_of = procs.iter().enumerate().filter(|(_, p)| p.sub.is_none()).map(|(j, p)| (p.node, j)).collect();+ // (A proxy's index in `procs` is the build's: nothing between the build and here may take one out.)+ assert!(tables.retained.proxies.iter().all(|(id, p)| !matches!(p.draw, scene::Draw::Procedural(j) if procs.get(j as usize).map(|q| q.node) != Some(*id))), "a procedural object's proxy names another's place");let triangles = sc.stats.get("triangles").map_or(tris.len(), |t| *t as usize);let first = prep.groups[..4].iter().sum::<usize>();// The kernel's first dynamic triangle (motion vectors, prev_verts) is group 4's first.@@ -260,15 +264,17 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pfor i in &instances {*users.entry(i.mesh).or_default() += 1;}- let mesh_of = tables.retained.own_instance.iter().filter_map(|(&id, &k)| instances.get(k as usize).map(|i| (id, i.mesh))).collect();- let managed = tables.retained.own_mesh.values().chain(tables.retained.emitter_mesh.values()).copied().collect();+ let emitter_meshes = tables.retained.proxies.values().filter_map(|p| match &p.draw {+ scene::Draw::Instance(scene::InstanceRef { mesh: scene::MeshKind::Emitter(k), .. }) => Some(*k),+ _ => None,+ });+ let managed = tables.retained.own_mesh.values().copied().chain(emitter_meshes).collect();let edit = EditState {tris: Holes::new(room_base.0, room_base.0 + room.tris),records: Holes::new(room_base.1, room_base.1 + room.records),objects: Holes::new(room_base.2, room_base.2 + room.objects),word: room_base.3,word_cap: room_base.3 + room.proc_words,- mesh_of,users,managed,dead_meshes: vec![],@@ -278,10 +284,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pbase: room_base,pool_first: prep.groups.iter().sum(),blobs,- placed: Default::default(),- instanced: Default::default(),- inst_at_load: instances.len(),- added: Default::default(),};- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_of, proc_first, instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex bb769ae..d4d7344 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -941,12 +941,7 @@ impl LiveCore {let (mut t, i) = closest(&self.sc.tris, o, d);let mut node = self.sc.tri_nodes.iter().find(|(_, a, b)| (*a as usize..*b as usize).contains(&i)).map(|n| n.0.as_str());let mut sub = self.sc.tri_instances.iter().find(|(a, b, _)| (*a as usize..*b as usize).contains(&i)).map(|r| r.2);- let added = |want_mesh: bool| self.sc.edit.added.values().filter_map(move |p| match p {- Picked::Mesh(i) if want_mesh => Some(Ok(i)),- Picked::Proc(q) if !want_mesh => Some(Err(q)),- _ => None,- });- for inst in self.sc.instances.iter().filter(|i| !i.hidden).chain(added(true).filter_map(|x| x.ok())) {+ for inst in self.sc.instances.iter().filter(|i| !i.hidden) {let m = self.sc.meshes[inst.mesh as usize];let inv = inst.world.inverse();let (lo, ld) = (inv.transform_point3a(o), inv.transform_vector3a(d));@@ -964,7 +959,7 @@ impl LiveCore {}}// Procedural geometry: its boxes (the geometry function runs on the GPU only).- for p in self.sc.procs.iter().filter(|p| !p.hidden).chain(added(false).filter_map(|x| x.err())) {+ for p in self.sc.procs.iter().filter(|p| !p.hidden) {let inv = p.world.inverse();let (lo, ld) = (inv.transform_point3a(o), inv.transform_vector3a(d));let slab = |a: glam::Vec3A, b: glam::Vec3A| {@@ -997,16 +992,6 @@ impl LiveCore {let m = self.sc.meshes[inst.mesh as usize];out.extend(self.sc.pool_tris[m.first as usize..(m.first + m.count) as usize].iter().map(|t| inst.tri(t)));}- // Objects added in place (Bugbot on #131: `pick` saw them, this did not).- for p in self.sc.edit.added.values() {- if let Picked::Mesh(inst) = p {- if inst.name != id {- continue;- }- let m = self.sc.meshes[inst.mesh as usize];- out.extend(self.sc.pool_tris[m.first as usize..(m.first + m.count) as usize].iter().map(|t| inst.tri(t)));- }- }out}@@ -1156,12 +1141,15 @@ mod instanced_tests {w.set_object(11, "b".into(), None, mesh(3, 5), true, false).unwrap();w.set_driven(11).unwrap();w.set_transform(11, Vec3::new(0.0, 0.0, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ assert!(!core.sc.moving_instances, "nothing moves as an instance yet");assert!(!core.commit(&mut w).unwrap(), "added in place, its material too");assert_eq!(core.sc.tables.materials.len(), materials + 1);+ assert!(core.sc.moving_instances, "a driven mesh: the frames write motion vectors from here");assert_eq!(picked(&core, 0.5).as_deref(), Some("b"));// Its body moves it 3 m to the side (u 0.95 of the image, 4 m from the camera): no rebuild, its record moved// with the rows it had the frame before.- let record = core.sc.edit.placed[&11].1;+ let record = core.sc.tables.retained.instance(11).unwrap().instance as usize;+ assert!(core.sc.edit.in_room(record), "placed by an edit: a record of the room");assert!(w.place_driven(11, Vec3::new(3.0, 0.0, 1.0), glam::Quat::IDENTITY));assert!(!core.commit(&mut w).unwrap(), "moved as an instance");assert_eq!(core.fallbacks, 0);@@ -1170,7 +1158,7 @@ mod instanced_tests {assert_eq!((r.m[0][3], r.p[0][3]), (3.0, 0.0), "moved: last frame's rows kept");// A rebuild places it as an instance too, and it moves on in place.core.rebuild(&w).unwrap();- assert!(core.sc.tables.retained.instance_of.contains_key(&11) && core.sc.edit.placed.is_empty());+ assert!(core.sc.tables.retained.instance(11).is_some_and(|i| i.moves && !core.sc.edit.in_room(i.instance as usize)), "placed by the build");assert_eq!((picked(&core, 0.5).as_deref(), picked(&core, 0.95).as_deref()), (Some("a"), Some("b")));assert!(w.place_driven(11, Vec3::new(0.0, 0.0, 1.0), glam::Quat::IDENTITY));assert!(!core.commit(&mut w).unwrap(), "moved as an instance");@@ -1179,6 +1167,7 @@ mod instanced_tests {w.remove(11);assert!(!core.commit(&mut w).unwrap(), "removed in place");assert_eq!(picked(&core, 0.5).as_deref(), Some("a"));+ assert!(!core.sc.moving_instances, "removed: nothing moves as an instance");}/// An instanced mesh's moved instances keep their previous-frame rows (motion vectors) through the commit that moves@@ -1202,7 +1191,7 @@ mod instanced_tests {w.set_settings(crate::world::Settings { camera: Some(4), ..Default::default() });let mut core = LiveCore::new(g, &w, Path::new("."), &crate::default_presets_dir(), 64, 36).unwrap();w.take_changes();- let first = core.sc.tables.retained.instanced[&3].first as usize;+ let first = core.sc.tables.retained.instanced(3).unwrap().first as usize;w.set_instances(3, 2, Some(at(2.0)), None, None).unwrap();assert!(!core.commit(&mut w).unwrap(), "in place");let r = core.sc.gpu_instances[first + 1];@@ -1214,7 +1203,7 @@ mod instanced_tests {// Movable, moved and given new instances in one commit: updated once (twice would lose the motion).w.set_object(3, "copies".into(), None, Kind::Instanced { geometry: 2, procedural: false, materials: vec![1], capacity: 2 }, true, true).unwrap();assert!(core.commit(&mut w).unwrap(), "made movable: rebuilt");- let first = core.sc.tables.retained.instanced[&3].first as usize;+ let first = core.sc.tables.retained.instanced(3).unwrap().first as usize;w.set_transform(3, Vec3::new(0.0, 1.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();w.set_instances(3, 2, Some(at(3.0)), None, None).unwrap();let c = w.changes.clone();diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 270d16d..573e9ff 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -566,45 +566,145 @@ pub struct Retained {pub textures: HashMap<(u32, bool), i32>,/// Material function name -> index (GpuMaterial.tex1[3] - 1).pub shaders: HashMap<String, i32>,- /// Object -> object-table index (objects that draw triangles: meshes, models, rect-light cards).- pub objects: HashMap<u32, u32>,+ /// Object -> where what it draws landed (`Proxy`): meshes, models, rect-light cards, instanced objects.+ pub proxies: HashMap<u32, Proxy>,/// Object of each `lights` entry, same order (`prepare` sorts both).pub light_nodes: Vec<u32>,- /// Rect-light object with a visible card -> its card material.- pub cards: HashMap<u32, u32>,/// Atmosphere sun: its colour comes from the sky bake.pub sun: Option<u32>,- /// Posed models and movable objects (dynamic triangles) -> what re-transforming them in place needs.- pub dynamic: HashMap<u32, DynamicModel>,- /// Movable models placed as instances (hardware RT) -> their instance: a move updates its transform, not triangles.- pub instance_of: HashMap<u32, u32>,- /// Posed rigid models split by node (`RigidModel`): a new pose moves their nodes' instances.- pub rigid: HashMap<u32, RigidModel>,- /// Posed models sharing a pose (`PoseGroup`), and each member's group (members are in `instance_of` too).+ /// Posed models sharing a pose (`PoseGroup`: its members' proxies name it, `MeshKind::Pose`).pub pose_groups: Vec<PoseGroup>,- pub pose_member: HashMap<u32, u32>,- /// `own_blas` meshes placed as instances (hardware RT): object -> its instance; (geometry, GPU material) -> the- /// shared mesh (objects with the same geometry and material share its BLAS). live/edits.rs `edit_geometry` keeps both.- pub own_instance: HashMap<u32, u32>,+ /// `own_blas` meshes: (geometry, GPU material) -> the shared mesh (objects with the same geometry and material+ /// share its BLAS). live/edits.rs `edit_geometry` keeps it.pub own_mesh: HashMap<(u32, u32), u32>,- /// Emitting `own_blas` meshes (`InstMesh::emits`): object -> its mesh (its own, in world space).- pub emitter_mesh: HashMap<u32, u32>,- /// Instanced objects (`Kind::Instanced`) placed as instances -> where (live/edits.rs `update_instanced`).- pub instanced: HashMap<u32, InstancedPlace>,/// Static models' instanced meshes by (uri, nodes), those with nothing flattened per placement: a model added in/// place is another instance of one (live/edits.rs `edit_geometry`).pub model_mesh: HashMap<(String, Option<Vec<String>>), u32>,}-/// Where an instanced object's instances are: `capacity` of them from `first` in `instances` (triangles) or `procs`-/// (procedural), with object-table entries from `object`, one each; the first `drawn` were last written with their-/// matrices (the rest are hidden, and an update leaves them be).+/// Where what one object of the world draws landed in the GPU's tables: its entry in the objects table and how its+/// geometry is held. Edits in place go through it (live/edits.rs `LiveCore::commit`).+#[derive(Clone, Default)]+pub struct Proxy {+ /// Object-table index (pivot, bounds, power, customData). None: an instanced object (an entry a copy: from+ /// `InstancedPlace::object` for instances; a flattened one's are the build's alone).+ pub object: Option<u32>,+ /// A rect light's visible card: its material.+ pub card: Option<u32>,+ pub draw: Draw,+}++/// How a drawn object's geometry is held.+#[derive(Clone, Default)]+pub enum Draw {+ /// As the build placed it, with nothing kept to change it by: triangles flattened into the static groups, a+ /// static model's instance. An edit that would change it rebuilds.+ #[default]+ Fixed,+ /// World-space triangles in the dynamic groups, re-transformed (a movable object) or re-skinned (a posed model)+ /// on the CPU.+ Dynamic(DynamicModel),+ /// An instance of a model-space mesh (hardware RT, or software traversal's units).+ Instance(InstanceRef),+ /// Procedural geometry: its index in `procs` (its record less the first procedural record).+ Procedural(u32),+ /// A posed rigid model split by node: a new pose moves its nodes' instances.+ Rigid(RigidModel),+ /// An instanced object's copies (live/edits.rs `update_instanced`).+ Instanced(InstancedPlace),+}++/// One instance of a mesh: its index in `instances`, which is its record (the build's, or one of the edit room's).+#[derive(Clone, Copy, Debug)]+pub struct InstanceRef {+ pub instance: u32,+ pub mesh: MeshKind,+ /// A move is its transform's, not its triangles' (a mesh a body drives, a movable model the build placed).+ pub moves: bool,+}++/// What mesh an instance is of.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum MeshKind {+ /// A model's.+ Model,+ /// A shared pose's (`Retained::pose_groups`): the group's mesh is re-skinned, its members move as instances.+ Pose(u32),+ /// An `own_blas` mesh, shared by the objects of its geometry and material (`Retained::own_mesh`).+ Own,+ /// An emitting `own_blas` mesh (`InstMesh::emits`): this mesh, its own, its triangles in world space.+ Emitter(u32),+}++impl MeshKind {+ /// An `own_blas` mesh, an emitter's too: what a geometry edit makes and places again (a model's is the build's).+ pub fn own(self) -> bool {+ matches!(self, MeshKind::Own | MeshKind::Emitter(_))+ }+}++impl Retained {+ /// The object's proxy, made if it has none yet (the build, an edit that places it).+ pub fn proxy(&mut self, id: u32) -> &mut Proxy {+ self.proxies.entry(id).or_default()+ }++ /// Its object-table index.+ pub fn object(&self, id: u32) -> Option<u32> {+ self.proxies.get(&id)?.object+ }++ /// Its instance, if it is one of a mesh.+ pub fn instance(&self, id: u32) -> Option<&InstanceRef> {+ match &self.proxies.get(&id)?.draw {+ Draw::Instance(p) => Some(p),+ _ => None,+ }+ }++ pub fn instanced(&self, id: u32) -> Option<&InstancedPlace> {+ match &self.proxies.get(&id)?.draw {+ Draw::Instanced(p) => Some(p),+ _ => None,+ }+ }++ pub fn rigid(&self, id: u32) -> Option<&RigidModel> {+ match &self.proxies.get(&id)?.draw {+ Draw::Rigid(r) => Some(r),+ _ => None,+ }+ }++ /// Whether any object's move is an instance's transform (a movable or driven instance, a rigid model's nodes).+ pub fn moves_instances(&self) -> bool {+ self.proxies.values().any(|p| matches!(&p.draw, Draw::Rigid(_)) || matches!(&p.draw, Draw::Instance(i) if i.moves))+ }++ /// Whether any object is an `own_blas` mesh's instance (what geometry edits place again).+ pub fn has_own_instances(&self) -> bool {+ self.proxies.values().any(|p| matches!(&p.draw, Draw::Instance(i) if i.mesh.own()))+ }++ /// The triangles re-transformed on the CPU: the dynamic objects' and the rigid models' flattened ones.+ pub fn dynamics_mut(&mut self) -> impl Iterator<Item = &mut DynamicModel> {+ self.proxies.values_mut().filter_map(|p| match &mut p.draw {+ Draw::Dynamic(d) => Some(d),+ Draw::Rigid(r) => Some(&mut r.rest),+ _ => None,+ })+ }+}++/// Where an instanced object's instances are: `capacity` of them from `first` in `instances` (instances of `mesh`) or+/// in `procs` (procedural copies: no mesh), with object-table entries from `object`, one each; the first `drawn`+/// were last written with their matrices (the rest are hidden, and an update leaves them be).#[derive(Clone, Copy, Debug)]pub struct InstancedPlace {pub first: u32,pub capacity: u32,pub object: u32,- pub procedural: bool,+ pub mesh: Option<u32>,pub drawn: u32,}@@ -1205,7 +1305,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sematch &n.kind {Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if shown && instancing && mesh_mats.len() <= 1 && m.determinant() > 0.0 && (n.driven || (*own_blas && !w.movable(*id))) => {// Its own BLAS (scene code's `dynamicGeometry`, or a mesh a rigid body drives: its moves are the- // instance's transform, `retained.instance_of`): placed like a model instance, its geometry's triangles+ // instance's transform, `InstanceRef::moves`): placed like a model instance, its geometry's triangles// in model space in the pool, shared by the objects of the same geometry and material. Glass, emissive// and function materials are flattened (as a model's would be), so they are never instanced.let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;@@ -1234,11 +1334,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet size = hi - lo;let oi = (objects.len() / stride) as u32;objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);- retained.objects.insert(*id, oi);- retained.own_instance.insert(*id, instances.len() as u32);- if n.driven {- retained.instance_of.insert(*id, instances.len() as u32);- }+ *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven }) };instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });}continue;@@ -1260,9 +1356,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sepool_attrs.extend(a);let mesh = meshes.len() as u32 - 1;objects.extend_from_slice(&object_row(m.transform_point3(Vec3::ZERO), n.power, im.hi - im.lo, n.custom, [1.0; 3])[..stride]);- retained.objects.insert(*id, oi);- retained.own_instance.insert(*id, instances.len() as u32);- retained.emitter_mesh.insert(*id, mesh);+ *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Emitter(mesh), moves: false }) };instances.push(Instance { mesh, world: Mat4::IDENTITY, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });}continue;@@ -1272,7 +1366,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se// re-transformed in place as any movable mesh's.)append_arrays(g, m, mat, if n.driven { flags | TRI_DYNAMIC } else { flags }, None, &mut tris, &mut tri_flags, &mut attrs);if n.driven {- retained.dynamic.insert(*id, DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });+ retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });}}Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {@@ -1287,7 +1381,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seif *procedural {let object = (objects.len() / stride) as u32;if let Some(p) = proc_object(w, *id, m, object, &retained.materials, assets)? {- retained.instanced.insert(*id, InstancedPlace { first: procs.len() as u32, capacity: *capacity, object, procedural: true, drawn: t.count });+ retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: procs.len() as u32, capacity: *capacity, object, mesh: None, drawn: t.count });for (i, &(wm, hidden)) in placed.iter().enumerate() {let q = ProcObject { world: wm, object: object + i as u32, sub: Some(i as u32), hidden, ..p.clone() };objects.extend_from_slice(&q.entry(n.power, t.custom(i, n.custom), t.color(i))[..stride]);@@ -1320,7 +1414,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se};if let Some(mesh) = mesh {let object = (objects.len() / stride) as u32;- retained.instanced.insert(*id, InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, procedural: false, drawn: t.count });+ retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, mesh: Some(mesh), drawn: t.count });for (i, &(wm, hidden)) in placed.iter().enumerate() {let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);objects.extend_from_slice(&entry(i, wm, Vec3::from(hi - lo))[..stride]);@@ -1329,6 +1423,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se}continue;}+ // Flattened: nothing kept to change it by (`Draw::Fixed`; an entry a copy, as the instances have).+ retained.proxy(*id);for (i, &(wm, hidden)) in placed.iter().enumerate() {if hidden {continue;@@ -1364,7 +1460,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seput_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, m.determinant() < 0.0, vc_tri.as_deref())));append_arrays(g, m, mat, if movable { flags | TRI_DYNAMIC } else { flags }, per_tri.as_deref(), &mut tris, &mut tri_flags, &mut attrs);if movable {- retained.dynamic.insert(*id, DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });+ retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });}}Kind::Model { uri, nodes, animation, functions } if shown => {@@ -1497,7 +1593,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sefor a in &mut attrs[first as usize..] {a.x[1] = f32::from_bits(oi);}- retained.objects.insert(*id, oi);rigid.rest.first = rest_first;rigid.rest.object = oi;if tris.len() as u32 > first {@@ -1506,7 +1601,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seif 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.rigid.insert(*id, rigid);+ *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Rigid(rigid) };continue;}// A model in a shared pose: an instance of the pose's mesh (`PoseGroup`), made by the group's first.@@ -1555,11 +1650,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet size = hi - lo;let oi = (objects.len() / stride) as u32;objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);- retained.objects.insert(*id, oi);let i = instances.len() as u32;instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });- retained.instance_of.insert(*id, i);- retained.pose_member.insert(*id, g);+ *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Pose(g), moves: true }) };retained.pose_groups[g as usize].members.push((*id, i));continue;}@@ -1635,7 +1728,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet size = hi - lo;let oi = (objects.len() / stride) as u32;objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);- retained.objects.insert(*id, oi);+ retained.proxy(*id).object = Some(oi);let inst = Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false };// Its glass / emissive triangles as ordinary world-space ones (same object).for k in im.rest_first..im.rest_first + im.rest_count {@@ -1646,8 +1739,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seif tris.len() as u32 > first {tri_nodes.push((n.name.clone(), first, tris.len() as u32));}+ // (A model that does not move keeps no instance of its own here: `Draw::Fixed`.)if movable {- retained.instance_of.insert(*id, instances.len() as u32);+ retained.proxy(*id).draw = Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Model, moves: true });}instances.push(inst);continue;@@ -1660,7 +1754,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&semats.push(mat);}if dynamic {- retained.dynamic.insert(*id, DynamicModel { first, mats, ..Default::default() });+ retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats, ..Default::default() });}}Kind::Light(l) => match (l, gpu_light_shown(l, m, n.power, shown)) {@@ -1672,13 +1766,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se// Visible one-sided emissive quad (importance sampled as an emitter).let mat = materials.len() as u32;materials.push(card_material(*color, *intensity));- retained.cards.insert(*id, mat);+ retained.proxy(*id).card = Some(mat);let movable = w.movable(*id);for (v, dir) in card_tris(m, *width, *height) {push_tri(&mut tris, &mut tri_flags, &mut attrs, v, [dir; 3], [Vec2::ZERO; 3], None, mat, if movable { TRI_NO_SHADOW | TRI_DYNAMIC } else { TRI_NO_SHADOW });}if movable {- retained.dynamic.insert(*id, DynamicModel { first, mats: vec![mat; 2], ..Default::default() });+ retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: vec![mat; 2], ..Default::default() });}}_ => {}@@ -1735,7 +1829,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seKind::Procedural { .. } if shown => {if let Some(p) = proc_object(w, *id, m, (objects.len() / stride) as u32, &retained.materials, assets)? {objects.extend_from_slice(&p.object_entry(n)[..stride]);- retained.objects.insert(*id, p.object);+ *retained.proxy(*id) = Proxy { object: Some(p.object), card: None, draw: Draw::Procedural(procs.len() as u32) };procs.push(p);}}@@ -1823,8 +1917,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sefor a in &mut attrs[first as usize..] {a.x[1] = f32::from_bits(oi);}- retained.objects.insert(*id, oi);- if let Some(d) = retained.dynamic.get_mut(id) {+ let proxy = retained.proxy(*id);+ proxy.object = Some(oi);+ if let Draw::Dynamic(d) = &mut proxy.draw {d.object = oi;}tri_nodes.push((n.name.clone(), first, tris.len() as u32));@@ -1873,7 +1968,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se*f |= TRI_NO_SHADOW;}}- for d in retained.dynamic.values_mut().chain(retained.rigid.values_mut().map(|r| &mut r.rest)) {+ for d in retained.dynamics_mut() {d.flags = tri_flags[d.first as usize..d.first as usize + d.mats.len()].to_vec();}Ok(Scene {@@ -2372,7 +2467,7 @@ mod instance_tests {assert_eq!((sc.meshes.len(), sc.instances.len(), sc.tris.len(), sc.objects.len() / 4), (1, 4, 0, 4), "tinted: 4 vec4s an object");assert_eq!(sc.instances.iter().map(|i| (i.sub, i.hidden)).collect::<Vec<_>>(), vec![(Some(0), false), (Some(1), false), (Some(2), true), (Some(3), true)]);assert_eq!((sc.objects[4][0], sc.objects[4 + 3]), (1.0, [0.5, 0.5, 0.5, 0.0]));- assert!(sc.tinted && sc.retained.instanced[&2].capacity == 4);+ assert!(sc.tinted && sc.retained.instanced(2).unwrap().capacity == 4);let mut m = m.map(|m| m.to_cols_array()).concat();m[0] = -1.0;w.set_instances(2, 3, Some(m), None, None).unwrap();diff --git a/renderer/src/tables.rs b/renderer/src/tables.rsindex 3956ba4..523ef60 100644--- a/renderer/src/tables.rs+++ b/renderer/src/tables.rs@@ -104,7 +104,7 @@ impl Tables {}for id in &c.powers {let o = w.objects.get(id).ok_or_else(|| anyhow!("unknown object {id}"))?;- if let Some(&oi) = self.retained.objects.get(id) {+ if let Some(oi) = self.retained.object(*id) {let row = oi as usize * self.stride;if self.defer_powers {self.deferred.retain(|p| p.0 != row);@@ -120,14 +120,14 @@ impl Tables {}for id in &c.customs {let o = w.objects.get(id).ok_or_else(|| anyhow!("unknown object {id}"))?;- if let Some(&oi) = self.retained.objects.get(id) {+ if let Some(oi) = self.retained.object(*id) {self.objects[oi as usize * self.stride + 2] = o.custom;d.objects = true;}}for id in &c.lights {let o = w.objects.get(id).ok_or_else(|| anyhow!("unknown object {id}"))?;- if let (Some(&mat), Kind::Light(desc::Light::Rect { color, intensity, visible: true, .. })) = (self.retained.cards.get(id), &o.kind) {+ if let (Some(mat), Kind::Light(desc::Light::Rect { color, intensity, visible: true, .. })) = (self.retained.proxies.get(id).and_then(|p| p.card), &o.kind) {let m = scene::card_material(*color, *intensity);if !self.can_emit(mat, &m) {return Ok(None);