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.

A posed skinned model is added and removed in place (#183)

Yujia23c11b947dbe
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 83d8b27..65c4462 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2776,6 +2776,41 @@ in-place tests' world, rows given back; two models in a shared pose posed again
(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting
section that is not its first, the model a unit under software traversal).
+**A posed skinned model is added and removed in place (2026-11-21).** A character that comes or goes while the game
+runs rebuilt the scene. Now one of a model the scene has is added as the build makes one: a mesh of its own in the
+room for edits, its triangles skinned on the CPU once for the pose it comes in, a job of the skinning pass for its
+next poses (the pass's table grows), skinned from the model's one copy of its corners. Removed, its instance is out
+(the build's or an edit's); one an edit placed gives back its triangles, its record and rows, its previous vertices
+and its job's slot, and the next one placed takes them.
+A mesh that deforms has its previous frame's vertices where its instance says (`scene::Instance::prev`, in its
+record): the kernel found them by the triangle's place among the dynamic triangles, which a mesh in the room does
+not have. Their buffer grows as the triangles' does. The kernel's read is a feature of its own (`F_DEFORM`: a scene
+with a mesh that deforms): in every kernel, a scene without one paid 0.6 % of its GPU frame for it (a flight over a
+city, five pairs of five).
+A fault found on the way: what a batch changed of an object (a pose, a move, its visibility) stayed when the same
+batch removed it, and the renderer rebuilt for an object it could not find. It goes with the object now.
+Still a rebuild: a skinned model the scene has not (its materials and textures load with one), one whose pose
+mirrors other primitives than the scene's, one added hidden and shown later, one added in a scene with particle
+systems (the rooms for edits do not grow there, for any edit: the particle passes hold the scene's buffers), and
+any under software traversal.
+Measured, hardware traversal, a game that spawns a character every half second and takes the oldest away (twelve
+at most): each spawn and each despawn rebuilt the scene, 31 times in 16 s, 46 ms each (the longest frame 79 ms);
+now none does, a frame that spawns or despawns commits in 3.5 ms (4.9 at most) and the longest frame is 21 ms. The
+frame between is the same: eight spawned and then none, at 1280 x 720, the GPU's frame is 10.6 ms either way (the
+trace 3.5, the BLAS builds 0.58).
+Tests: one added against the CPU skin (triangles, attributes, BLAS input, previous vertices) and a build's picture;
+its motion vectors at a new pose against a built one's, none longer than the furthest a corner went; moved, hidden,
+shown; 40 added at once (every room grows), posed on, half of them hidden and shown; 24 more in a commit that
+grows the pass's buffers alone; previous vertices kept mesh by mesh (a model removed before a frame is drawn, two
+whose triangles are neighbours and whose previous vertices are not, one posed twice between frames); one removed
+and the next added in what it had; a built one removed (shown, hidden, posed in the same batch); the three that
+rebuild. The pictures are compared with the build's frames counted from the live view's (a frame's samples go by
+its number: at another count a picture of many thin models is two thirds of a step from itself).
+36 mutations of the new logic: 33 fail a test natively, two under software traversal, and one is equivalent (the
+CPU's copy of an added model's triangles: a fallback no path reads while the model loads). Eight did not at first:
+the scenes had no moving triangles before the meshes, motion vectors were compared with a build's alone (wrong
+alike in both), other rooms grew in every commit that grew the pass's, and no frame was skipped between two edits.
+
**A posed skinned model is a mesh of its own (2026-11-21).** Models in the same pose (the same clip and time) shared
one mesh, found by the build; one of them taking another pose had to leave it, and that rebuilt the scene (and a
rebuild grouped whichever models then happened to be in one pose). A model alone in its pose was no mesh at all:
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index a4ce361..26c8035 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -90,6 +90,7 @@ const F_BACKGROUND: u32 = 2097152u; // scene.background (`sky_mis`)
const F_VCOLOR: u32 = 4194304u; // vertex colours (`vcolor`)
const F_GRID: u32 = 33554432u; // density grids (`vgrid`)
const F_IFUNC: u32 = 268435456u; // a material function on an instanced mesh: `mat_in_at` places the triangle by its instance
+const F_DEFORM: u32 = 1073741824u; // a mesh that deforms among the instances: its previous vertices by its record (the first hit's motion)
const F_IGLASS: u32 = 536870912u; // glass among an instance's other sections: a shadow ray steps through it by its row (trace_hw.wgsl), a unit's walk skips it
const F_LISTS: u32 = 134217728u; // light tiles (`lt_list_start`): a scene whose shadow-casting local lights are resampled
fn has(f: u32) -> bool { return (FEAT & f) != 0u; }
@@ -3804,7 +3805,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let ti = hit.tri;
// The first dynamic triangle is the first of traversal group 4 (a u32: an index carried as f32 bits would be a
// denormal below 2^23, which a driver may flush to zero).
- // Dynamic triangles (and deforming instanced meshes, in model space) keep their previous vertices.
+ // Dynamic triangles keep their previous vertices, as they lie from the first dynamic one (`kp`); a deforming
+ // instanced mesh keeps its own in model space, where its instance's record says.
let deforms = LIVE && P.motion.x > 0.5 && !is_proc(hit) && ti >= P.group_first[1].x && (bitcast<u32>(tri_verts[ti * 3u].w) & TRI_DYNAMIC) != 0u;
let kp = (ti - P.group_first[1].x) * 3u;
if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {
@@ -3820,7 +3822,14 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let r = instance_at(hit.inst);
if (deforms || any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
var lp = vec4<f32>(tri_verts[ti * 3u].xyz + tri_verts[ti * 3u + 1u].xyz * hit.u + tri_verts[ti * 3u + 2u].xyz * hit.v, 1.0);
- if (deforms) { lp = vec4<f32>(prev_verts[kp].xyz + prev_verts[kp + 1u].xyz * hit.u + prev_verts[kp + 2u].xyz * hit.v, 1.0); }
+ // (A deforming mesh's previous vertices are where its record says, n2.w, in its triangles' order:
+ // a mesh an edit placed has them elsewhere than its triangles lie. F_DEFORM: a scene with such a
+ // mesh; elsewhere nothing here deforms, and the read is as the dynamic triangles'.)
+ if (deforms) {
+ var kq = kp;
+ if (has(F_DEFORM)) { kq = (bitcast<u32>(r.n2.w) + ti - r.info.x) * 3u; }
+ lp = vec4<f32>(prev_verts[kq].xyz + prev_verts[kq + 1u].xyz * hit.u + prev_verts[kq + 2u].xyz * hit.v, 1.0);
+ }
mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - s.p, 1.0);
}
} else if (deforms) {
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 28a474d..c95ae05 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -762,6 +762,58 @@ pub struct SkinGpu {
palette: wgpu::Buffer,
/// Per job, and how many matrices its palette is.
jobs: Vec<(SkinJob, u32)>,
+ /// Each source's first triangle among the corners (`Scene::skin_sources`), and the palette's matrices in use.
+ source_first: Vec<u32>,
+ palette_end: u32,
+}
+
+impl SkinGpu {
+ /// (Tests: the bytes of the jobs' table, the palettes' and the blocks' buffers.)
+ #[cfg(test)]
+ pub fn rooms(&self) -> [u64; 3] {
+ [self.table.size(), self.palette.size(), self.blocks.size()]
+ }
+
+ /// The job of a mesh an edit placed, at `slot` (a new one, or one whose mesh is gone): its triangles from `first`
+ /// in the scene's, skinned from `source`'s corners by a palette of `palette_len` matrices. The pass's buffers
+ /// grow with it (the table written again whole; the palette's and the blocks' contents are a dispatch's, and
+ /// need no copy). True where one was made again: the pass's bind group is then to be (`Gpu::rebind_scene`).
+ pub fn set_job(&mut self, d: &wgpu::Device, q: &wgpu::Queue, slot: usize, first: u32, count: u32, source: u32, palette_len: u32) -> bool {
+ let room = |label: &str, size: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut grew = false;
+ // Its palette: the slot's own where that is as long, else new room at the end.
+ let palette = match self.jobs.get(slot) {
+ Some((j, len)) if *len == palette_len => j.palette,
+ _ => {
+ self.palette_end += palette_len;
+ self.palette_end - palette_len
+ }
+ };
+ let job = SkinJob { first, count, source: self.source_first[source as usize], palette };
+ if slot < self.jobs.len() {
+ self.jobs[slot] = (job, palette_len);
+ } else {
+ self.jobs.push((job, palette_len));
+ }
+ if self.jobs.len() as u64 * 16 > self.table.size() {
+ self.table = room("skin jobs", self.jobs.len() as u64 * 32);
+ let table: Vec<SkinJob> = self.jobs.iter().map(|j| j.0).collect();
+ q.write_buffer(&self.table, 0, bytemuck::cast_slice(&table));
+ grew = true;
+ } else {
+ q.write_buffer(&self.table, slot as u64 * 16, bytemuck::bytes_of(&job));
+ }
+ if self.palette_end as u64 * 48 > self.palette.size() {
+ self.palette = room("skin palette", self.palette_end as u64 * 96);
+ grew = true;
+ }
+ let blocks: u64 = self.jobs.iter().map(|j| j.0.count.div_ceil(SKIN_BLOCK) as u64).sum();
+ if blocks * 8 > self.blocks.size() {
+ self.blocks = room("skin blocks", blocks * 16);
+ grew = true;
+ }
+ grew
+ }
}
fn skin_bind_group(d: &wgpu::Device, pipeline: &wgpu::ComputePipeline, own: [&wgpu::Buffer; 5], verts: &wgpu::Buffer, attrs: &wgpu::Buffer, blas_verts: &wgpu::Buffer) -> wgpu::BindGroup {
@@ -1722,6 +1774,10 @@ pub const F_IFUNC: u32 = 1 << 28;
/// software traversal skips such a triangle of a unit). Compiled out where no instance mixes the two: one that is all
/// glass is out of a shadow ray's way by its mask (`scene::rows_cast`).
pub const F_IGLASS: u32 = 1 << 29;
+/// A mesh that deforms among the instances (a posed skinned model's): the first hit's motion takes its previous
+/// frame's vertices from where its instance's record says. Compiled out where no mesh deforms: with the read in every
+/// kernel a scene without one paid for it (a flight over a city: frame GPU +0.6 %, five pairs of five).
+pub const F_DEFORM: u32 = 1 << 30;
/// Whether a scene with more such lights has the light tiles (`F_LISTS`): `THREERT_LIGHT_TILES=1|0`, else everywhere
/// but Android. On Adreno 740 they took OpenStrikeRT's Foundry from 31 to 48 ms a frame (249 x 140, one bounce):
/// there the lights are resampled as in a scene of fewer, unguided (docs/RUNTIME.md "Android").
@@ -1786,7 +1842,7 @@ pub fn environment_features(fog: Option<&crate::desc::Fog>, background: bool, ae
/// Kernel features of the scene's structure, which parameter edits do not change: F_INST and F_MASKED for the
/// instanced meshes (cutout triangles among them), F_MEDIA for participating media (F_HMEDIA for homogeneous ones),
/// F_PEMIT for opaque particles, F_PROC for procedural geometry, F_TINT for instance colours, F_IFUNC for a material
-/// function on an instanced mesh, F_IGLASS for glass on one.
+/// function on an instanced mesh, F_IGLASS for glass on one, F_DEFORM for a mesh that deforms.
pub fn instance_features(scene: &Scene) -> u32 {
// (F_GRID also for a volume function that calls `vgrid` on a node without a grid: it reads zeros.)
let grid = !scene.grids.is_empty() || (!scene.media.is_empty() && scene.volume_fns.iter().any(|(_, code, helpers)| code.contains("vgrid(") || helpers.contains("vgrid(")));
@@ -1803,7 +1859,8 @@ pub fn instance_features(scene: &Scene) -> u32 {
let ifunc = if scene.rows.iter().any(|r| function(crate::scene::row_material(r))) { F_IFUNC } else { 0 };
let iglass = if mixed_glass { F_IGLASS } else { 0 };
let masked = any_row(crate::scene::ROW_CUTOUT);
- media | particles | ifunc | iglass | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
+ let deform = if scene.meshes.iter().any(|m| m.deforms) { F_DEFORM } else { 0 };
+ media | particles | ifunc | iglass | deform | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
@@ -3429,7 +3486,7 @@ impl Gpu {
let params = room("skin params", 16, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST);
let (b_blocks, palette) = (room("skin blocks", blocks as u64 * 8, storage), room("skin palette", matrices as u64 * 48, storage));
let bg = skin_bind_group(d, &pipeline, [&params, &b_blocks, &b_table, &b_corners, &palette], verts, attrs, blas_verts);
- SkinGpu { pipeline, bg, params, blocks: b_blocks, table: b_table, corners: b_corners, palette, jobs }
+ SkinGpu { pipeline, bg, params, blocks: b_blocks, table: b_table, corners: b_corners, palette, jobs, source_first, palette_end: matrices }
}
/// Skins the meshes of `work` (a job and its pose's palette each) on the GPU: their triangles, shading attributes
@@ -3786,6 +3843,7 @@ mod tests {
("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),
("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),
("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),
+ ("F_DEFORM", F_DEFORM),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index eaa4079..1b48569 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -601,6 +601,13 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
tri_verts.push([e2.x, e2.y, e2.z, 0.0]);
attrs.push(*a);
}
+ // (A deforming mesh's previous vertices lie as its triangles do, counted from the first dynamic triangle: what
+ // gpu.rs `prev_verts` holds at the build. Its instance's record says where.)
+ let first_dynamic: usize = groups[..4].iter().sum();
+ for i in &mut sc.instances {
+ let m = &sc.meshes[i.mesh as usize];
+ i.prev = if m.deforms { (pool_first - first_dynamic) as u32 + m.first } else { 0 };
+ }
sc.gpu_instances = sc.instances.iter().map(|i| i.gpu(pool_first as u32 + sc.meshes[i.mesh as usize].first)).collect();
// A row's section starts here in the triangles' table (hardware traversal: a hit's geometry is its section, its
// primitive counts from there).
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 73c07cd..5ac1d26 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -115,6 +115,11 @@ 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>,
+ /// The previous frame's vertices (`prev_verts`, in triangles) of the deforming meshes edits place: the build's
+ /// before them, then room that grows. And the `scene::Skinned` slots (the skinning pass's jobs) of those an edit
+ /// took out again: the next one placed takes one.
+ pub(super) prev: Holes,
+ pub(super) free_skinned: Vec<u32>,
}
impl EditState {
@@ -218,6 +223,8 @@ pub(super) enum Placed {
/// A part: its node (`scene::STILL_NODES`: those its clip leaves alone), its instance and its rows. Their records
/// follow each other.
Parts(Vec<(usize, scene::Instance, Vec<scene::Row>)>),
+ /// A posed skinned model: the instance of its own mesh, its rows, and its slot among `Retained::skinned`.
+ Skinned(scene::Instance, Vec<scene::Row>, u32),
}
/// What `place_instance` writes to.
@@ -320,6 +327,21 @@ pub(super) fn mesh_places(im: &scene::InstMesh, sections: &[scene::Section], poo
out
}
+/// Spans (first triangle, first of the previous vertices, how many) in order, the same one once, neighbours in both
+/// as one: the copies `keep_prev_spans` makes.
+pub(super) fn merge_spans(mut spans: Vec<(usize, usize, usize)>) -> Vec<(usize, usize, usize)> {
+ spans.sort_unstable();
+ spans.dedup();
+ let mut out: Vec<(usize, usize, usize)> = vec![];
+ for s in spans {
+ match out.last_mut() {
+ Some(l) if l.0 + l.2 == s.0 && l.1 + l.2 == s.1 => l.2 += s.2,
+ _ => out.push(s),
+ }
+ }
+ out
+}
+
/// One object fewer draws instanced mesh `k`: a mesh edits manage that none draws any more is freed (its triangles a
/// hole the next new mesh can take, its slot reused, its BLAS dropped with it).
pub(super) fn drop_mesh_user(k: u32, edit: &mut EditState, tables: &mut tables::Tables, meshes: &[scene::InstMesh]) {
@@ -373,6 +395,20 @@ impl Grow<'_> {
true
}
+ /// The previous frame's vertices of deforming meshes.
+ pub(super) fn prev(&self, h: &mut Holes, extra: usize, prev: &mut wgpu::Buffer) -> bool {
+ if !self.ok {
+ return false;
+ }
+ let cap = Self::cap(h, extra);
+ if !self.fits(&[(cap * 48) as u64]) {
+ return false;
+ }
+ *prev = self.g.grown(prev, (cap * 48) as u64, "prev verts");
+ h.cap = cap;
+ true
+ }
+
/// A table's section to `bytes` (heap.rs `Heap::grow`), if the device binds the buffer that makes.
fn table(&self, heap: &mut Heap<Table>, t: Table, bytes: u64) -> bool {
if !self.fits(&[heap.size_with(t, bytes)]) {
@@ -1886,19 +1922,19 @@ impl LiveCore {
self.cpu_skin_ms += t_skin.elapsed().as_secs_f32() * 1000.0;
let t_up = Instant::now();
// Motion vectors: the GPU still holds the previous pose of these meshes (and of the last re-skin's, if others):
- // keep it in `prev_verts` before the pass writes the new one.
- let df = self.sc.dynamic.0;
- let (mut lo, mut hi) = (usize::MAX, 0usize);
- for (g, _) in &jobs {
- let sk = &self.sc.tables.retained.skinned[*g as usize];
- let k = self.sc.gpu_instances[sk.instance as usize].info[0] as usize - df;
- (lo, hi) = (lo.min(k), hi.max(k + sk.order.len()));
- }
- self.keep_prev(self.pose_span.map_or((lo, hi), |(a, b)| (a.min(lo), b.max(hi))));
+ // keep it in `prev_verts`, each mesh's where its instance says, before the pass writes the new one.
+ let posed: Vec<(usize, usize, usize)> = jobs
+ .iter()
+ .map(|(g, _)| {
+ let sk = &self.sc.tables.retained.skinned[*g as usize];
+ (self.sc.gpu_instances[sk.instance as usize].info[0] as usize, self.sc.instances[sk.instance as usize].prev as usize, sk.order.len())
+ })
+ .collect();
+ self.keep_prev_spans(&posed.iter().chain(&self.pose_spans).copied().collect::<Vec<_>>());
if !self.g.skin(&self.sc.up, &work) {
return Ok(false);
}
- self.pose_span = Some((lo, hi));
+ self.pose_spans = posed;
self.pose_reposed = true;
for (g, a) in jobs {
let sk = &mut self.sc.tables.retained.skinned[g as usize];
@@ -2006,6 +2042,20 @@ impl LiveCore {
self.g.queue.submit([e.finish()]);
}
+ /// Likewise for deforming meshes, each where it lies: (its first triangle in the scene's, the first of its
+ /// previous vertices, how many).
+ pub(super) fn keep_prev_spans(&self, spans: &[(usize, usize, usize)]) {
+ if spans.is_empty() {
+ return;
+ }
+ let up = &self.sc.up;
+ let mut e = self.g.device.create_command_encoder(&Default::default());
+ for (verts, prev, n) in merge_spans(spans.to_vec()) {
+ e.copy_buffer_to_buffer(&up.verts, (verts * 48) as u64, &up.prev_verts, (prev * 48) as u64, (n * 48) as u64);
+ }
+ self.g.queue.submit([e.finish()]);
+ }
+
/// Skins / transforms the objects into the CPU copy of the dynamic tail; the touched span (relative to the tail), or
/// None when one cannot be updated in place.
pub(super) fn reskin(&mut self, world: &World, ids: &std::collections::HashSet<u32>, models: &std::collections::HashMap<u32, scene::DynamicModel>) -> Result<Option<(usize, usize)>> {
@@ -2222,13 +2272,31 @@ impl LiveCore {
continue;
}
emitters_changed |= release(*id, tables, instances);
- // (A still model the build placed, whose instance is all of it, is taken out by it too.)
- let at = slot_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| whole(i, instances, meshes)).map(|i| (inst_base + i.instance as usize, i.instance as usize)));
+ // (A still model the build placed, whose instance is all of it, is taken out by it too; and a posed skinned
+ // model, an instance of its own mesh, where there is such an instance: software traversal has its triangles
+ // in the still tree. Its mesh's triangles and its skinning job stay until the next rebuild, as the build's do.)
+ let its_own = |i: &scene::InstanceRef| whole(i, instances, meshes) || (matches!(i.mesh, scene::MeshKind::Skinned(_)) && instances.get(i.instance as usize).is_some_and(|x| top.has_mesh(x.mesh)));
+ let at = slot_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| its_own(i)).map(|i| (inst_base + i.instance as usize, i.instance as usize)));
// Drawn, and not at a record an edit can clear (a model with triangles flattened beside its instance,
// anything the build 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 in parts, something it flattened) removed".into());
}
+ // (A skinned model an edit placed: with its mesh's triangles go the room of its previous vertices and its
+ // slot among the skinned, which the next one placed takes. The build's stay until the next rebuild.)
+ if let Some((g, rec)) = tables.retained.instance(*id).and_then(|i| match i.mesh {
+ scene::MeshKind::Skinned(g) if edit.in_room(i.instance as usize) => Some((g as usize, i.instance as usize)),
+ _ => None,
+ }) {
+ let mesh = tables.retained.skinned[g].mesh;
+ if let (Some(inst), Some(im)) = (instances.get(rec), meshes.get(mesh as usize)) {
+ edit.prev.give(inst.prev as usize, im.count as usize);
+ let first = edit.pool_first + im.first as usize;
+ self.pose_spans.retain(|s| s.0 != first);
+ }
+ tables.retained.skinned[g].mesh = u32::MAX;
+ edit.free_skinned.push(g as u32);
+ }
let proxy = tables.retained.proxies.remove(id);
if let Some((slot, record)) = at {
top.clear(slot);
@@ -2354,9 +2422,9 @@ impl LiveCore {
(at.map(|(_, r)| r), Placed::Proc(blas, p, gpu), entry)
}
Kind::Model { uri, nodes, animation, functions } => {
- // A model already in the scene: another instance of its mesh, or of each of its parts' meshes if it
- // is a posed rigid one (one not in the scene brings materials and textures, which load with a
- // rebuild).
+ // A model already in the scene: another instance of its mesh, of each of its parts' meshes if it is
+ // a posed rigid one, or of a mesh of its own if it is a posed skinned one (one not in the scene
+ // brings materials and textures, which load with a rebuild).
if !functions.is_empty() {
return Err("a model with material functions (its materials load with a rebuild)".into());
}
@@ -2366,7 +2434,126 @@ impl LiveCore {
// (Shadow rays pass the glass among a caster's other sections under a kernel feature: a scene where
// no instance of the model cast a shadow was built without it.)
let glass_caster = |its: &[scene::Row]| scene::rows_bits(its) & scene::INST_GLASS != 0 && scene::rows_cast(its, o.cast_shadow) && features & gpu::F_IGLASS == 0;
- if let Some(a) = animation {
+ let glb = scene::model_gltf(uri, assets).map_err(|e| e.to_string())?;
+ if let Some(a) = animation.as_ref().filter(|_| glb.animated() && !(nodes.is_none() && glb.rigid())) {
+ // A posed skinned model the scene has: a mesh of its own in the room, as the build makes one. Its
+ // triangles are skinned here once, for the pose it comes in; the pass skins it from its next
+ // pose on, from the corners the scene's others of the model are skinned from.
+ if top.sw() {
+ return Err("a skinned model (software traversal has its triangles in the still tree)".into());
+ }
+ if at.is_some() {
+ return Err("a skinned model placed again".into());
+ }
+ let t = *tables.retained.skinned_model.get(&(uri.clone(), nodes.clone())).ok_or("a skinned model not in the scene (its materials and textures load with a rebuild)")?;
+ let (order, source, palette_len, its_mesh, mirrors) = {
+ let s = &tables.retained.skinned[t as usize];
+ (s.order.clone(), s.source, s.palette_len, s.mesh, s.mirrors.clone())
+ };
+ if glb.mirrored(Some(a)).map_err(|e| e.to_string())? != mirrors {
+ return Err("a skinned model whose pose mirrors other primitives than the scene's (its triangles are a build's to order)".into());
+ }
+ let mine = tables.retained.mesh_rows.get(&its_mesh).ok_or("a model's mesh without its rows")?.clone();
+ if glass_caster(&mine) {
+ return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());
+ }
+ let posed = glb.triangles(glam::Mat4::IDENTITY, nodes.as_deref(), Some(a)).map_err(|e| e.to_string())?;
+ let n = order.len();
+ if order.iter().any(|&(k, _, _)| k as usize >= posed.len()) {
+ return Err("a skinned model whose triangles are not the scene's".into());
+ }
+ let (mut verts, mut a_tris, mut blas_verts, mut t) = (Vec::with_capacity(n * 3), Vec::with_capacity(n), Vec::with_capacity(n * 3), Vec::with_capacity(n));
+ for &(k, section, rank) in order.iter() {
+ let q = &posed[k as usize];
+ let (e1, e2) = (q.p[1] - q.p[0], q.p[2] - q.p[0]);
+ verts.extend_from_slice(&[[q.p[0].x, q.p[0].y, q.p[0].z, f32::from_bits(scene::TRI_DYNAMIC)], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
+ a_tris.push(scene::section_attr(q.p, q.n, q.uv, q.tangent, section, rank));
+ blas_verts.extend(scene::blas_tri(q.p.map(|p| p.to_array())));
+ t.push(q.p.map(glam::Vec3A::from));
+ }
+ // Its triangles, and their previous frame's vertices: holes that fit, else the rooms' ends.
+ let first = match edit.tris.take(n) {
+ Some(f) => f,
+ None if match &mut top { gpu::Top::Hw(accel) => grow.tris(&mut edit.tris, n, &mut up.verts, &mut up.attrs, &mut up.words, vcolors, accel), gpu::Top::Sw(_) => false } => {
+ edit.grows += 1;
+ edit.rebind = true;
+ edit.tris.take(n).ok_or("edit room: triangles")?
+ }
+ None => return Err("edit room: triangles (particles, or the device's limits)".into()),
+ };
+ let prev = match edit.prev.take(n) {
+ Some(f) => f,
+ None if grow.prev(&mut edit.prev, n, &mut up.prev_verts) => {
+ edit.grows += 1;
+ edit.rebind = true;
+ edit.prev.take(n).ok_or("edit room: previous vertices")?
+ }
+ None => return Err("edit room: previous vertices (particles, or the device's limits)".into()),
+ };
+ // A freed mesh's slot (and its sections', where they are as many at least), else new ones: the
+ // model's sections, its own copy (a slot's are written over by the next mesh that takes it).
+ let dead = edit.dead_meshes.pop();
+ let sects = meshes[its_mesh as usize].sections(sections).to_vec();
+ let ns = sects.len();
+ let sect_first = match dead.map(|k| meshes[k as usize]).filter(|m| m.sect_count as usize >= ns) {
+ Some(m) => m.sect_first,
+ None => {
+ sections.resize(sections.len() + ns, scene::Section { first: 0, count: 0, slot: 0 });
+ (sections.len() - ns) as u32
+ }
+ };
+ sections[sect_first as usize..][..ns].copy_from_slice(&sects);
+ // (Other poses reach further: its bounds wider, as the build's.)
+ let own = scene::own_inst_mesh(&t, (first - edit.pool_first) as u32);
+ let pad = if a.nodes.is_empty() { (own.hi - own.lo) * 0.25 } else { glam::Vec3A::splat((own.hi - own.lo).length()) };
+ let im = scene::InstMesh { lo: own.lo - pad, hi: own.hi + pad, deforms: true, sect_first, sect_count: ns as u32, ..own };
+ let mesh = match &mut top {
+ gpu::Top::Hw(accel) => match dead {
+ Some(k) => {
+ g.set_mesh(accel, k, first, &im, sections);
+ k
+ }
+ None => g.add_mesh(accel, first, &im, sections),
+ },
+ gpu::Top::Sw(_) => unreachable!("refused above"),
+ };
+ if mesh as usize == meshes.len() {
+ meshes.push(im);
+ } else {
+ meshes[mesh as usize] = im;
+ }
+ edit.managed.insert(mesh);
+ *edit.users.entry(mesh).or_default() += 1;
+ new_meshes.push(mesh);
+ split.added += 1;
+ w_verts.put((first * 48) as u64, bytemuck::cast_slice(&verts));
+ w_attrs.put((first * std::mem::size_of::<scene::GpuTriAttr>()) as u64, bytemuck::cast_slice(&a_tris));
+ w_blas.put((first * 36) as u64, bytemuck::cast_slice(&blas_verts));
+ if vcolors {
+ w_colors.put((first * 12) as u64, bytemuck::cast_slice(&vec![scene::WHITE; n]));
+ }
+ // (It has not moved yet: its previous vertices are its own.)
+ q.write_buffer(&up.prev_verts, (prev * 48) as u64, bytemuck::cast_slice(&verts));
+ let rel = first - edit.pool_first;
+ if pool_tris.len() < rel + n {
+ pool_tris.resize(rel + n, [glam::Vec3A::ZERO; 3]);
+ }
+ pool_tris[rel..rel + n].copy_from_slice(&t);
+ // Its slot among the skinned (one an edit took out again, else a new one), and the pass's job.
+ let slot = edit.free_skinned.pop().unwrap_or(tables.retained.skinned.len() as u32);
+ let sk = scene::Skinned { mesh, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order, object: id, instance: 0, source, palette_len, mirrors };
+ if slot as usize == tables.retained.skinned.len() {
+ tables.retained.skinned.push(sk);
+ } else {
+ tables.retained.skinned[slot as usize] = sk;
+ }
+ let pass = up.skin.as_mut().ok_or("a scene without a skinning pass")?;
+ edit.rebind |= pass.set_job(&g.device, q, slot as usize, first as u32, n as u32, source, palette_len);
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine), prev: prev as u32 };
+ 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]);
+ (None, Placed::Skinned(inst, mine, slot), entry)
+ } else if let Some(a) = animation {
let parts = nodes.is_none().then(|| tables.retained.rigid_meshes.get(&(uri.clone(), scene::rigid_pose_key(a)))).flatten().ok_or("an animated model that is no rigid one of the scene's with this pose's nodes (its meshes are a build's to make)")?.clone();
let globals = scene::model_gltf(uri, assets).and_then(|g| g.node_globals(Some(a))).map_err(|e| e.to_string())?;
let (mut lo, mut hi) = (glam::Vec3A::splat(f32::MAX), glam::Vec3A::splat(f32::MIN));
@@ -2383,7 +2570,7 @@ impl LiveCore {
let (w_n, _) = scene::placed_world(scene::RigidModel::part_world(m, node, &globals), m.w_axis.truncate());
let (plo, phi) = meshes[mesh as usize].placed_bounds(w_n);
(lo, hi) = (lo.min(plo), hi.max(phi));
- let inst = scene::Instance { mesh, world: w_n, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) };
+ let inst = scene::Instance { mesh, world: w_n, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine), prev: 0 };
placed.push((node, inst, mine));
}
for &(_, mesh) in &parts {
@@ -2406,7 +2593,7 @@ impl LiveCore {
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: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) };
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine), prev: 0 };
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]);
(at.map(|(_, r)| r), Placed::Mesh(inst, mine), entry)
@@ -2644,7 +2831,7 @@ impl LiveCore {
};
let (st, size) = (tables.stride, std::mem::size_of::<scene::GpuInstance>());
if instances.len() < r0 + cap {
- let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 };
instances.resize(r0 + cap, filler);
}
if gpu_instances.len() < r0 + cap {
@@ -2659,7 +2846,7 @@ impl LiveCore {
let row_at = run + i;
let mut row = scene::row_of(mat, &tables.materials);
row[1] = edit.pool_first as u32 + im.first;
- let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: scene::rows_cast(&[row], o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: row_at as u32, bits: scene::rows_bits(&[row]) };
+ let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: scene::rows_cast(&[row], o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: row_at as u32, bits: scene::rows_bits(&[row]), prev: 0 };
// A copy whose material emits: its emitters, a run at the light list's end; moving ones
// (`update_instanced` changes the copies in place), a hidden copy's at no weight.
if emits {
@@ -2699,7 +2886,7 @@ impl LiveCore {
if scene::rows_bits(&mine) & scene::INST_GLASS != 0 && scene::rows_cast(&mine, o.cast_shadow) && features & gpu::F_IGLASS == 0 {
return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) };
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine), prev: 0 };
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), if unseen { 0.0 } else { o.power }, hi - lo, o.custom, [1.0; 3]);
(at.map(|(_, r)| r), Placed::Mesh(inst, mine), entry)
@@ -2755,6 +2942,12 @@ impl LiveCore {
let mesh = if matches!(o.kind, Kind::Model { .. }) { scene::MeshKind::Model } else { scene::MeshKind::Own };
scene::Draw::Instance(scene::InstanceRef { instance: record as u32, mesh, moves })
}
+ // A posed skinned model: the instance of its own mesh; a move is its transform's.
+ Placed::Skinned(mut inst, mut mine, g) => {
+ place(record, &mut inst, &mut mine, true)?;
+ tables.retained.skinned[g as usize].instance = record as u32;
+ scene::Draw::Instance(scene::InstanceRef { instance: record as u32, mesh: scene::MeshKind::Skinned(g), moves: true })
+ }
// A posed rigid model: a part a record, the nodes a pose may move with moving emitters; where it
// stands as an update finds it (`repose_rigid` tells a move by that).
Placed::Parts(parts) => {
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 00aa6fb..c1a4d8f 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -330,9 +330,9 @@ impl LiveCore {
self.prev_span = None;
}
self.reposed = false;
- if let (false, Some(span)) = (self.pose_reposed, self.pose_span) {
- self.keep_prev(span);
- self.pose_span = None;
+ if !self.pose_reposed && !self.pose_spans.is_empty() {
+ let spans = std::mem::take(&mut self.pose_spans);
+ self.keep_prev_spans(&spans);
}
self.pose_reposed = false;
// Likewise the instances the last update moved: their previous-frame rows become the current ones.
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 8b22bdc..a8bc4f9 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -2281,6 +2281,7 @@ fn a_posed_rigid_model_is_hidden_shown_and_removed_in_place() {
Err(e) => return eprintln!("skipped: {e}"),
};
w.take_changes();
+ assert!(live.sc.up.kernel.features & gpu::F_DEFORM == 0, "no mesh deforms here: the kernel has none of that");
let records = |c: &LiveCore, id: u32| c.sc.tables.retained.rigid(id).expect("a posed rigid model").records();
let (a, b) = (records(&live, 32), records(&live, 33));
let seen = |c: &LiveCore, of: &[u32]| of.iter().map(|&i| (c.sc.instances[i as usize].hidden, c.sc.instances[i as usize].masked)).collect::<Vec<_>>();
@@ -2553,6 +2554,7 @@ fn posed_skinned_models_are_meshes_of_their_own() {
let of = |c: &LiveCore, id: u32| c.sc.tables.retained.skinned.iter().find(|s| s.object == id).expect("a posed skinned model").clone();
let (a, b) = (of(&live, 30), of(&live, 31));
assert_eq!((live.sc.tables.retained.skinned.len(), a.mesh != b.mesh, a.source == b.source, live.sc.meshes[a.mesh as usize].sect_count), (2, true, true, 2), "two meshes of two sections, skinned from the model's one copy of its corners");
+ assert!(live.sc.up.kernel.features & gpu::F_DEFORM != 0, "the kernel finds a deforming mesh's previous vertices by its instance");
let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
let mut fresh = open(w).unwrap();
forget(live);
@@ -2643,6 +2645,424 @@ fn a_posed_skinned_model_is_hidden_and_shown_in_place() {
assert!(apart(&shown, &again) < 0.5, "as before it was hidden ({:.2} steps)", apart(&shown, &again));
}
+/// A posed skinned model of a model the scene has is added in place: a mesh of its own in the room, skinned as the
+/// build skins one, its previous vertices its own, a job of the pass. It is then posed, moved, hidden, shown and
+/// removed as one a build placed, and the next one added takes what it had. Many added at once make every room grow.
+/// Its motion (the kernel finds a deforming mesh's previous vertices through its instance) is a built one's. One of a
+/// model the scene has not, or in a pose that mirrors otherwise, is a rebuild's; so is any under software traversal.
+#[test]
+fn a_posed_skinned_model_is_added_in_place() {
+ 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 pose = |clip: &str, time| crate::desc::Animation { clip: clip.into(), time, r#loop: true, nodes: Default::default() };
+ let bend = |time| pose("bend", time);
+ let file = |name: &str| format!("tests/render/data/{name}.glb");
+ let model = |name: &str, a: crate::desc::Animation| Kind::Model { uri: file(name), nodes: None, animation: Some(a), functions: vec![] };
+ let mut w = world();
+ for (id, name, x) in [(30, "arm", -1.2), (31, "skin-blend", 1.3)] {
+ w.set_object(id, format!("m{id}"), None, model(name, bend(0.0)), true, false).unwrap();
+ w.set_transform(id, Vec3::new(x, -0.8, 0.8), glam::Quat::IDENTITY, Vec3::splat(1.2)).unwrap();
+ }
+ // (A movable rect light's card: world-space triangles that move, whose previous vertices lie before the meshes'.)
+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 0.3, "height": 0.3, "range": 0 })).unwrap();
+ w.set_object(22, "card".into(), None, Kind::Light(card), true, true).unwrap();
+ w.set_transform(22, Vec3::new(-2.4, 1.3, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ // (The build's frames counted from the live view's: a frame's samples go by its number, and a picture of many
+ // thin models is two thirds of a step from itself at another count, more than a model that is not drawn.)
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
+ let mut fresh = open(w).unwrap();
+ fresh.frame = live.frame;
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.35, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ a
+ };
+ let loaded = against_a_build("as loaded", &mut live, &w);
+ let add = |w: &mut World, id: u32, name: &str, a: crate::desc::Animation, at: Vec3| {
+ w.set_object(id, format!("m{id}"), None, model(name, a), true, false).unwrap();
+ w.set_transform(id, at, glam::Quat::from_rotation_y(0.3), Vec3::splat(1.2)).unwrap();
+ };
+ if !live.g.hwrt {
+ // (With a mesh the scene says it edits, so that there is room for triangles: the model is still a rebuild's.)
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(1.4, -0.7, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ live = open(&w).unwrap();
+ w.take_changes();
+ assert!(live.sc.edit.tris.cap > live.sc.edit.tris.end + 8, "the room has triangles to give");
+ let loaded = against_a_build("as loaded, with a mesh to edit", &mut live, &w);
+ add(&mut w, 32, "arm", bend(0.3), Vec3::new(-0.2, -0.8, 0.9));
+ assert!(live.commit(&mut w).unwrap(), "added under software traversal: a rebuild");
+ let added = against_a_build("added under software traversal", &mut live, &w);
+ assert!(apart(&loaded, &added) > 0.5, "it is in the picture ({:.2} steps)", apart(&loaded, &added));
+ return;
+ }
+ let read = |c: &LiveCore, b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<f32> {
+ let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut e = c.g.device.create_command_encoder(&Default::default());
+ e.copy_buffer_to_buffer(b, at, &to, 0, bytes);
+ c.g.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ c.g.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let words = bytemuck::pod_collect_to_vec(&to.slice(..).get_mapped_range().unwrap());
+ words
+ };
+ let of = |c: &LiveCore, id: u32| c.sc.tables.retained.skinned.iter().position(|s| s.object == id && s.mesh != u32::MAX).expect("a posed skinned model");
+ // What the CPU skin gives a model's mesh for a pose: vertices (48 B a triangle), attributes (96 B), BLAS input (36 B).
+ let cpu = |c: &LiveCore, id: u32, a: &crate::desc::Animation| {
+ let sk = &c.sc.tables.retained.skinned[of(c, id)];
+ let tris = scene::model_gltf(&sk.uri, Path::new("..")).unwrap().triangles(glam::Mat4::IDENTITY, None, Some(a)).unwrap();
+ let (mut v, mut at, mut b): (Vec<f32>, Vec<f32>, Vec<f32>) = Default::default();
+ for &(k, section, rank) in sk.order.iter() {
+ let q = &tris[k as usize];
+ let (e1, e2) = (q.p[1] - q.p[0], q.p[2] - q.p[0]);
+ v.extend([q.p[0].x, q.p[0].y, q.p[0].z, f32::from_bits(scene::TRI_DYNAMIC), e1.x, e1.y, e1.z, 0.0, e2.x, e2.y, e2.z, 0.0]);
+ at.extend(bytemuck::cast_slice::<_, f32>(&[scene::section_attr(q.p, q.n, q.uv, q.tangent, section, rank)]));
+ b.extend(q.p.iter().flat_map(|p| p.to_array()));
+ }
+ (v, at, b)
+ };
+ let same = |what: &str, got: &[f32], want: &[f32], words: &[usize], stride: usize| {
+ assert_eq!(got.len(), want.len(), "{what}: its length");
+ for (i, (g, x)) in got.iter().zip(want).enumerate() {
+ let ok = if words.contains(&(i % stride)) { g.to_bits() == x.to_bits() } else { (g - x).abs() <= 2e-5 * x.abs().max(1.0) };
+ assert!(ok, "{what}: word {} of triangle {}: {g} ({:#x}), the CPU's {x} ({:#x})", i % stride, i / stride, g.to_bits(), x.to_bits());
+ }
+ };
+ // A model's mesh on the GPU against the CPU skin of `now`; its previous vertices against that of `before`.
+ let check = |what: &str, c: &LiveCore, id: u32, now: &crate::desc::Animation, before: &crate::desc::Animation| {
+ let sk = &c.sc.tables.retained.skinned[of(c, id)];
+ let inst = &c.sc.instances[sk.instance as usize];
+ let (k, n, prev) = (c.sc.gpu_instances[sk.instance as usize].info[0] as u64, sk.order.len() as u64, inst.prev as u64);
+ assert_eq!(c.sc.gpu_instances[sk.instance as usize].n[2][3].to_bits() as u64, prev, "{what}: the record has where the mesh's previous vertices are");
+ let (up, (cv, cat, cb)) = (&c.sc.up, cpu(c, id, now));
+ same(&format!("{what}: the vertices"), &read(c, &up.verts, k * 48, n * 48), &cv, &[3], 12);
+ same(&format!("{what}: the attributes"), &read(c, &up.attrs, k * 96, n * 96), &cat, &[15, 21, 22, 23], 24);
+ same(&format!("{what}: the BLAS input"), &read(c, &up.accel.as_ref().unwrap().verts, k * 36, n * 36), &cb, &[], 9);
+ same(&format!("{what}: the previous frame's vertices"), &read(c, &up.prev_verts, prev * 48, n * 48), &cpu(c, id, before).0, &[3], 12);
+ let asked: Vec<f32> = c.node_tris(&format!("m{id}")).iter().flatten().flat_map(|p| p.to_array()).collect();
+ let placed: Vec<f32> = cb.chunks_exact(3).flat_map(|p| inst.world.transform_point3(Vec3::new(p[0], p[1], p[2])).to_array()).collect();
+ same(&format!("{what}: the mesh as the CPU has it when asked"), &asked, &placed, &[], 9);
+ };
+ let built = live.sc.tables.retained.skinned.len();
+ let prev_size = live.sc.up.prev_verts.size();
+ {
+ let i = &live.sc.instances[live.sc.tables.retained.skinned[of(&live, 31)].instance as usize];
+ assert!(live.sc.dynamic.1.len() == 6 && i.prev == live.sc.meshes[i.mesh as usize].first + 2, "a mesh's previous vertices lie after the card's two triangles'");
+ }
+
+ // One of a model the scene has, in a pose of its own.
+ add(&mut w, 32, "arm", bend(0.3), Vec3::new(-0.2, -0.8, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "added: in place ({:?})", live.fallback);
+ let (g, t) = (of(&live, 32), of(&live, 30));
+ let (sk, its) = (live.sc.tables.retained.skinned[g].clone(), live.sc.tables.retained.skinned[t].clone());
+ assert_eq!((g, sk.source, sk.mesh != its.mesh, live.sc.meshes[sk.mesh as usize].deforms), (built, its.source, true, true), "a mesh of its own that deforms, skinned from the model's one copy of its corners, the next of the skinned");
+ assert!(live.sc.edit.in_room(sk.instance as usize) && live.sc.instances[sk.instance as usize].prev as usize >= live.sc.edit.prev.base && seen_by_rays(&live, sk.instance), "its record and its previous vertices are the room's, and the rays see it");
+ assert!(live.sc.up.prev_verts.size() > prev_size, "the previous vertices' buffer was made again, larger");
+ check("added", &live, 32, &bend(0.3), &bend(0.3));
+ check("the built one beside it", &live, 30, &bend(0.0), &bend(0.0));
+ let added = against_a_build("added", &mut live, &w);
+ assert!(apart(&loaded, &added) > 0.5, "it is in the picture ({:.2} steps)", apart(&loaded, &added));
+
+ // Its motion at a new pose is a built one's: the same world built, both posed on in place, a frame of each.
+ let mut w2 = w.clone();
+ let mut fresh = open(&w2).unwrap();
+ w2.take_changes();
+ for id in [30, 31, 32] {
+ w.set_animation(id, Some(bend(0.8))).unwrap();
+ w2.set_animation(id, Some(bend(0.8))).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap() && !fresh.commit(&mut w2).unwrap(), "posed on: in place ({:?}, {:?})", live.fallback, fresh.fallback);
+ check("posed on", &live, 32, &bend(0.8), &bend(0.3));
+ check("the built one posed on", &live, 30, &bend(0.8), &bend(0.0));
+ check("the other built one posed on", &live, 31, &bend(0.8), &bend(0.0));
+ // (The card did not move: its previous vertices are its own, whatever the meshes' did.)
+ assert_eq!(read(&live, &live.sc.up.prev_verts, 0, 96), read(&live, &live.sc.up.verts, live.sc.dynamic.0 as u64 * 48, 96), "the card's previous vertices are its vertices");
+ let motion = |c: &mut LiveCore| -> Vec<f32> {
+ (c.fixed_dt, c.frame, c.reset) = (Some(1.0 / 60.0), 16, true);
+ c.render(1, |_, _| {});
+ let m = &c.targets.kernel.motion;
+ read(c, &m.buffer, m.offset, m.size)
+ };
+ let (a, b) = (motion(&mut live), motion(&mut fresh));
+ let moving = |m: &[f32]| m.chunks_exact(4).filter(|p| p[3] > 0.5 && (p[0].abs() + p[1].abs() + p[2].abs()) > 1e-3).count();
+ assert!(moving(&a) > 20 && moving(&a) == moving(&b), "pixels that moved: {} here, {} in a build", moving(&a), moving(&b));
+ let off = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
+ assert!(off < 1e-3, "the motion vectors are a build's (off by {off} at most)");
+ // No vector is longer than the furthest a corner of a model went (a kernel that takes another triangle's previous
+ // vertices gives vectors as long as the mesh; another mesh's, anything), and some are nearly as long.
+ let reach = |c: &LiveCore, id: u32, before: &crate::desc::Animation| -> f32 {
+ let world = c.sc.instances[c.sc.tables.retained.skinned[of(c, id)].instance as usize].world;
+ let corners = |v: &[f32]| -> Vec<Vec3> {
+ v.chunks_exact(12).flat_map(|t| { let (p, e1, e2) = (Vec3::new(t[0], t[1], t[2]), Vec3::new(t[4], t[5], t[6]), Vec3::new(t[8], t[9], t[10])); [p, p + e1, p + e2] }).collect()
+ };
+ corners(&cpu(c, id, &bend(0.8)).0).iter().zip(corners(&cpu(c, id, before).0)).map(|(x, y)| world.transform_vector3(*x - y).length()).fold(0.0, f32::max)
+ };
+ let far = [(30, bend(0.0)), (31, bend(0.0)), (32, bend(0.3))].iter().map(|(id, before)| reach(&live, *id, before)).fold(0.0f32, f32::max);
+ let longest = a.chunks_exact(4).filter(|p| p[3] > 0.5).map(|p| Vec3::new(p[0], p[1], p[2]).length()).fold(0.0f32, f32::max);
+ assert!(longest <= far * 1.001 + 1e-4 && longest > far * 0.2, "the longest motion vector is {longest}; the furthest a corner went, {far}");
+ drop(fresh);
+
+ // Moved, hidden and shown, as one a build placed.
+ w.set_transform(32, Vec3::new(0.2, -0.7, 1.0), glam::Quat::from_rotation_y(-0.4), Vec3::splat(1.2)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the one added moved: in place ({:?})", live.fallback);
+ assert_eq!(live.sc.instances[sk.instance as usize].world, w.world_matrix(32), "its instance stands where it was moved to");
+ let moved = against_a_build("the one added moved", &mut live, &w);
+ w.set_visible(32, false).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the one added hidden: in place ({:?})", live.fallback);
+ assert!(!seen_by_rays(&live, sk.instance), "no ray sees it");
+ against_a_build("the one added hidden", &mut live, &w);
+ w.set_visible(32, true).unwrap();
+ w.set_animation(32, Some(bend(0.5))).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the one added shown and posed: in place ({:?})", live.fallback);
+ check("shown and posed", &live, 32, &bend(0.5), &bend(0.8));
+ let shown = against_a_build("the one added shown", &mut live, &w);
+ assert!(apart(&moved, &shown) > 0.2, "its new pose is in the picture ({:.2} steps)", apart(&moved, &shown));
+
+ // Many at once, of both models (more triangles than the room has): every room grows again, and each is skinned as
+ // the build skins it.
+ let (tris_size, ids) = (live.sc.up.verts.size(), (100..140).collect::<Vec<u32>>());
+ for (k, &id) in ids.iter().enumerate() {
+ add(&mut w, id, if k % 2 == 0 { "skin-blend" } else { "arm" }, bend(0.1 + 0.02 * k as f32), Vec3::new(-1.5 + 0.075 * k as f32, 0.3, 0.6));
+ }
+ assert!(!live.commit(&mut w).unwrap(), "40 added at once: in place ({:?})", live.fallback);
+ assert!(live.sc.up.verts.size() > tris_size, "the triangles' buffer was made again, larger");
+ for (k, &id) in ids.iter().enumerate() {
+ let a = bend(0.1 + 0.02 * k as f32);
+ check(&format!("one of 40 added ({id})"), &live, id, &a, &a);
+ }
+ // (Frames were drawn since its last pose: its previous vertices are that pose's too.)
+ check("the first added, after the rooms grew", &live, 32, &bend(0.5), &bend(0.5));
+ against_a_build("40 added at once", &mut live, &w);
+ // Every other one hidden, and shown again.
+ for &id in ids.iter().step_by(2) {
+ w.set_visible(id, false).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "20 of them hidden: in place ({:?})", live.fallback);
+ against_a_build("20 of them hidden", &mut live, &w);
+ for &id in ids.iter().step_by(2) {
+ w.set_visible(id, true).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "shown again: in place ({:?})", live.fallback);
+ // (A model shown has its power back, and what a power edit touched keeps a short history for half a second of the
+ // scene's clock, which a game's frames advance and a test's do not: past it.)
+ for _ in 0..6 {
+ live.advance_time(0.1);
+ }
+ against_a_build("the 20 shown again", &mut live, &w);
+ for &id in &ids {
+ w.set_animation(id, Some(bend(0.9))).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "the 40 posed on: in place ({:?})", live.fallback);
+ for (k, &id) in ids.iter().enumerate() {
+ check(&format!("one of 40 posed on ({id})"), &live, id, &bend(0.9), &bend(0.1 + 0.02 * k as f32));
+ }
+ against_a_build("the 40 posed on", &mut live, &w);
+
+ // Removed: its slot among the skinned, its record, its triangles and its previous vertices are the room's again,
+ // and the next one added takes them.
+ let (mesh, prev, tri) = (sk.mesh, live.sc.instances[sk.instance as usize].prev, live.sc.gpu_instances[sk.instance as usize].info[0]);
+ w.remove(32);
+ assert!(!live.commit(&mut w).unwrap(), "the one added removed: in place ({:?})", live.fallback);
+ assert!(live.sc.tables.retained.skinned[g].mesh == u32::MAX && live.sc.edit.free_skinned == vec![g as u32] && live.sc.edit.dead_meshes.contains(&mesh) && !seen_by_rays(&live, sk.instance), "its slot and its mesh are free, no ray sees it");
+ assert!(live.sc.edit.prev.free.iter().any(|(&at, &n)| at <= prev as usize && prev as usize + 4 <= at + n), "its previous vertices are the room's again");
+ against_a_build("the one added removed", &mut live, &w);
+ add(&mut w, 34, "arm", bend(0.6), Vec3::new(0.0, -0.8, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "the next added: in place ({:?})", live.fallback);
+ let next = live.sc.tables.retained.skinned[of(&live, 34)].clone();
+ assert_eq!((of(&live, 34), next.mesh, next.instance, live.sc.instances[next.instance as usize].prev, live.sc.gpu_instances[next.instance as usize].info[0]), (g, mesh, sk.instance, prev, tri), "it has the slot, the mesh, the record, the previous vertices and the triangles of the one removed");
+ check("the next added", &live, 34, &bend(0.6), &bend(0.6));
+ w.set_animation(34, Some(bend(0.2))).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the next added posed on: in place ({:?})", live.fallback);
+ check("the next added posed on", &live, 34, &bend(0.2), &bend(0.6));
+ against_a_build("the next added posed on", &mut live, &w);
+
+ // One the build placed removed, and another of its model added: the build's mesh stays, the model is still the scene's.
+ w.remove(30);
+ add(&mut w, 35, "arm", bend(0.4), Vec3::new(-1.2, -0.8, 0.8));
+ assert!(!live.commit(&mut w).unwrap(), "a built one removed and another of its model added: in place ({:?})", live.fallback);
+ check("another of a removed one's model", &live, 35, &bend(0.4), &bend(0.4));
+ against_a_build("a built one removed and another added", &mut live, &w);
+
+ // More of them, in one commit that makes no room grow but the skinning pass's own: the pass reads its new table.
+ let (grows, rooms, more) = (live.sc.edit.grows, live.sc.up.skin.as_ref().unwrap().rooms(), (200..224).collect::<Vec<u32>>());
+ for (k, &id) in more.iter().enumerate() {
+ add(&mut w, id, "arm", bend(0.33), Vec3::new(-2.8 + 0.1 * k as f32, -1.6, 0.9));
+ }
+ assert!(!live.commit(&mut w).unwrap(), "24 more added: in place ({:?})", live.fallback);
+ assert!(live.sc.edit.grows == grows && live.sc.up.skin.as_ref().unwrap().rooms() != rooms, "no room grew but the pass's ({:?} -> {:?})", rooms, live.sc.up.skin.as_ref().unwrap().rooms());
+ for &id in &more {
+ w.set_animation(id, Some(bend(0.7))).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "the 24 posed on: in place ({:?})", live.fallback);
+ for &id in &more {
+ check(&format!("one of 24 more posed on ({id})"), &live, id, &bend(0.7), &bend(0.33));
+ }
+ for &id in &more {
+ w.remove(id);
+ }
+ assert!(!live.commit(&mut w).unwrap(), "the 24 removed: in place ({:?})", live.fallback);
+ against_a_build("24 more added, posed and removed", &mut live, &w);
+
+ // Previous vertices kept mesh by mesh. Two more, one after the other in the room; the first posed and, before a
+ // frame is drawn, removed, a mesh of two triangles and a third model taking what it had: the third's previous
+ // vertices are where the first's were, its triangles are not.
+ let place = |c: &LiveCore, id: u32| {
+ let i = c.sc.tables.retained.instance(id).unwrap().instance as usize;
+ (c.sc.gpu_instances[i].info[0], c.sc.instances[i].prev)
+ };
+ add(&mut w, 50, "arm", bend(0.1), Vec3::new(-2.6, -0.2, 0.7));
+ add(&mut w, 51, "arm", bend(0.1), Vec3::new(-2.1, -0.2, 0.7));
+ assert!(!live.commit(&mut w).unwrap(), "two more: in place ({:?})", live.fallback);
+ let ((ta, pa), (tb, pb)) = (place(&live, 50), place(&live, 51));
+ assert_eq!((tb, pb), (ta + 4, pa + 4), "the two lie one after the other");
+ picture(&mut live, 2);
+ w.set_animation(50, Some(bend(0.5))).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the first posed: in place ({:?})", live.fallback);
+ w.remove(50);
+ w.set_geometry(8, Geometry { positions: vec![-0.1, -0.1, 0.0, 0.1, -0.1, 0.0, 0.1, 0.1, 0.0, -0.1, 0.1, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] }).unwrap();
+ w.set_object(49, "two".into(), None, Kind::Mesh { geometry: 8, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(49, Vec3::new(-2.6, 0.6, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ add(&mut w, 52, "arm", bend(0.2), Vec3::new(-2.6, -0.2, 0.7));
+ assert!(!live.commit(&mut w).unwrap(), "the first removed, a mesh and a third added: in place ({:?})", live.fallback);
+ assert_eq!(place(&live, 52), (tb + 4, pa), "the third: its triangles after the second's, its previous vertices where the first's were");
+ picture(&mut live, 4);
+ check("the third, frames on (the first's pose is no one's to keep)", &live, 52, &bend(0.2), &bend(0.2));
+ // The second and the third posed; then, before a frame is drawn, the third alone again: the second's previous
+ // vertices are its pose's (it stands), the third's the pose between.
+ w.set_animation(51, Some(bend(0.6))).unwrap();
+ w.set_animation(52, Some(bend(0.7))).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "both posed: in place ({:?})", live.fallback);
+ w.set_animation(52, Some(bend(0.9))).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the third posed again: in place ({:?})", live.fallback);
+ check("the second, which stands", &live, 51, &bend(0.6), &bend(0.6));
+ check("the third, posed twice", &live, 52, &bend(0.9), &bend(0.7));
+ against_a_build("previous vertices kept mesh by mesh", &mut live, &w);
+
+ // A rebuild's: one whose pose mirrors other primitives than the scene's; one of a model the scene has not (by its nodes).
+ add(&mut w, 36, "skin-blend", pose("flip", 0.9), Vec3::new(0.6, 0.4, 0.7));
+ assert!(live.commit(&mut w).unwrap(), "one whose pose mirrors otherwise: a rebuild");
+ against_a_build("one whose pose mirrors otherwise", &mut live, &w);
+ w.set_object(37, "m37".into(), None, Kind::Model { uri: file("skin-blend"), nodes: Some(vec!["strip".into()]), animation: Some(bend(0.2)), functions: vec![] }, true, false).unwrap();
+ w.set_transform(37, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::splat(1.2)).unwrap();
+ assert!(live.commit(&mut w).unwrap(), "one of a model the scene has not: a rebuild");
+ against_a_build("one of a model the scene has not", &mut live, &w);
+}
+
+/// In a scene with particle systems the rooms for edits do not grow (the particle passes hold the scene's buffers),
+/// and a skinned model added needs room for its previous vertices: a rebuild's, as a mesh larger than the room is
+/// there. Posed on and removed, the build's are in place as anywhere.
+#[test]
+fn a_posed_skinned_model_added_beside_particles_is_a_rebuilds() {
+ 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 bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
+ let arm = |time| Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: bend(time), functions: vec![] };
+ let mut w = world();
+ w.set_particle_fn("spark", "fn pf_spark(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(0.3, 0.2, 1.0), vec3<f32>(0.05, 0.0, 0.0), vec3<f32>(0.0, 0.05, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());
+ w.set_object(18, "sparks".into(), None, Kind::Particles { count: 3, emitter: "spark".into(), params: vec![], material: 5, emitter_area: 0.01 }, true, false).unwrap();
+ // (A mesh the scene says it edits: room for triangles and records, which a model's instance would take.)
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(1.4, -0.7, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ for (id, x) in [(30, -0.9), (31, 0.0)] {
+ w.set_object(id, format!("arm{id}"), None, arm(0.0), true, false).unwrap();
+ w.set_transform(id, Vec3::new(x, -1.0, 0.8), glam::Quat::IDENTITY, Vec3::splat(2.0)).unwrap();
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ if !live.g.hwrt {
+ return eprintln!("skipped: no hardware ray tracing");
+ }
+ assert!(live.sc.up.particles.is_some() && live.sc.edit.tris.cap >= live.sc.edit.tris.end + 4, "a scene with a particle pass, and room for a model's triangles");
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
+ let mut fresh = open(w).unwrap();
+ fresh.frame = live.frame;
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.35, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ };
+ w.set_animation(30, bend(0.6)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "a built one posed: in place ({:?})", live.fallback);
+ against_a_build("a built one posed", &mut live, &w);
+ w.set_object(32, "arm32".into(), None, arm(0.3), true, false).unwrap();
+ w.set_transform(32, Vec3::new(0.9, -1.0, 0.8), glam::Quat::IDENTITY, Vec3::splat(2.0)).unwrap();
+ assert!(live.commit(&mut w).unwrap(), "one added beside particles: a rebuild");
+ assert!(live.fallback.as_deref().is_some_and(|f| f.contains("previous vertices")), "for its previous vertices' room ({:?})", live.fallback);
+ against_a_build("one added beside particles", &mut live, &w);
+ w.remove(31);
+ assert!(!live.commit(&mut w).unwrap(), "one removed beside particles: in place ({:?})", live.fallback);
+ against_a_build("one removed beside particles", &mut live, &w);
+}
+
+/// A posed skinned model is removed in place: its instance is no object's and no ray sees it, the others are posed
+/// on as ever, and the picture is a build's. One that is hidden is removed in place too. (Under software traversal,
+/// where it has no instance, by a rebuild.)
+#[test]
+fn a_posed_skinned_model_is_removed_in_place() {
+ 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 bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
+ let mut w = world();
+ for (id, x) in [(30, -0.9), (31, 0.0), (32, 0.9)] {
+ w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: bend(0.0), functions: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(x, -1.0, 0.8), glam::Quat::IDENTITY, Vec3::splat(2.0)).unwrap();
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
+ let mut fresh = open(w).unwrap();
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ a
+ };
+ let loaded = against_a_build("as loaded", &mut live, &w);
+ if !live.g.hwrt {
+ w.remove(31);
+ assert!(live.commit(&mut w).unwrap(), "removed under software traversal: a rebuild");
+ let removed = against_a_build("removed under software traversal", &mut live, &w);
+ assert!(apart(&loaded, &removed) > 0.5, "it is out of the picture ({:.2} steps)", apart(&loaded, &removed));
+ return;
+ }
+ let record = |c: &LiveCore, id: u32| c.sc.tables.retained.instance(id).expect("a posed skinned model").instance;
+ let (r30, r31, r32) = (record(&live, 30), record(&live, 31), record(&live, 32));
+ w.remove(31);
+ assert!(!live.commit(&mut w).unwrap(), "removed: in place ({:?})", live.fallback);
+ assert!(!seen_by_rays(&live, r31) && seen_by_rays(&live, r30) && seen_by_rays(&live, r32), "no ray sees the one removed; the others are seen");
+ assert!(live.sc.tables.retained.instance(31).is_none() && live.pick(0.5, 0.5).is_none_or(|p| p.0 != "arm31"), "it is no object's, and a click does not find it");
+ let removed = against_a_build("removed", &mut live, &w);
+ assert!(apart(&loaded, &removed) > 0.5, "it is out of the picture ({:.2} steps)", apart(&loaded, &removed));
+ // The others posed and moved on, in place.
+ w.set_animation(30, bend(0.7)).unwrap();
+ w.set_transform(32, Vec3::new(0.3, -0.9, 0.9), glam::Quat::from_rotation_y(0.4), Vec3::splat(2.0)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the others posed and moved: in place ({:?})", live.fallback);
+ let on = against_a_build("the others posed and moved", &mut live, &w);
+ assert!(apart(&removed, &on) > 0.5, "that is in the picture ({:.2} steps)", apart(&removed, &on));
+ // One hidden, then removed: in place both.
+ w.set_visible(32, false).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "hidden: in place ({:?})", live.fallback);
+ w.remove(32);
+ assert!(!live.commit(&mut w).unwrap(), "a hidden one removed: in place ({:?})", live.fallback);
+ assert!(!seen_by_rays(&live, r32) && live.sc.tables.retained.instance(32).is_none(), "no ray sees it, it is no object's");
+ against_a_build("a hidden one removed", &mut live, &w);
+ // The last, posed in the commit that removes it: in place, nothing left of it.
+ w.set_animation(30, bend(0.2)).unwrap();
+ w.remove(30);
+ assert!(!live.commit(&mut w).unwrap(), "posed and removed at once: in place ({:?})", live.fallback);
+ assert!(!seen_by_rays(&live, r30), "no ray sees it");
+ against_a_build("all removed", &mut live, &w);
+}
+
/// The skinning pass writes what the CPU skin writes. Two models (tests/render/data/skin-blend.glb: 72 triangles,
/// vertices two joints hold, weights that do not sum to one, a primitive with tangents and one without normals, a
/// mesh on a node beside the skin that mirrors it, a joint turned about an axis that is neither the normals' nor the
@@ -2698,7 +3118,7 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {
let (uri, order, _, _) = &deforming(c)[g];
let tris = scene::model_gltf(uri, Path::new("..")).unwrap().triangles(glam::Mat4::IDENTITY, None, Some(a)).unwrap();
let (mut v, mut at, mut b): (Vec<f32>, Vec<f32>, Vec<f32>) = Default::default();
- for &(k, section, rank) in order {
+ for &(k, section, rank) in order.iter() {
let q = &tris[k as usize];
let (e1, e2) = (q.p[1] - q.p[0], q.p[2] - q.p[0]);
v.extend([q.p[0].x, q.p[0].y, q.p[0].z, f32::from_bits(scene::TRI_DYNAMIC), e1.x, e1.y, e1.z, 0.0, e2.x, e2.y, e2.z, 0.0]);
@@ -2719,7 +3139,10 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {
let (_, order, instance, _) = &deforming(c)[g];
let (k, n) = (c.sc.gpu_instances[*instance as usize].info[0] as u64, order.len() as u64);
let up = &c.sc.up;
- (read(c, &up.verts, k * 48, n * 48), read(c, &up.attrs, k * 96, n * 96), read(c, &up.accel.as_ref().unwrap().verts, k * 36, n * 36), read(c, &up.prev_verts, (k - c.sc.dynamic.0 as u64) * 48, n * 48))
+ // (Its previous vertices: where its instance's record says, on the CPU and on the GPU.)
+ let prev = c.sc.instances[*instance as usize].prev;
+ assert_eq!(c.sc.gpu_instances[*instance as usize].n[2][3].to_bits(), prev, "the record has where the mesh's previous vertices are");
+ (read(c, &up.verts, k * 48, n * 48), read(c, &up.attrs, k * 96, n * 96), read(c, &up.accel.as_ref().unwrap().verts, k * 36, n * 36), read(c, &up.prev_verts, prev as u64 * 48, n * 48))
};
let check_one = |what: &str, c: &LiveCore, g: usize, now: &crate::desc::Animation, before: &crate::desc::Animation| {
let what = format!("{what}, {} (object {})", deforming(c)[g].0, deforming(c)[g].3);
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index a9ffd63..f1085eb 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -305,6 +305,13 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
row_runs: Default::default(),
pool_first: prep.groups.iter().sum(),
blobs,
+ // (What `prev_verts` holds at the build: the dynamic triangles and the deforming meshes after them. No room:
+ // it grows with the first deforming mesh an edit places.)
+ prev: {
+ let n = prep.groups.iter().sum::<usize>() + scene::deforming_pool(&meshes) - up.dynamic_first;
+ Holes::new(n, n)
+ },
+ free_skinned: vec![],
};
Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, pool_place, meshes, instances, sections, rows, 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, codes_sent: vec![] }, view, env))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 034e2b2..962a521 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -341,9 +341,9 @@ pub struct LiveCore {
pending_emitters: Vec<(u32, crate::GpuEmitterTri)>,
/// Objects whose instance a move hid or brought back this commit (a placement without size): their rows' power.
flipped: Vec<u32>,
- /// Likewise for posed skinned models' meshes (`repose_skinned`): the span they took (relative to the dynamic
- /// tail, past its end) and whether this frame re-skinned any.
- pose_span: Option<(usize, usize)>,
+ /// Likewise for posed skinned models' meshes (`repose_skinned`): the spans the last new poses took (each mesh's
+ /// first triangle, the first of its previous vertices, how many) and whether this frame re-skinned any.
+ pose_spans: Vec<(usize, usize, usize)>,
pose_reposed: bool,
/// Movable instances moved by the last update (their records' previous-frame rows differ), and whether it was this
/// frame's.
@@ -540,7 +540,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 { pending_emitters: vec![], flipped: vec![], 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, 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, emitters_reweigh: 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 { pending_emitters: vec![], flipped: vec![], 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, 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, emitters_reweigh: false, pose_spans: vec![], 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)
@@ -603,7 +603,7 @@ impl LiveCore {
self.spark_lights = self.sc.tables.emitter_tris.iter().any(|e| e.nominal);
self.inst_moving.clear();
self.prev_span = None;
- self.pose_span = None;
+ self.pose_spans.clear();
self.emitters_moved = false;
self.emitters_reweigh = false;
self.lit_changed = self.frame.max(1);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 5aa6987..f8cb78e 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -203,6 +203,9 @@ pub struct Instance {
/// (`rows_bits`).
pub rows: u32,
pub bits: u32,
+ /// An instance of a mesh that deforms: the first triangle of its previous frame's vertices (the kernel's
+ /// `prev_verts`: its motion is its pose's and its transform's). 0 otherwise.
+ pub prev: u32,
}
/// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose),
@@ -219,14 +222,14 @@ pub struct GpuInstance {
impl Instance {
/// Kernel record with its mesh's first triangle at `first` in the GPU order. (n0.w is left free: a unit's record
- /// takes it for its tree's root, units.rs `unit_record`.)
+ /// takes it for its tree's root, units.rs `unit_record`. n1.w: its bits. n2.w: `prev`, as bits.)
pub fn gpu(&self, first: u32) -> GpuInstance {
let w = self.world;
let nm = glam::Mat3::from_mat4(w).inverse().transpose();
let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];
let nrow = |r: usize, w: f32| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], w];
let bits = f32::from_bits(self.bits | if mirrors(w) { INST_MIRRORED } else { 0 });
- GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, bits), nrow(2, 0.0)], info: [first, self.object, lod_offset(w).to_bits(), self.rows], p: [row(0), row(1), row(2)] }
+ GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, bits), nrow(2, f32::from_bits(self.prev))], info: [first, self.object, lod_offset(w).to_bits(), self.rows], p: [row(0), row(1), row(2)] }
}
/// A triangle's attributes as a flattened triangle has them: the material its row names in place of the
/// section, and no index in it (`rows`: the instance's).
@@ -744,8 +747,12 @@ pub struct Retained {
pub light_nodes: Vec<u32>,
/// Atmosphere sun: its colour comes from the sky bake.
pub sun: Option<u32>,
- /// Posed skinned models' meshes (`Skinned`: a model's proxy names its own, `MeshKind::Skinned`).
+ /// Posed skinned models' meshes (`Skinned`: a model's proxy names its own, `MeshKind::Skinned`). One an edit took
+ /// out again has no mesh (`u32::MAX`) until the next one placed takes its slot.
pub skinned: Vec<Skinned>,
+ /// Posed skinned models an edit can place another of: (uri, nodes) -> one of `skinned` that the build placed, with
+ /// the file's own materials (what the pass skins it from, its mesh's sections and rows are the model's).
+ pub skinned_model: HashMap<(String, Option<Vec<String>>), u32>,
/// Meshes and instanced objects: (geometry, whether by its groups: `by_groups`) -> the shared mesh (objects of the
/// same geometry share its BLAS, whatever their materials: those are their instances' rows). live/edits.rs
/// `edit_geometry` keeps it.
@@ -974,8 +981,9 @@ pub struct Skinned {
pub nodes: Option<Vec<String>>,
/// The pose the mesh holds.
pub animation: desc::Animation,
- /// Per pool triangle of the mesh, in order: its index in the model's triangles, its section and its index in it.
- pub order: Vec<(u32, u32, u32)>,
+ /// Per pool triangle of the mesh, in order: its index in the model's triangles, its section and its index in it
+ /// (the model's: one list for all its placements).
+ pub order: Arc<Vec<(u32, u32, u32)>>,
/// Its object, and its instance.
pub object: u32,
pub instance: u32,
@@ -1536,7 +1544,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mut rigid_parts: HashMap<(String, String), std::rc::Rc<Vec<RigidPart>>> = HashMap::new();
// What the skinning pass reads, by (model, nodes, the primitives mirrored): shared by the model's placements.
let mut skin_sources: Vec<Vec<[skin::SkinCorner; 3]>> = vec![];
- let mut skin_source_of: HashMap<(String, Option<Vec<String>>, Vec<bool>), u32> = HashMap::new();
+ let mut skin_source_of: HashMap<(String, Option<Vec<String>>, Vec<bool>), (u32, Arc<Vec<(u32, u32, u32)>>)> = HashMap::new();
// Flattened instances' triangle ranges.
let mut tri_instances: Vec<(u32, u32, u32)> = vec![];
// Instance colours anywhere: object entries of 4 vec4s, and the kernel's F_TINT.
@@ -1589,7 +1597,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
retained.edits_meshes |= *own_blas || n.driven;
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven || w.movable(*id) }) };
let mine = section_rows(meshes[mesh as usize].sections(&sections), if grouped { &gpu_mats } else { std::slice::from_ref(&mat) }, &materials);
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0 });
rows.extend(mine);
}
}
@@ -1647,7 +1655,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
- instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0 });
rows.extend(mine.iter().copied());
}
}
@@ -1822,7 +1830,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
} else {
rigid.instances.push((part.node, i));
}
- instances.push(Instance { mesh, world: w_n, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ instances.push(Instance { mesh, world: w_n, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0 });
rows.extend(mine);
}
for (p, nn, uv, tg, mat) in &part.rest {
@@ -1867,13 +1875,14 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mirrors = glb.mirrored(Some(a))?;
let file = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };
let skey = (file, nodes.clone(), mirrors.clone());
- let source = match skin_source_of.get(&skey) {
- Some(k) => *k,
+ let (source, tri_order) = match skin_source_of.get(&skey) {
+ Some(s) => s.clone(),
None => {
let corners = glb.skin_source(nodes.as_deref(), Some(a))?;
skin_sources.push(order.iter().map(|&(k, _, _)| corners[k]).collect());
- skin_source_of.insert(skey, skin_sources.len() as u32 - 1);
- skin_sources.len() as u32 - 1
+ let s = (skin_sources.len() as u32 - 1, Arc::new(order.iter().map(|&(k, section, rank)| (k as u32, section, rank)).collect::<Vec<_>>()));
+ skin_source_of.insert(skey, s.clone());
+ s
}
};
let first = pool_tris.len() as u32;
@@ -1887,7 +1896,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
}
- let tri_order: Vec<(u32, u32, u32)> = order.iter().map(|&(k, section, rank)| (k as u32, section, rank)).collect();
// Other poses reach further (a stride, a swing): object bounds a quarter wider each way; one
// the game poses may take any pose (lie down): as far as its size each way.
let pad = if a.nodes.is_empty() { (hi - lo) * 0.25 } else { Vec3A::splat((hi - lo).length()) };
@@ -1901,10 +1909,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
let i = instances.len() as u32;
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0 });
rows.extend(mine);
retained.skinned.push(Skinned { mesh, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order: tri_order, object: *id, instance: i, source, palette_len: glb.palette_len() as u32, mirrors });
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Skinned(retained.skinned.len() as u32 - 1), moves: true }) };
+ if functions.is_empty() {
+ retained.skinned_model.entry((uri.clone(), nodes.clone())).or_insert(retained.skinned.len() as u32 - 1);
+ }
continue;
}
}
@@ -1973,7 +1984,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
retained.proxy(*id).object = Some(oi);
let mine = retained.mesh_rows[&mesh].clone();
- let inst = Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) };
+ let inst = Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0 };
rows.extend(mine);
// Its glass / function triangles as ordinary world-space ones (same object).
for k in im.rest_first..im.rest_first + im.rest_count {
@@ -2809,7 +2820,7 @@ mod instance_tests {
let local = tri_attr(p, n, uv, None, 7);
for (w, mirrored) in [(keeps, false), (keeps * Mat4::from_scale(Vec3::new(-1.0, 1.0, 1.0)), true)] {
assert_eq!(mirrors(w), mirrored);
- let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 };
assert_eq!(inst.gpu(0).n[1][3].to_bits(), if mirrored { INST_MIRRORED } else { 0 }, "the record says whether it mirrors");
let (placed, got, got_colors) = inst.flat(&[p[0].into(), p[1].into(), p[2].into()], &local, Some(colors));
// The world-space triangle: its vertices in the order the build flattens a placement in.
@@ -2844,7 +2855,7 @@ mod instance_tests {
let mats = [opaque, cutout];
let p = [Vec3::ZERO, Vec3::X, Vec3::Y];
let a = |m: u32| tri_attr(p, [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], None, m);
- let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 };
assert_eq!(instance_tri_flags(&inst(true), &a(0), &mats), 0);
assert_eq!(instance_tri_flags(&inst(true), &a(1), &mats), TRI_MASKED);
assert_eq!(instance_tri_flags(&inst(false), &a(1), &mats), TRI_MASKED | TRI_NO_SHADOW);
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index a9237e5..f53363d 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -1355,7 +1355,7 @@ mod tests {
fn record(&self, mesh: usize, world: Mat4, cast: bool) -> GpuInstance {
let (first, _, root, ..) = self.meshes[mesh].unwrap();
- let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 };
unit_record(inst.gpu(first), root, cast)
}
@@ -1969,7 +1969,7 @@ mod tests {
// A built tree is a level short of the bound: two of them joined are at it.
assert!(check_tree(&build_sah(&(0..1 << 12).map(|k| (Vec3A::splat(k as f32), Vec3A::splat(k as f32 + 1.0))).collect::<Vec<_>>(), 12).0, 64, |_, _| Ok(())).unwrap() <= 12);
// The record's word for a placement by a translation alone.
- let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 }.gpu(0), 9, true);
+ let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 }.gpu(0), 9, true);
let shifted = |m: Mat4| rec(m).n[1][3].to_bits() & UNIT_SHIFTED != 0;
assert!(shifted(Mat4::IDENTITY));
assert!(shifted(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))));
diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rs
index b1b0b38..3598bf1 100644
--- a/renderer/src/units_cost.rs
+++ b/renderer/src/units_cost.rs
@@ -409,7 +409,7 @@ fn units_pile() {
let made = (u.kept.builds - was.0, u.kept.changes - was.1, u.kept.refits - was.2);
// At rest: the kernel's buffers as a session would have written them.
for (j, p) in pieces.iter().enumerate() {
- let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0 };
l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri), root as u32, true);
}
let at = u.layout.top_first as usize;
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 1b1caa8..0418faa 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -972,6 +972,12 @@ impl World {
if self.objects.remove(d).is_some_and(|o| !matches!(o.kind, Kind::Group)) && !self.changes.added.remove(d) {
self.changes.removed.insert(*d);
}
+ // What else this batch changed of it goes with it (a pose, a move, its visibility: there is nothing
+ // left to pose, and the renderer would rebuild for an object it cannot find).
+ let c = &mut self.changes;
+ for set in [&mut c.poses, &mut c.moved, &mut c.started, &mut c.shown, &mut c.powers, &mut c.customs, &mut c.instanced] {
+ set.remove(d);
+ }
}
return doomed;
}
@@ -1258,6 +1264,30 @@ mod tests {
assert_eq!(w.objects[&4].position.x, f32::INFINITY, "the transform kept as set");
}
+ /// What a batch changed of an object goes with the object when the same batch removes it in place: its pose, its
+ /// move, its visibility, its power. (The renderer finds nothing to pose, and would rebuild.)
+ #[test]
+ fn an_object_removed_takes_its_other_changes_with_it() {
+ let mut w = World::default();
+ let pose = |time| Some(desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
+ for id in [1, 2] {
+ w.set_object(id, format!("m{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: pose(0.0), functions: vec![] }, true, true).unwrap();
+ }
+ w.take_changes();
+ for id in [1, 2] {
+ w.set_animation(id, pose(0.5)).unwrap();
+ w.set_transform(id, Vec3::new(1.0, 0.0, 0.0), Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_visible(id, false).unwrap();
+ }
+ w.remove(1);
+ let c = w.take_changes();
+ assert!(!c.structural && c.removed.contains(&1), "removed in place");
+ for (what, set) in [("poses", &c.poses), ("moved", &c.moved), ("shown", &c.shown), ("started", &c.started), ("powers", &c.powers), ("customs", &c.customs), ("instanced", &c.instanced)] {
+ assert!(!set.contains(&1), "{what}: nothing of the object removed");
+ }
+ assert!(c.poses.contains(&2) && c.moved.contains(&2) && c.shown.contains(&2), "the other's changes are kept");
+ }
+
/// Density grids: sizes and data are checked; a new grid, another size or another program rebuilds the scene, new
/// data for the same grid is uploaded in place (a grid sent again without data keeps what it had); sources go only
/// to volumes with a grid, 12 finite floats each, at most GRID_MAX_SOURCES pending.