The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Triangles are vertices and indices (#186)
Yujia8447d9c450dc
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 9712919..8da98e5 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2789,6 +2789,55 @@ What it costs: under hardware traversal a frame's GPU time in twelve scenes, altis -1 % to +4 % (Zero Day +4.0, the neon street +3.8, the colour room +3.6, the crowd +2.9, the others under 2, Tokyo-1.0); under software traversal, whose tree walks are loops, the trace of a crowd of 3.3 M triangles is 85.3 -> 90.6 ms(+6 %). The pictures and the suites are the ones before.+**Triangles are vertices and indices (2026-11-22).** Every triangle carried its own three vertices (48 bytes), its+shading attributes (96) and, under hardware traversal, its positions again as the BLAS's input (36). Now the scene+has vertices, a record of 48 bytes each (position and u; normal and v; tangent), and a triangle is three indices+(`renderer/src/indexed.rs`; docs/RUNTIME.md "The scene's triangles"): one layout for both traversals, and the+BLASes are built from the same vertices through the indices. A mesh's vertices are a run of their own: the+skinning pass skins a vertex once (it skinned every corner), the particle passes and the light list's fill write+and read vertices, the previous frame's are kept a vertex, and an edit in place takes a run of vertices with its+triangles. The kernel binds one buffer fewer.+A mesh's triangle has no data of its own besides. Its hit says which section of its mesh it is in (the BLAS's+geometry; under software traversal its tree's leaf); the section's row of its instance has the material, the+instance's record the object and whether the mesh deforms; the light list's record (64 bytes, was 48) has an+emitter's section. A triangle no instance places keeps a row of four words.+Software traversal's trees keep their triangles in their leaves, their own copy as an acceleration structure has+one (48 bytes a triangle: v0, the edges, its section and its index there): a candidate's test read through the+indices and the 48-byte vertices cost its trace 6 % (a crowd standing still, 85 -> 90 ms); from the leaves it is+81 ms. A pass takes a posed mesh's leaves again from its vertices.+On the GPU, data and BLASes together: Tokyo (23 M triangles) 6.4 GB -> 3.9, Zero Day 1.6 GB -> 0.95, a small scene+15 MB -> 7.5. The BLASes themselves are as large as they were.+A frame's GPU time under hardware traversal, twelve scenes alternated twice with the kernel before: the home+showcase +4.2 %, the colour room +2.0, the museum +1.9, the crowd -2.5, Tokyo -1.2, the others within 1 %.+What changes in a picture. A triangle's tangent frame, where its file gives none, is made where it is hit, not at+the build: rounding (offline, software traversal, against the build before: two scenes the same bytes, one with+411 of 921,600 pixels off by 2 steps at most). Under hardware traversal the driver's tree over indexed geometry is+another tree, and a few rays at shared edges meet the other triangle: five scenes at 8 samples differ in 3 to+2,408 pixels, by 3 steps at most but for single samples (8 steps; in one scene one sample, 22 steps over the 11 x 11+pixels the denoiser spreads it to).+A skinned vertex whose position is not finite is at its mesh's origin now; its triangles were left out before.+The build finds the sharing again, 1.2 s on Tokyo (a file's indices are flattened before: historical, a later step).+Tests: indexed.rs's own (sharing; a seam or a crease; a first corner's tangent; a triangle that is not finite); the+build's triangles through their indices against the scene's; the in-place tests read every triangle they check+back through its indices (the light list's emitters with their sections; a skinned mesh's corners, normals, UVs,+tangents and previous positions against the CPU skin, its record's deforming bit, each triangle's section and its+index there); a mesh changed in place to more vertices; a moved card beside another, a drifting particle and a+drifting GPU particle, by their motion vectors; a skinned primitive without normals, by the normal the camera sees;+emitters in a mesh's second section against the same triangles a mesh each (live, and offline for the weight of a+ray that meets one); a first frames' bounce off a mesh's second section and off a particle, which the kernel's+second pass shades; a cutout particle; an emitting particle's two sides beside a light's card;+`material/function-file-tangent` (a file's tangent is the one a function is given); the rasterized first hit+(`THREERT_RASTER`, which had no test and is off in any scene with a mesh since meshes are instances) against the+traced picture.+Fixed on the way: a still mesh that emits, moved for the first time, had the pass that places moved emitters run+over the emitters the move had just made, which the light list did not hold yet (its write landed on the list's+last record); they are made where the mesh stands and the pass leaves them alone.+Mutations: 28 of the first form (20 failed a test there was, 8 none and have their tests above), 27 of this+one (17 and 8; one changes nothing, no deforming instance has its materials' classes remade in place; one is+reached only by a live view without units, `THREERT_UNITS=0`, and has no test) and 17 of the trees' leaves (15+failed a test, one the walk's transcription alone, one none until the emitters' test had three at right angles).+Next: tangents a vertex, interpolated (generated where a file has none); vertices packed to 32 bytes; a file's+indices carried through the build.**A triangle's texel density is the hit's to compute (2026-11-22).** Every triangle carried a constant for its mipchoice, half the log of its UV area over its area, made when the scene was built; an instance added an offset fordiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 5c8a296..03cb911 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1459,8 +1459,8 @@ too is an override, from F_TINT).`cache_acc_add`, `refl_store`, ...), declared once in each layout's block, so a layout is its declarations andnothing else of the kernel knows which it is in.- The loop guard's count goes into every loop by a pass over the variant's syntax tree (gpu.rs `guard_loops`).-- What more than one shader reads or writes is declared once, in `records.wgsl`: a triangle's attributes- (`TriAttr`), a sample of the trace (`Pixel`), the light tiles' constants. The file is part of the kernel, of the+- What more than one shader reads or writes is declared once, in `records.wgsl`: a triangle's attributes as a hit+ has them (`TriAttr`), a sample of the trace (`Pixel`), the light tiles' constants. The file is part of the kernel, of theparticle passes and of the live passes (build.rs reads it with live.wgsl). The particle passes take the objecttable's stride as a pipeline constant, as the kernel does (until 2026-11-15 gpu.rs rewrote a line of their text).- The kernel's bind group layouts are written in one place (gpu.rs `kernel_layout_entries`), and a test holds them@@ -1492,7 +1492,8 @@ The kernel's read-only scene data other than triangles is two storage buffers, ecopies, so a light sample reads no placement; what moves an emitter after the load is copied again on the GPU,`emitter_fill.wgsl`).- `words` (binding 5), 32-bit words (`Stream`): the environment's CDF, the procedural geometry's data, the vertex- colours (`env_cdf_at`, `pword`, `vcolor_word`). Integers are read as integers, not through a float's bits.+ colours, the instances' rows, and the triangles' indices and rows ("The scene's triangles" below) (`env_cdf_at`,+ `pword`, `vcolor_word`, `tri_indices`, `tri_row`). Integers are read as integers, not through a float's bits.`Params::table_first` and `word_first` name each section's first element and are written with the parameters(`Uploaded::place`). What a scene has more of is another section, not another binding.@@ -1525,6 +1526,50 @@ The kernel's read-only scene data other than triangles is two storage buffers, e(Hardware traversal no longer binds software traversal's trees, a placeholder there; the light tiles' lists tookthe binding.)+## The scene's triangles++Vertices and indices, one layout for hardware and software traversal (`renderer/src/indexed.rs`):+- **Vertices.** `vertices` (binding 1): a record of 48 bytes a vertex, (position, u), (normal, v), (tangent, hand;+ zeros: none). The BLASes are built from this buffer too (stride 48).+- **Triangles.** Three indices each, a section of `words` (`Stream::Indices`): what a hit reads, and the BLASes'+ index buffer. A mesh's indices count from the mesh's first vertex, which its instances' records carry+ (`info.z`); a world-space triangle's count from 0.+- **A mesh's triangle has nothing else of its own.** Which section of its mesh it is in, its hit says (`Hit.part`):+ the geometry of the BLAS it was hit in, or under software traversal its tree's leaf. Its instance's row for+ the section has the material and where the section's triangles and emitters start; its instance's record has+ its object and whether its mesh deforms (`INST_DEFORMS`). A light sample is told its emitter's section by the+ light list's record (64 bytes). The record a pixel is left to `finish` by has 16 bits for it (`MESH_SECTIONS`).+- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (a light's card, a particle's, a+ flattened scene's) has one: its material, its object, its flags, its emitter + 1. They are all the GPU holds: the+ world-space triangles', then the translucent particles'.+- **Software traversal's leaves** (`leaves`, binding 2; `indexed::Leaf`). A tree keeps its triangles itself, as an+ acceleration structure does: 48 bytes each, in the triangles' order, (v0, id), (v1 - v0, id), (v2 - v0, -). A+ candidate's test reads nothing else. The ids: a world-space triangle's flags; a mesh's section, and its index in+ the section (a tree has a mesh's triangles in its own order). Written at the build and where an edit places a+ mesh; after the skinning pass a pass takes a posed mesh's again from its vertices (`leaf_gather.wgsl`).+- **A hit reads** its triangle's indices and its three vertices' records (`tri_data(triangle, instance, part)`).+- **What shares.** Corners equal bit for bit in position, normal and UV are one vertex: the still world-space+ triangles among themselves, each mesh within itself, a skinned mesh by its model's corners. Triangles the CPU or+ a pass writes whole (those that move in world space, particles) keep three vertices each.+- **Tangents.** A triangle's frame is its first vertex's tangent where its file has one (a first corner never+ shares a vertex with a triangle of another tangent), else made where it is hit, from its edges, its UVs and its+ first normal (`hit_tangent`), and placed by its instance there.+- **Motion.** `prev_verts` (binding 6): the vertices that move as they were the previous frame, whole records (a+ copy on the GPU has no stride; the kernel reads their positions): the moving world-space triangles' first, then+ the deforming meshes', each where its record says (`n2.w`).+- **Edits.** A mesh an edit places takes a run of triangles and a run of vertices (`EditState::tris`, `verts`);+ both rooms grow by a copy on the GPU. A mesh changed in place keeps its run where the new vertices fit.+- **Bytes.** A triangle was 144 bytes for the kernel (48 its vertices, 96 its attributes) and 36 more as the BLAS's+ input; it is its three indices, 12, and its share of the vertices' 48 each. Vertices a triangle as measured:+ Tokyo 1.17, Zero Day 1.03, a crowd of skinned walkers 0.98, small scenes of smooth models 0.5 to 0.7, a voxel+ level's meshes 1.88 (a face's four corners are no other face's). With the BLASes, on the GPU: Tokyo 6.4 GB ->+ 3.9, Zero Day 1.6 -> 0.95.+- The build still flattens a file's indexed geometry and finds the sharing again (1.2 s on Tokyo's 23 M+ triangles): carrying a file's indices through is a later step.+- Under hardware traversal the kernel binds one buffer fewer than it did (a triangle's attributes were a second+ one): the translucency pass's pipeline, which was at Metal's 29 buffers a stage, is at 28. Under software+ traversal the leaves take that place: a browser's merged layout uses all eight of its storage buffers, as it did.+## Random numbers`shaders/sample.wgsl`: shuffled, Owen-scrambled Sobol (Burley 2020; Cycles' Sobol-Burley), four dimensions padded by@@ -1896,7 +1941,7 @@ on the device", and differs where it says so.|---|---|---|| `tables` (4) and, with the views, `materials` (12), `lights` (13), `emitters` (14) | megabytes in a lit scene | storage: the device drew right with materials, lights and emitters as storage buffers of their own (bindings 4 to 6, before #89) and reads them right from `tables` whole; not as the views (above) || `words` (5): the environment's CDF, the procedural geometry's data, vertex colours | megabytes | storage; the environment's light sampling is off on Android, below |- | `tri_verts` (1), `attrs` (2), `nodes` (3), `prev_verts` (6) | per triangle | storage (megabytes) |+ | `vertices` (1), `leaves` (2), `nodes` (3), `prev_verts` (6) | per vertex, per triangle, per node | storage (megabytes) || `accum` (11), group 1 (radiance cache, the trace's outputs, `finish`'s records, the loop guard's count) | per pixel, per cache entry | written by the kernel: cannot be uniform || group 2, the translucency pass (`timg`, `vpts`, `vcount`, `tlow`) | per pixel | written by the pass || the particle passes' `systems`, `spawns`, `grid`; the grid programs' `srcs` | small, read-only | storage: other shaders, of eleven bindings at most and no acceleration structure; not known to misread (the fix on the device left them alone) |diff --git a/renderer/shaders/emitter_fill.wgsl b/renderer/shaders/emitter_fill.wgslindex e429ebd..412e5d2 100644--- a/renderer/shaders/emitter_fill.wgsl+++ b/renderer/shaders/emitter_fill.wgsl@@ -4,8 +4,12 @@// the instances that moved).struct Run { first: u32, count: u32 };@group(0) @binding(0) var<storage, read> runs: array<Run>;-@group(0) @binding(1) var<storage, read> verts: array<vec4<f32>>;-// Three vec4s an emitter: (v0, its triangle), (e1, its instance), (e2, its path code). The words stay.+// The scene's vertices (three rows each: the first has the position), and its triangles' indices (three a triangle,+// counted from the first vertex of the mesh an instance places; a world-space triangle's from 0).+@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>;+@group(0) @binding(4) var<storage, read> indices: array<u32>;+// Four vec4s an emitter: (v0, its triangle), (e1, its instance), (e2, its path code), (its section, -). The words+// stay.@group(0) @binding(2) var<storage, read_write> list: array<vec4<u32>>;// The instances' records (scene.rs `GpuInstance`: the first three vec4s are the rows of the instance's matrix). Read// only: they are a section of the buffer the list is one of, and a buffer is not bound to read and to write at once.@@ -17,11 +21,15 @@ const NO_INST: u32 = 0xffffffffu;fn fill(@builtin(global_invocation_id) id: vec3<u32>) {let run = runs[id.y];if (id.x >= run.count) { return; }- let r = (run.first + id.x) * 3u;+ let r = (run.first + id.x) * 4u;let t = list[r].w * 3u;- var rows = array<vec3<f32>, 3>(verts[t].xyz, verts[t + 1u].xyz, verts[t + 2u].xyz);- // An instance's emitter: its mesh's triangle (v0, e1, e2 in model space) placed by the instance.+ // An instance's emitter: its mesh's triangle (v0, e1, e2 in model space) placed by the instance. (The record's+ // seventh vec4: its mesh's first triangle, its object, its mesh's first vertex, its rows.)let inst = list[r + 1u].w;+ var base = 0u;+ if (inst != NO_INST) { base = bitcast<u32>(instances[inst * INSTANCE_VEC4 + 6u].z); }+ let v0 = vertices[(base + indices[t]) * 3u].xyz;+ var rows = array<vec3<f32>, 3>(v0, vertices[(base + indices[t + 1u]) * 3u].xyz - v0, vertices[(base + indices[t + 2u]) * 3u].xyz - v0);if (inst != NO_INST) {let m0 = instances[inst * INSTANCE_VEC4];let m1 = instances[inst * INSTANCE_VEC4 + 1u];diff --git a/renderer/shaders/gpu_particles.wgsl b/renderer/shaders/gpu_particles.wgslindex d6f1403..3fbc113 100644--- a/renderer/shaders/gpu_particles.wgsl+++ b/renderer/shaders/gpu_particles.wgsl@@ -59,12 +59,12 @@ struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, d: vec4<f32>, e: vec4<@group(0) @binding(0) var<uniform> PPS: PP;@group(0) @binding(1) var<storage, read> systems: array<System>;-@group(0) @binding(2) var<storage, read_write> verts: array<vec4<f32>>;+// The scene's vertices (pathtrace.wgsl `vertices`: three rows each) and those that move as they were the previous+// frame (their positions are read).+@group(0) @binding(2) var<storage, read_write> vertices: array<vec4<f32>>;@group(0) @binding(3) var<storage, read_write> prev_verts: array<vec4<f32>>;-@group(0) @binding(4) var<storage, read_write> blas: array<f32>;@group(0) @binding(5) var<storage, read_write> objects: array<vec4<f32>>;-@group(0) @binding(6) var<storage, read_write> attrs: array<TriAttr>;-// This pass's last positions of its triangles (prev_verts' indexing; a repose re-uploads the dynamic tail).+// This pass's last positions of its vertices (the previous positions' indexing; a repose re-uploads the dynamic tail).@group(0) @binding(7) var<storage, read_write> last: array<vec4<f32>>;// Per particle: (pos, age), (vel, life), color, (size, alive, -, -); from each system's first state.@group(0) @binding(8) var<storage, read_write> state: array<vec4<f32>>;@@ -139,32 +139,19 @@ fn collide(s_in: PState, dt: f32, flags: f32, d: vec4<f32>) -> PState {return s;}-// One triangle of a quad (particles.wgsl `put_tri`, opaque particles only).-fn put_tri(t: u32, dyn_first: u32, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>) {- let flags = verts[t * 3u].w;- let now = array<vec4<f32>, 3>(vec4<f32>(a, flags), vec4<f32>(b - a, 0.0), vec4<f32>(c - a, 0.0));- let first = PPS.env.x > 0.5;- for (var k = 0u; k < 3u; k++) {- verts[t * 3u + k] = now[k];- let j = (t - dyn_first) * 3u + k;- prev_verts[j] = select(last[j], now[k], first);- last[j] = now[k];- }- attrs[t].n0.x = n.x;- attrs[t].n0.y = n.y;- attrs[t].n0.z = n.z;- attrs[t].n1.x = n.x;- attrs[t].n1.y = n.y;- attrs[t].n1.z = n.z;- attrs[t].n2.x = n.x;- attrs[t].n2.y = n.y;- attrs[t].n2.z = n.z;- attrs[t].t = vec4<f32>(tg, 1.0);+// One triangle of a quad, from its first vertex `v` on (particles.wgsl `put_tri`, opaque particles only).+fn put_tri(v: u32, dyn_first: u32, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>) {let corners = array<vec3<f32>, 3>(a, b, c);+ let first = PPS.env.x > 0.5;for (var k = 0u; k < 3u; k++) {- for (var j = 0u; j < 3u; j++) {- blas[t * 9u + k * 3u + j] = corners[k][j];- }+ let i = (v + k) * 3u;+ vertices[i] = vec4<f32>(corners[k], vertices[i].w);+ vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);+ vertices[i + 2u] = vec4<f32>(tg, 1.0);+ let j = v + k - dyn_first;+ let now = vec4<f32>(corners[k], 0.0);+ prev_verts[j * 3u] = select(last[j], now, first);+ last[j] = now;}}@@ -237,9 +224,9 @@ fn gpu_particles(@builtin(global_invocation_id) gid: vec3<u32>) {let area = length(uxv);let n = select(to_cam, uxv / area, area > 1e-12);let tg = select(vec3<f32>(1.0, 0.0, 0.0), normalize(u), dot(u, u) > 1e-24);- let t = sys.a.x + 2u * k;+ let t = sys.a.x + 6u * k;put_tri(t, sys.b.y, c00, c10, c11, n, tg);- put_tri(t + 1u, sys.b.y, c00, c11, c01, n, tg);+ put_tri(t + 3u, sys.b.y, c00, c11, c01, n, tg);let oi = (sys.a.z + k) * OBJECT_STRIDE;objects[oi] = vec4<f32>(s.pos, objects[oi].w);objects[oi + 1u] = vec4<f32>(vec3<f32>(4.0 * half), objects[oi + 1u].w);diff --git a/renderer/shaders/leaf_gather.wgsl b/renderer/shaders/leaf_gather.wgslnew file mode 100644index 0000000..05ec79a--- /dev/null+++ b/renderer/shaders/leaf_gather.wgsl@@ -0,0 +1,52 @@+// The leaf-gather pass (software traversal): the trees' leaves of meshes whose vertices a pass has just written (a+// new pose: skin.wgsl) take their triangles again from those vertices, through the triangles' indices: v0, e1, e2+// (pathtrace.wgsl `leaves`; indexed.rs `Leaf`). A leaf's ids stay. One invocation a triangle; a workgroup is 64+// triangles of one mesh (`blocks`: the frame's work, the meshes with a new pose alone).++struct Params {+ // x: the frame's blocks; y: the first word of the triangles' indices in `words`.+ n: vec4<u32>,+}++// A mesh: its first triangle among the scene's and how many, its first vertex.+struct Job {+ first: u32,+ count: u32,+ vertex: u32,+ spare: u32,+}++// Workgroups a row of the dispatch (a dimension holds 65,535).+const ROW: u32 = 32768u;++@group(0) @binding(0) var<uniform> PP: Params;+// (mesh, its first triangle of the block)+@group(0) @binding(1) var<storage, read> blocks: array<vec2<u32>>;+@group(0) @binding(2) var<storage, read> jobs: array<Job>;+// The scene's vertices, three rows each, the first (position, u); the words' heap, the triangles' indices in it.+@group(0) @binding(3) var<storage, read> vertices: array<vec4<f32>>;+@group(0) @binding(4) var<storage, read> words: array<u32>;+@group(0) @binding(5) var<storage, read_write> leaves: array<vec4<f32>>;++@compute @workgroup_size(64)+fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) li: u32) {+ let b = wg.x + wg.y * ROW;+ if b >= PP.n.x {+ return;+ }+ let block = blocks[b];+ let job = jobs[block.x];+ let local = block.y + li;+ if local >= job.count {+ return;+ }+ let t = job.first + local;+ let w = PP.n.y + t * 3u;+ let p0 = vertices[(job.vertex + words[w]) * 3u].xyz;+ let p1 = vertices[(job.vertex + words[w + 1u]) * 3u].xyz;+ let p2 = vertices[(job.vertex + words[w + 2u]) * 3u].xyz;+ let k = t * 3u;+ leaves[k] = vec4<f32>(p0, leaves[k].w);+ leaves[k + 1u] = vec4<f32>(p1 - p0, leaves[k + 1u].w);+ leaves[k + 2u] = vec4<f32>(p2 - p0, 0.0);+}diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgslindex 27db7b9..182d963 100644--- a/renderer/shaders/particles.wgsl+++ b/renderer/shaders/particles.wgsl@@ -41,23 +41,20 @@ struct PP {// (`TriAttr`: records.wgsl.)-// a: (first triangle in the GPU order, count, first object, function); b: (seed, first dynamic triangle, translucent-// (1: its triangles are the translucency pass's, `tblas` from the first translucent triangle), first translucent-// triangle); c: the node's pivot, w: 1 collapse every particle (the system was just hidden), 2 its first run since it+// a: (its first vertex (six a particle), count, first object, function); b: (seed, the first vertex that moves,+// translucent (1: its triangles are the translucency pass's), -); c: the node's pivot, w: 1 collapse every particle (the system was just hidden), 2 its first run since it// was shown (no last frame: motion vectors 0) (gpu.rs `set_particles_hidden`); p: parameters; d: the node's customData.struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, p: array<vec4<f32>, 8>, d: vec4<f32> };@group(0) @binding(0) var<uniform> PPS: PP;@group(0) @binding(1) var<storage, read> systems: array<System>;-@group(0) @binding(2) var<storage, read_write> verts: array<vec4<f32>>;+// The scene's vertices (pathtrace.wgsl `vertices`: three rows each) and those that move as they were the previous+// frame (their positions are read).+@group(0) @binding(2) var<storage, read_write> vertices: array<vec4<f32>>;@group(0) @binding(3) var<storage, read_write> prev_verts: array<vec4<f32>>;-@group(0) @binding(4) var<storage, read_write> blas: array<f32>;@group(0) @binding(5) var<storage, read_write> objects: array<vec4<f32>>;-@group(0) @binding(6) var<storage, read_write> attrs: array<TriAttr>;-// This pass's last positions of the dynamic tail's particle triangles (prev_verts' indexing).+// This pass's last positions of the dynamic tail's particle vertices (the previous positions' indexing).@group(0) @binding(7) var<storage, read_write> last: array<vec4<f32>>;-// The translucent particles' BLAS input (gpu.rs `Translucent`).-@group(0) @binding(8) var<storage, read_write> tblas: array<f32>;// vec4s an object in `objects` (scene.rs `object_stride`: 4 in a scene with instance colours), the pipeline's constant.override OBJECT_STRIDE: u32 = 3u;@@ -74,40 +71,23 @@ fn unit(h: u32) -> f32 { return f32(h >> 8u) * (1.0 / 16777216.0); }fn particle_function(f: u32, i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(i.pivot, vec3<f32>(0.0), vec3<f32>(0.0), false, vec4<f32>(0.0)); }// @particle-functions-end-// One triangle of a quad: positions, last frame's as prev_verts, shading normal / tangent (as scene.rs tri_attr),-// BLAS input.-// Translucent triangles (`trans` = first translucent triangle) have no motion vectors (the pass draws them over the-// image each frame) and their own BLAS input.-fn put_tri(t: u32, dyn_first: u32, trans: u32, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>, first: bool) {- let flags = verts[t * 3u].w;- let now = array<vec4<f32>, 3>(vec4<f32>(a, flags), vec4<f32>(b - a, 0.0), vec4<f32>(c - a, 0.0));- for (var k = 0u; k < 3u; k++) {- verts[t * 3u + k] = now[k];- if (trans == 0xffffffffu) {- let j = (t - dyn_first) * 3u + k;- prev_verts[j] = select(last[j], now[k], first);- last[j] = now[k];- }- }- // Component writes: the w's hold the uv corners (and x.y the object), left as built.- attrs[t].n0.x = n.x;- attrs[t].n0.y = n.y;- attrs[t].n0.z = n.z;- attrs[t].n1.x = n.x;- attrs[t].n1.y = n.y;- attrs[t].n1.z = n.z;- attrs[t].n2.x = n.x;- attrs[t].n2.y = n.y;- attrs[t].n2.z = n.z;- attrs[t].t = vec4<f32>(tg, 1.0);+// One triangle of a quad, from its first vertex `v` on (three vertices a triangle): positions, the last frame's as+// the previous positions, shading normal and tangent (as scene.rs tri_attr). The dynamic groups' BLAS is built from+// the positions, the translucent triangles' own too. Translucent triangles (`trans`) have no motion vectors (the pass+// draws them over the image each frame).+fn put_tri(v: u32, dyn_first: u32, trans: bool, a: vec3<f32>, b: vec3<f32>, c: vec3<f32>, n: vec3<f32>, tg: vec3<f32>, first: bool) {let corners = array<vec3<f32>, 3>(a, b, c);for (var k = 0u; k < 3u; k++) {- for (var j = 0u; j < 3u; j++) {- if (trans == 0xffffffffu) {- blas[t * 9u + k * 3u + j] = corners[k][j];- } else {- tblas[(t - trans) * 9u + k * 3u + j] = corners[k][j];- }+ let i = (v + k) * 3u;+ // (The w's hold the uv, left as built.)+ vertices[i] = vec4<f32>(corners[k], vertices[i].w);+ vertices[i + 1u] = vec4<f32>(n, vertices[i + 1u].w);+ vertices[i + 2u] = vec4<f32>(tg, 1.0);+ if (!trans) {+ let j = v + k - dyn_first;+ let now = vec4<f32>(corners[k], 0.0);+ prev_verts[j * 3u] = select(last[j], now, first);+ last[j] = now;}}}@@ -145,11 +125,11 @@ fn particles(@builtin(global_invocation_id) gid: vec3<u32>) {let area = length(uxv);let n = select(vec3<f32>(0.0, 0.0, 1.0), uxv / area, area > 1e-12);let tg = select(vec3<f32>(1.0, 0.0, 0.0), normalize(o.u), dot(o.u, o.u) > 1e-24);- let t = s.a.x + 2u * k;- let trans = select(0xffffffffu, s.b.w, s.b.z == 1u);+ let t = s.a.x + 6u * k;+ let trans = s.b.z == 1u;let first = PPS.env.z > 0.5 || s.c.w > 1.5;put_tri(t, s.b.y, trans, c00, c10, c11, n, tg, first);- put_tri(t + 1u, s.b.y, trans, c00, c11, c01, n, tg, first);+ put_tri(t + 3u, s.b.y, trans, c00, c11, c01, n, tg, first);let oi = (s.a.z + k) * OBJECT_STRIDE;objects[oi] = vec4<f32>(o.center, objects[oi].w);objects[oi + 1u] = vec4<f32>(2.0 * (abs(o.u) + abs(o.v)), objects[oi + 1u].w);diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 197d9a7..c1b9486 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -126,7 +126,7 @@ struct Params {ltile2: vec4<u32>, // the traced size they were built at, -, -lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, uptable_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, emitter triangles- word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows+ word_first: array<vec4<u32>, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rowslive_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists};@@ -142,10 +142,17 @@ struct Material {struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>, x: vec4<f32> };@group(0) @binding(0) var<uniform> P: Params;-@group(0) @binding(1) var<storage, read> tri_verts: array<vec4<f32>>;-@group(0) @binding(2) var<storage, read> attrs: array<TriAttr>;-// (Software traversal's trees: hardware traversal has no binding for them.)+// The scene's vertices (indexed.rs `Vertex`), each kept once, a record of three rows: (position, u), (normal, v),+// (tangent, hand; zeros: it has none). A triangle is three of them, by its indices in `words` (`tri_data`).+@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>;+const VERTEX_VEC4: u32 = 3u;+// Software traversal's trees (hardware traversal has no binding for them): their nodes, and their leaves'+// triangles (indexed.rs `Leaf`), the trees' own copy, three vec4s a triangle in the triangles' order: (v0, id),+// (e1, id), (e2, -). A candidate's test reads nothing else. The ids: a world-space triangle's flags (TRI_*); a+// mesh's section, and its index in the section.+@if(!hwrt) @group(0) @binding(2) var<storage, read> leaves: array<vec4<f32>>;@if(!hwrt) @group(0) @binding(3) var<storage, read> nodes: array<Node>;+@if(!hwrt) fn leaf_id(ti: u32, k: u32) -> u32 { return bitcast<u32>(leaves[ti * 3u + k].w); }@group(0) @binding(7) var textures: texture_2d_array<f32>;@group(0) @binding(8) var samp: sampler;@group(0) @binding(9) var env_tex: texture_2d<f32>;@@ -157,7 +164,8 @@ struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>,// (The CDF is the buffer's first section: from word 0, no offset to read.)fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }@group(0) @binding(11) var<storage, read_write> accum: array<Pixel>;-// The dynamic triangles' vertices (kernel layout, from triangle P.group_first[1].x on) as they were the previous frame.+// The vertices that move as they were the previous frame (their records: the positions are read), from the first of+// them (`P.word_first[1].z`) on.@group(0) @binding(6) var<storage, read> prev_verts: array<vec4<f32>>;// Instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, a spare word, its rows' first).struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, info: vec4<u32>, p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32> };@@ -192,16 +200,17 @@ fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i)// An emitter's triangle (lib.rs `GpuEmitterTri`): in world space, the light list's own copy, so a light sample reads// no placement (what moves it is copied again: emitter_fill.wgsl); `tri`: its triangle in the triangles' table// (attributes: `emitter_attrs`), `inst`: the instance that places it (NO_INST: none), `code`: the light tree's path-// code (0: not one of the tree's), EMITTER_MOVES if it moves.-struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32 };-const EMITTER_TRI_VEC4: u32 = 3u;+// code (0: not one of the tree's), EMITTER_MOVES if it moves; `part`: as a hit's (`Hit.part`): its section of its+// instance's mesh, or its own row. Four vec4s, a cache line.+struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32, part: u32 };+const EMITTER_TRI_VEC4: u32 = 4u;const EMITTER_MOVES: u32 = 0x80000000u;fn emitter_tri_at(i: u32) -> EmitterTri {let b = P.table_first[2].w + i * EMITTER_TRI_VEC4;let r0 = tables[b];let r1 = tables[b + 1u];let r2 = tables[b + 2u];- return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w);+ return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w, tables[b + 3u].x);}// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,// `object_at`, `instance_at` and `medium_at` in every layout.@@ -273,7 +282,7 @@ fn emitter_tri_at(i: u32) -> EmitterTri {// Density grids (gpu.rs F_GRID, `GridsGpu`): field A of every grid, stacked along z; one cell in scenes without.@group(0) @binding(10) var grid_tex: texture_3d<f32>;// Vertex colours (three.js `vertexColors`; gpu.rs F_VCOLOR): three sRGB 8-bit colours per triangle.-fn vcolor_word(k: u32) -> u32 { return words[P.word_first.z + k]; }+fn vcolor_word(k: u32) -> u32 { return words[P.word_first[0].z + k]; }fn vcolor(t: u32, u: f32, v: f32) -> vec3<f32> {let c0 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u)).rgb);let c1 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u + 1u)).rgb);@@ -295,16 +304,17 @@ fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {return vec4<f32>(x.x, bitcast<f32>(info.y), x.z, x.w);}// An instance's rows (scene.rs `Row`): four words a section of its mesh, from the record's info.w on. The material-// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). A triangle of-// a mesh holds its section in its attributes' uv.w and its index in the section in x.w; a record's n1.w says whether-// a row of it is a cutout's or glass.+// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). Which section+// a triangle of a mesh is in, its hit says (`Hit.part`); a record's n1.w says whether a row of it is a cutout's or+// glass, and whether its mesh deforms.const INST_CUTOUT: u32 = 16u;const INST_GLASS: u32 = 32u;+const INST_DEFORMS: u32 = 64u;const ROW_MATERIAL: u32 = 0xffffffu;const ROW_CUTOUT: u32 = 0x1000000u;const ROW_GLASS: u32 = 0x2000000u;const NO_EMITTER: u32 = 0xffffffffu;-fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first.w + (first + section) * 4u + k]; }+fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first[0].w + (first + section) * 4u + k]; }// The material of a triangle, given its attributes and the instance that places it (NO_INST: none). Every read of a// hit's material goes through here: where the material is kept is this function's alone. In the row of the triangle's@@ -317,13 +327,99 @@ fn material_of(a: TriAttr, inst: u32) -> u32 {// The material a triangle itself holds: one that no instance places.fn triangle_material(a: TriAttr) -> u32 { return bitcast<u32>(a.uv.w); }-// A model-space triangle's shading attributes placed by instance r (scene::instance_attr).+// A triangle's three vertices (indexed.rs), counted from its mesh's first (a world-space triangle's from 0): what a+// hit and a candidate's test read, and what the acceleration structures are built from.+fn tri_indices(ti: u32) -> vec3<u32> {+ let k = P.word_first[1].x + ti * 3u;+ return vec3<u32>(words[k], words[k + 1u], words[k + 2u]);+}+// The row of a triangle no instance places (a light's card, a particle's, a scene's that is flattened), four words:+// its material, its object, its flags (TRI_*), its emitter entry + 1. A mesh's triangle has none: which section of+// its mesh it is in is its hit's to say (`Hit.part`), and the rest is its instance's.+fn tri_row(row: u32) -> vec4<u32> {+ let k = P.word_first[1].y + row * 4u;+ return vec4<u32>(words[k], words[k + 1u], words[k + 2u], words[k + 3u]);+}+fn tri_flags(row: u32) -> u32 { return words[P.word_first[1].y + row * 4u + 2u]; }+// Whether an emitter is a rect light's card, which lights one side. (A card is in world space: its row has its+// material. No mesh is drawn with a card's.)+fn emitter_is_card(em: EmitterTri) -> bool {+ if (has(F_INST) && em.inst != NO_INST) { return false; }+ return material_at(tri_row(em.part).x).tex1.z == MAT_EMITTER_CARD;+}+// A triangle read whole: its first corner and its edges, and its attributes as a hit has them: normals and UVs a+// corner; `uv.w`: its section (an instance's: `part`) or its material; `t`: its first vertex's tangent, zeros where+// that has none (`hit_tangent`); `x`: -, its object (an instance's: where its attributes are placed, `inst_x`), -,+// its emitter entry + 1. `inst`, `part`: as a hit has them (`Hit`): with an instance its vertices count from the+// mesh's first and `part` is its section; without, `part` is its row.+struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32> }+fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {+ var base = 0u;+ var row = vec4<u32>(part, 0u, 0u, 0u);+ if (has(F_INST) && inst != NO_INST) { base = instance_at(inst).info.z; } else { row = tri_row(part); }+ let i = (tri_indices(ti) + vec3<u32>(base)) * VERTEX_VEC4;+ let p0 = vertices[i.x];+ let p1 = vertices[i.y];+ let p2 = vertices[i.z];+ var n0 = vertices[i.x + 1u];+ var n1 = vertices[i.y + 1u];+ var n2 = vertices[i.z + 1u];+ let e1 = p1.xyz - p0.xyz;+ let e2 = p2.xyz - p0.xyz;+ // A skinned mesh whose model has no normals has zeros: the triangle's own, as it is posed.+ if (has(F_DEFORM) && all(n0.xyz == vec3<f32>(0.0))) {+ let f = cross(e1, e2);+ let l = length(f);+ var flat = vec3<f32>(0.0);+ if (l > 0.0 && (bitcast<u32>(l) & 0x7f800000u) != 0x7f800000u) { flat = f / l; }+ n0 = vec4<f32>(flat, n0.w);+ n1 = vec4<f32>(flat, n1.w);+ n2 = vec4<f32>(flat, n2.w);+ }+ return TriData(TriAttr(vec4<f32>(n0.xyz, p0.w), vec4<f32>(n1.xyz, n0.w), vec4<f32>(n2.xyz, p1.w), vec4<f32>(n1.w, p2.w, n2.w, bitcast<f32>(row.x)), vertices[i.x + 2u],+ vec4<f32>(0.0, bitcast<f32>(row.y), 0.0, bitcast<f32>(row.w))), p0.xyz, e1, e2);+}+// A triangle's tangent frame in the world: (tangent, hand). Its first vertex's where that has one (a file's, a+// particle's); else the triangle's own, from its edges, its UVs and its first normal as `td` has them (its model's+// space). Then placed by its instance, if one places it. Asked where a frame is read: a normal map, a function.+fn hit_tangent(td: TriData, inst: u32) -> vec4<f32> {+ var t = td.a.t;+ if (all(t.xyz == vec3<f32>(0.0))) {+ let a = td.a;+ let uv0 = vec2<f32>(a.n0.w, a.n1.w);+ let d1 = vec2<f32>(a.n2.w, a.uv.x) - uv0;+ let d2 = a.uv.yz - uv0;+ let det = d1.x * d2.y - d2.x * d1.y;+ if (abs(det) < 1e-12) {+ var any = vec3<f32>(0.0, 1.0, 0.0);+ if (abs(a.n0.x) < 0.9) { any = vec3<f32>(1.0, 0.0, 0.0); }+ t = vec4<f32>(normalize(cross(a.n0.xyz, any)), 1.0);+ } else {+ let r = 1.0 / det;+ let tu = (td.e1 * d2.y - td.e2 * d1.y) * r;+ let l = length(tu);+ var tn = vec3<f32>(0.0);+ if (l > 0.0 && (bitcast<u32>(l) & 0x7f800000u) != 0x7f800000u) { tn = tu / l; }+ let bt = (td.e2 * d1.x - td.e1 * d2.x) * r;+ var hand = -1.0;+ if (dot(cross(a.n0.xyz, tn), bt) < 0.0) { hand = 1.0; }+ t = vec4<f32>(tn, hand);+ }+ }+ if (has(F_INST) && inst != NO_INST) {+ let r = instance_at(inst);+ t = vec4<f32>(normalize(inst_vec(r, t.xyz)), t.w * inst_sign(r));+ }+ return t;+}++// A model-space triangle's shading attributes placed by instance r (scene::instance_attr). (Not its tangent, which+// is placed where it is read: `hit_tangent`.)fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {var b = a;b.n0 = inst_normal(r, a.n0);b.n1 = inst_normal(r, a.n1);b.n2 = inst_normal(r, a.n2);- b.t = vec4<f32>(normalize(inst_vec(r, a.t.xyz)), a.t.w * inst_sign(r));b.x = inst_x(r.info, a.x);return b;}@@ -524,7 +620,10 @@ fn emitter_pmf(ei: u32, em: EmitterTri, x: vec3<f32>, n: vec3<f32>) -> f32 {// Intersection// `inst`: the model instance whose model-space triangle `tri` is (F_INST), NO_INST for world-space triangles.-struct Hit { t: f32, tri: u32, u: f32, v: f32, inst: u32 };+// `part`: with an instance, the section of its mesh the triangle is in (the acceleration structure's geometry; a+// unit's tree's leaf's id): its instance's row for it has its material. Without one, the triangle's row+// (`tri_row`): `tri` itself.+struct Hit { t: f32, tri: u32, u: f32, v: f32, inst: u32, part: u32 };const NO_INST: u32 = 0xffffffffu;// ------------------------------------------------------------------------------------------------@@ -548,7 +647,7 @@ struct GOut { t: f32, normal: vec3<f32>, material: u32, attr: vec2<f32> };// `pword`: the renderer's own reads (headers, boxes, materials). `gdata`: the geometry function's, of its object's data// only, word i.data .. i.data + i.count - 1; anything else reads 0. The kernel is compiled without bounds checks (its// indices come from the scene build) and the function is game code: it must not reach past its data.-fn pword(k: u32) -> u32 { return words[P.word_first.y + k]; }+fn pword(k: u32) -> u32 { return words[P.word_first[0].y + k]; }fn pwordf(k: u32) -> f32 { return bitcast<f32>(pword(k)); }var<private> gdata_first: u32;var<private> gdata_count: u32;@@ -609,7 +708,7 @@ fn proc_hit(t: f32, g: GOut, prim: u32, rec: u32) -> Hit {// Each half rounded to its upper 15 bits (a carry into the exponent is the right rounding; 0x7fff stays put).let ha = min(((a & 0xffffu) + 1u) >> 1u, 0x7fffu);let hb = min(((a >> 16u) + 1u) >> 1u, 0x7fffu);- return Hit(t, PROC_BIT | (min(g.material, 255u) << 23u) | prim, proc_word(q.x | (q.y << 15u)), proc_word(ha | (hb << 15u)), rec);+ return Hit(t, PROC_BIT | (min(g.material, 255u) << 23u) | prim, proc_word(q.x | (q.y << 15u)), proc_word(ha | (hb << 15u)), rec, 0u);}// A procedural hit's attribute (GOut.attr): its material function's `i.uv`.@@ -631,16 +730,17 @@ fn proc_normal(h: Hit) -> vec3<f32> {// The camera ray's hit on a known triangle (two-sided, no t range): the raster pass already resolved visibility.fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {- let a = tri_verts[ti * 3u].xyz;- let e1 = tri_verts[ti * 3u + 1u].xyz;- let e2 = tri_verts[ti * 3u + 2u].xyz;+ let ix = tri_indices(ti) * VERTEX_VEC4;+ let a = vertices[ix.x].xyz;+ let e1 = vertices[ix.y].xyz - a;+ let e2 = vertices[ix.z].xyz - a;let p = cross(d, e2);let det = dot(e1, p);let inv = 1.0 / select(det, 1e-20, abs(det) < 1e-20);let s = o - a;let u = dot(s, p) * inv;let q = cross(s, e1);- return Hit(dot(e2, q) * inv, ti, clamp(u, 0.0, 1.0), clamp(dot(d, q) * inv, 0.0, 1.0), NO_INST);+ return Hit(dot(e2, q) * inv, ti, clamp(u, 0.0, 1.0), clamp(dot(d, q) * inv, 0.0, 1.0), NO_INST, ti);}// The software BVH walk (without `hwrt`: trace_hw.wgsl's traversal is the hardware's).@@ -656,9 +756,10 @@ fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {}@if(!hwrt) fn intersect_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> vec3<f32> {- let v0 = tri_verts[i * 3u].xyz;- let e1 = tri_verts[i * 3u + 1u].xyz;- let e2 = tri_verts[i * 3u + 2u].xyz;+ let k = i * 3u;+ let v0 = leaves[k].xyz;+ let e1 = leaves[k + 1u].xyz;+ let e2 = leaves[k + 2u].xyz;let pv = cross(d, e2);let det = dot(e1, pv);if (abs(det) < 1e-12) { return vec3<f32>(INF, 0.0, 0.0); }@@ -676,7 +777,7 @@ fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {// mode: TRACE_CLOSEST, TRACE_SHADOW (any hit among shadow casters), TRACE_ANY (any hit on any surface).@if(!hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {- var hit = Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST);+ var hit = Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);if (rays_off) { return hit; }let inv_d = 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20));@if(!units) var stack: array<u32, 48>;@@ -687,12 +788,12 @@ fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {if (n.count > 0u) {for (var k = 0u; k < n.count; k++) {let ti = n.left_or_first + k;- let flags = bitcast<u32>(tri_verts[ti * 3u].w);- if (mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }let r = intersect_tri(o, d, ti, hit.t);if (r.x < hit.t) {- if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, NO_INST, r.y, r.z, r.x)) { shadow_hole = true; continue; }- hit = Hit(r.x, ti, r.y, r.z, NO_INST);+ let flags = leaf_id(ti, 0u);+ if (mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }+ if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, NO_INST, ti, r.y, r.z, r.x)) { shadow_hole = true; continue; }+ hit = Hit(r.x, ti, r.y, r.z, NO_INST, ti);if (mode != TRACE_CLOSEST) { return hit; }}}@@ -890,9 +991,10 @@ fn glass_hit(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {}fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {- var a = attrs[h.tri];- var e1 = tri_verts[h.tri * 3u + 1u].xyz;- var e2 = tri_verts[h.tri * 3u + 2u].xyz;+ let td = tri_data(h.tri, h.inst, h.part);+ var a = td.a;+ var e1 = td.e1;+ var e2 = td.e2;var side = 1.0;if (has(F_INST) && h.inst != NO_INST) {let r = instance_at(h.inst);@@ -1179,13 +1281,14 @@ fn obj_tint(oi: u32) -> vec3<f32> { return object_at(oi * OBJECT_STRIDE + 3u).rgfn obj_power(a: TriAttr) -> f32 { return object_at(object_of(a) * OBJECT_STRIDE).w; }// Inputs at a point of triangle ti (barycentrics u, v) for material functions outside full shading (alpha, NEE).-// `inst`: the instance a mesh's triangle is placed by (as `surface` places it), or NO_INST. (By F_IFUNC, not by-// F_INST: where no instanced mesh has a function the placement is not compiled in.)-fn mat_in_at(ti: u32, inst: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {- var a = attrs[ti];- var v0 = tri_verts[ti * 3u].xyz;- var e1 = tri_verts[ti * 3u + 1u].xyz;- var e2 = tri_verts[ti * 3u + 2u].xyz;+// `inst`: the instance a mesh's triangle is placed by (as `surface` places it), or NO_INST; `part`: as a hit's. (By+// F_IFUNC, not by F_INST: where no instanced mesh has a function the placement is not compiled in.)+fn mat_in_at(ti: u32, inst: u32, part: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {+ let td = tri_data(ti, inst, part);+ var a = td.a;+ var v0 = td.v0;+ var e1 = td.e1;+ var e2 = td.e2;var side = 1.0;if (has(F_IFUNC) && inst != NO_INST) {let r = instance_at(inst);@@ -1200,9 +1303,13 @@ fn mat_in_at(ti: u32, inst: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> Mlet p = v0 + e1 * u + e2 * v;let ng = normalize(cross(e1, e2)) * side;var n = normalize(a.n0.xyz * w + a.n1.xyz * u + a.n2.xyz * v);- let t = normalize(a.t.xyz - n * dot(n, a.t.xyz) + vec3<f32>(1e-9));+ // (Its frame placed as its attributes are: by F_IFUNC.)+ var placed = NO_INST;+ if (has(F_IFUNC)) { placed = inst; }+ let tw = hit_tangent(td, placed);+ let t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));let oi = object_of(a);- return MatIn(p, n, ng, t, cross(n, t) * a.t.w, mesh_uv(a, m, u, v), mesh_lod(mesh_density(e1, e2, a, m), 1.0, 1.0), view, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz,+ return MatIn(p, n, ng, t, cross(n, t) * tw.w, mesh_uv(a, m, u, v), mesh_lod(mesh_density(e1, e2, a, m), 1.0, 1.0), view, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz,P.time.x, P.time.y, P.time.z, lod, cur_depth, object_at(oi * OBJECT_STRIDE).w, cur_depth == 0u || mirror_path,object_at(oi * OBJECT_STRIDE + 2u));}@@ -1237,14 +1344,16 @@ var<private> nee_alone: bool = false;var<private> lights_only: bool = false;// Alpha-cutout test for candidate hits on masked triangles (mesh UVs, footprint of a camera ray at distance t). `inst`:-// the model instance a pool triangle belongs to (it places the triangle's edges: its texel density), or NO_INST.-fn alpha_pass(ti: u32, inst: u32, u: f32, v: f32, t: f32) -> bool {- let a = attrs[ti];+// the model instance a pool triangle belongs to (it places the triangle's edges: its texel density), or NO_INST;+// `part`: as a hit's.+fn alpha_pass(ti: u32, inst: u32, part: u32, u: f32, v: f32, t: f32) -> bool {+ let td = tri_data(ti, inst, part);+ let a = td.a;let m = material_at(material_of(a, inst));var alpha = m.base_color.a;if (has(F_TEX) && m.tex0.x >= 0) {- var e1 = tri_verts[ti * 3u + 1u].xyz;- var e2 = tri_verts[ti * 3u + 2u].xyz;+ var e1 = td.e1;+ var e2 = td.e2;if (has(F_INST) && inst != NO_INST) {let r = instance_at(inst);e1 = inst_vec(r, e1);@@ -1255,7 +1364,7 @@ fn alpha_pass(ti: u32, inst: u32, u: f32, v: f32, t: f32) -> bool {alpha *= tex(m.tex0.x, mesh_uv(a, m, u, v), lod).a;}if (has(F_FUNC) && m.tex1.w > 0) {- let i = mat_in_at(ti, inst, u, v, vec3<f32>(0.0, 1.0, 0.0), log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)));+ let i = mat_in_at(ti, inst, part, u, v, vec3<f32>(0.0, 1.0, 0.0), log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)));var b = mat_base(m);b.opacity = alpha;alpha = alpha_material_function(m.tex1.w - 1, i, m, b).opacity;@@ -1275,9 +1384,10 @@ fn emission(m: Material, uv: vec2<f32>, lod: f32) -> vec3<f32> {fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {if (is_proc(h)) { return surface_proc(o, d, h, width); }let i = h.tri;- var e1 = tri_verts[i * 3u + 1u].xyz;- var e2 = tri_verts[i * 3u + 2u].xyz;- var a = attrs[i];+ let td = tri_data(i, h.inst, h.part);+ var e1 = td.e1;+ var e2 = td.e2;+ var a = td.a;var side = 1.0;if (has(F_INST) && h.inst != NO_INST) {let r = instance_at(h.inst);@@ -1330,19 +1440,21 @@ fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {let near = cur_depth == 0u || mirror_path;if (has(F_TEX) && m.tex0.y >= 0 && near) {let tn = tex(m.tex0.y, uv, lod).xyz * 2.0 - 1.0;- let tp = a.t.xyz - n * dot(n, a.t.xyz);+ let tw = hit_tangent(td, h.inst);+ let tp = tw.xyz - n * dot(n, tw.xyz);if (dot(tp, tp) > 1e-12) {let t = normalize(tp);- let b = cross(n, t) * a.t.w;+ let b = cross(n, t) * tw.w;let pn = t * (tn.x * m.params.w) + b * (tn.y * m.params.w) + n * tn.z;if (dot(pn, pn) > 1e-12 && dot(pn, ng) > 0.0) { n = normalize(pn); }}}if (has(F_FUNC) && m.tex1.w > 0) {let oi = object_of(a);- var t = normalize(a.t.xyz - n * dot(n, a.t.xyz) + vec3<f32>(1e-9));+ let tw = hit_tangent(td, h.inst);+ var t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));let nv = normalize(a.n0.xyz * w + a.n1.xyz * h.u + a.n2.xyz * h.v) * select(-1.0, 1.0, front || dot(a.n0.xyz, ng) > 0.0);- let i = MatIn(p, select(-nv, nv, dot(nv, ng) >= 0.0), ng, t, cross(n, t) * a.t.w, mesh_uv(a, m, h.u, h.v), mesh_lod(density, 1.0, 1.0), -d,+ let i = MatIn(p, select(-nv, nv, dot(nv, ng) >= 0.0), ng, t, cross(n, t) * tw.w, mesh_uv(a, m, h.u, h.v), mesh_lod(density, 1.0, 1.0), -d,object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz, P.time.x, P.time.y, P.time.z,log2(max(width, 1e-7)) - 0.5 * log2(max(abs(dot(ng, d)), 1e-3)), cur_depth, object_at(oi * OBJECT_STRIDE).w, near,object_at(oi * OBJECT_STRIDE + 2u));@@ -1897,25 +2009,33 @@ fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {// its triangle's, with its instance's object if it has one. (Not the normals and the tangent, which stay the mesh's:// a light sample reads none, and placing them is work a sample. Its texel density is from the list's own edges.)fn emitter_attrs(em: EmitterTri) -> TriAttr {- var a = attrs[em.tri];+ var a = tri_data(em.tri, em.inst, em.part).a;if (has(F_INST) && em.inst != NO_INST) { a.x = inst_x(instance_at(em.inst).info, a.x); }return a;}+// A mesh's triangle's index in its section. Hardware traversal: from the section's first triangle (the instance's+// row for it, the word a hit's triangle is found by: trace_hw.wgsl `hit_tri`). Software traversal's units: its+// leaf's id (a tree has a mesh's triangles in its own order).+@if(hwrt) fn hit_rank(h: Hit, rows: u32) -> u32 { return h.tri - row_word(rows, h.part, 1u); }+@if(!hwrt) fn hit_rank(h: Hit, rows: u32) -> u32 { return leaf_id(h.tri, 1u); }+// The MIS weight of a BSDF ray's (pdf `pdf`) hit on an emitter against light sampling in `direct_light`: by the// density light sampling has for the point, the probability it picks the emitter (`emitter_pmf`, at the vertex the// ray left) over the triangle's area. One it never picks (no entry, no weight: switched off, culled, a procedural// surface) is the BSDF ray's alone.fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {if (is_proc(hit) || P.counts.y == 0u) { return 1.0; }- // The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled). A triangle an- // instance places: x.w is its index in its section, counted from the section's first entry (its row's).- let a = attrs[hit.tri];- var entry = bitcast<u32>(a.x.w);+ // The hit triangle's emitter. One no instance places: its row has the entry + 1 (0: it is not light-sampled). A+ // mesh's: its index in its section, counted from the section's first entry (its instance's row's).+ var entry = 0u;if (has(F_INST) && hit.inst != NO_INST) {- let first = row_word(instance_at(hit.inst).info.w, bitcast<u32>(a.uv.w), 2u);+ let rows = instance_at(hit.inst).info.w;+ let first = row_word(rows, hit.part, 2u);if (first == NO_EMITTER) { return 1.0; }- entry += first + 1u;+ entry = first + hit_rank(hit, rows) + 1u;+ } else {+ entry = tri_row(hit.part).w;}if (entry == 0u) { return 1.0; }let em = emitter_tri_at(entry - 1u);@@ -2174,7 +2294,7 @@ fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32>if (has(F_FUNC) && m.tex1.w > 0) {var mb = mat_base(m);mb.emissive *= pw;- le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, em.inst, b1, b2, -l, log2(0.05)), m, mb).emissive;+ le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, em.inst, em.part, b1, b2, -l, log2(0.05)), m, mb).emissive;}return le;}@@ -2246,7 +2366,7 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobeslet dist = sqrt(d2);let l = dl / dist;var cos_l = dot(ln, -l);- let m_card = material_at(material_of(attrs[em.tri], em.inst)).tex1.z == MAT_EMITTER_CARD;+ let m_card = emitter_is_card(em);if (!m_card) { cos_l = abs(cos_l); }if (cos_l <= 0.0) { return r; }r.le = emitter_radiance(em, pick_b.x, pick_b.y, l);@@ -2281,7 +2401,7 @@ fn sample_emitter(x: vec3<f32>, n: vec3<f32>, rd: u32) -> ES {let dist = sqrt(d2);let l = dl / dist;var cos_l = dot(ln, -l);- if (material_at(material_of(attrs[em.tri], em.inst)).tex1.z != MAT_EMITTER_CARD) { cos_l = abs(cos_l); }+ if (!emitter_is_card(em)) { cos_l = abs(cos_l); }if (cos_l <= 0.0 || (has(F_PEMIT) && !(cos_l > 0.0))) { return r; } // also a particle not shown (no area: NaN)r.le = emitter_radiance(em, b1, b2, l);r.l = l;@@ -3455,9 +3575,10 @@ fn cache_end(s: Surface, d: vec3<f32>, cone: vec2<f32>, thr: vec3<f32>, depth: ureturn c;}-// A pixel `main` left for `finish`, DEFERRED_VECS vec4<u32>s (floats as their bits): (pixel, DF_ flags | depth << 8,-// light list + its length, hit triangle) (hit instance, u, v, k_spec.x) (hit point, cone width) (ray direction, cone-// spread) (path weight, k_spec.y) (the specular ray's weight, k_spec.z).+// A pixel `main` left for `finish`, DEFERRED_VECS vec4<u32>s (floats as their bits): (pixel, DF_ flags | depth << 8+// (255 at most) | an instance's hit's section << 16 (scene.rs `MESH_SECTIONS`), light list + its length, hit triangle)+// (hit instance, u, v, k_spec.x) (hit point, cone width) (ray direction, cone spread) (path weight, k_spec.y) (the+// specular ray's weight, k_spec.z).const DEFERRED_VECS: u32 = 6u;const DEFERRED_ROW: u32 = 16384u; // `finish` invocations a dispatch row (gpu.rs DEFERRED_ROW)const DF_TRAIN: u32 = 1u; // of a training tile@@ -3487,7 +3608,8 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {let pix = r0.x;let fl = r0.y;rng_start(vec2<u32>(pix % P.size.x, pix / P.size.x), P.size.z, P.size.w, 0u);- cur_depth = fl >> 8u;+ let depth = (fl >> 8u) & 0xffu;+ cur_depth = depth;mirror_path = (fl & DF_MIRROR) != 0u;rays_off = LIVE && P.raster.w > 0.5;if (has(F_LISTS)) {@@ -3496,8 +3618,9 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {lt_fb = LT_NONE;}// (The hit point as the ray's origin, at distance 0.)- let s = surface(r2.xyz, r3.xyz, Hit(0.0, r0.w, bitcast<f32>(r1.y), bitcast<f32>(r1.z), r1.x), r2.w);- let c = cache_end(s, r3.xyz, vec2<f32>(r2.w, r3.w), r4.xyz, fl >> 8u, (fl & DF_TRAIN) != 0u, (fl & DF_HIT_LIGHT) != 0u, (fl & DF_STRAIGHT) != 0u);+ // (A hit without an instance: its row is its triangle.)+ let s = surface(r2.xyz, r3.xyz, Hit(0.0, r0.w, bitcast<f32>(r1.y), bitcast<f32>(r1.z), r1.x, select(fl >> 16u, r0.w, r1.x == NO_INST)), r2.w);+ let c = cache_end(s, r3.xyz, vec2<f32>(r2.w, r3.w), r4.xyz, depth, (fl & DF_TRAIN) != 0u, (fl & DF_HIT_LIGHT) != 0u, (fl & DF_STRAIGHT) != 0u);if ((fl & DF_OUT) == 0u || non_finite(c)) { return; }let cs = c * vec3<f32>(bitcast<f32>(r1.w), r4.w, r5.w);var px = accum[pix];@@ -3805,11 +3928,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {if (raster && depth == 0u) {let id = textureLoad(vis_tex, vec2<i32>(gid.xy), 0).x;if (id == 0u) {- hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST);+ hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);} else {hit = tri_hit(id - 1u, o, d);// The raster pass draws cutout triangles whole: the alpha test decides here, else trace past them.- if (has(F_MASKED) && (bitcast<u32>(tri_verts[hit.tri * 3u].w) & TRI_MASKED) != 0u && !alpha_pass(hit.tri, NO_INST, hit.u, hit.v, hit.t)) {+ if (has(F_MASKED) && (tri_flags(hit.part) & TRI_MASKED) != 0u && !alpha_pass(hit.tri, NO_INST, hit.part, hit.u, hit.v, hit.t)) {hit = trace(o, d, INF, TRACE_CLOSEST);}}@@ -3921,8 +4044,14 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {// denormal below 2^23, which a driver may flush to zero).// 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;+ var deforms = false;+ if (LIVE && P.motion.x > 0.5 && !is_proc(hit)) {+ if (has(F_INST) && hit.inst != NO_INST) {+ deforms = has(F_DEFORM) && (bitcast<u32>(instance_at(hit.inst).n1.w) & INST_DEFORMS) != 0u;+ } else {+ deforms = ti >= P.group_first[1].x && (tri_flags(hit.part) & TRI_DYNAMIC) != 0u;+ }+ }if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {// Procedural geometry: its object-space hit point through the previous frame's rows.let r = instance_at(hit.inst);@@ -3935,19 +4064,27 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {// previous frame's transform (p rows; the same as m when it did not move).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);- // (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);+ let ix = tri_indices(ti);+ let now = (ix + vec3<u32>(r.info.z)) * VERTEX_VEC4;+ var q0 = vertices[now.x].xyz;+ var q1 = vertices[now.y].xyz;+ var q2 = vertices[now.z].xyz;+ // (A deforming mesh's previous positions are where its record says, n2.w, its vertices as the+ // mesh has them. F_DEFORM: a scene with such a mesh.)+ if (has(F_DEFORM) && deforms) {+ let before = (ix + vec3<u32>(bitcast<u32>(r.n2.w))) * VERTEX_VEC4;+ q0 = prev_verts[before.x].xyz;+ q1 = prev_verts[before.y].xyz;+ q2 = prev_verts[before.z].xyz;}+ let lp = vec4<f32>(q0 + (q1 - q0) * hit.u + (q2 - q0) * 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) {- let pp = prev_verts[kp].xyz + prev_verts[kp + 1u].xyz * hit.u + prev_verts[kp + 2u].xyz * hit.v;+ // (A world-space triangle that moves: its vertices' previous positions, from the first that moves.)+ let ix = (tri_indices(ti) - vec3<u32>(P.word_first[1].z)) * VERTEX_VEC4;+ let q0 = prev_verts[ix.x].xyz;+ let pp = q0 + (prev_verts[ix.y].xyz - q0) * hit.u + (prev_verts[ix.z].xyz - q0) * hit.v;mv = vec4<f32>(pp - s.p, 1.0);}if (has(F_LISTS)) { lt_list_start(s.p + mv.xyz); }@@ -4006,7 +4143,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {if (later || train) {let at = atomicAdd(&deferred.n, 1u) * DEFERRED_VECS;if (at + DEFERRED_VECS <= arrayLength(&deferred.recs)) {- let fl = (depth << 8u) | select(0u, DF_TRAIN, train) | select(0u, DF_OUT, later) | select(0u, DF_HIT_LIGHT, hit_light) | select(0u, DF_STRAIGHT, straight)+ let fl = (min(depth, 255u) << 8u) | select(0u, hit.part << 16u, hit.inst != NO_INST) | select(0u, DF_TRAIN, train) | select(0u, DF_OUT, later) | select(0u, DF_HIT_LIGHT, hit_light) | select(0u, DF_STRAIGHT, straight)| select(0u, DF_MIRROR, mirror_path) | select(0u, DF_RESOLVE, resolve_on() && !through0 && !glass0) | select(0u, DF_REFL_RAY, refl_pdf > 0.0);var lt = 0u;if (has(F_LISTS) && lt_list_n > 0u) { lt = lt_list + lt_list_n; }diff --git a/renderer/shaders/skin.wgsl b/renderer/shaders/skin.wgslindex b4607fa..bf514ce 100644--- a/renderer/shaders/skin.wgsl+++ b/renderer/shaders/skin.wgsl@@ -1,15 +1,15 @@-// The skinning pass: the triangles of meshes that deform, from their corners (skin.rs `SkinCorner`, as the file has-// them) and their poses' palettes, into the scene's triangles, shading attributes and BLAS vertices. One invocation a-// triangle; a workgroup is 64 triangles of one mesh (`blocks`: the frame's work, the meshes with a new pose alone).-// What it writes is what the CPU skin writes (skin.rs `Model::triangles`, scene.rs `tri_attr`).+// The skinning pass: the vertices of meshes that deform, from their model's vertices (skin.rs `SkinCorner`, as the+// file has them) and their poses' palettes, into the scene's positions and vertex attributes. One invocation a vertex;+// a workgroup is 64 vertices of one mesh (`blocks`: the frame's work, the meshes with a new pose alone). What it+// writes is what the CPU skin writes (skin.rs `skin_corner`).struct Params {// x: the frame's blocks.n: vec4<u32>,}-// A mesh that deforms: its first triangle in the scene's triangles and how many, its first triangle among the-// corners, its palette's first matrix.+// A mesh that deforms: its first vertex among the scene's and how many, its model's first vertex among `corners`, its+// palette's first matrix.struct Job {first: u32,count: u32,@@ -28,36 +28,20 @@ struct Corner {w: vec4<f32>,}-// (pathtrace.wgsl `TriAttr`.)-struct TriAttr {- n0: vec4<f32>,- n1: vec4<f32>,- n2: vec4<f32>,- uv: vec4<f32>,- t: vec4<f32>,- x: vec4<f32>,-}--// (pathtrace.wgsl `TRI_DYNAMIC`.)-const TRI_DYNAMIC: u32 = 4u;const CORNER_NORMAL: u32 = 1u;const CORNER_TANGENT: u32 = 2u;// Workgroups a row of the dispatch (a dimension holds 65,535).const ROW: u32 = 32768u;-// Whether the BLASes' input is written too: hardware traversal. Software traversal has none (its meshes' trees take-// their boxes on the CPU), and binds a word there.-override BLAS: bool = true;@group(0) @binding(0) var<uniform> PP: Params;-// (mesh, its first triangle of the block)+// (mesh, its first vertex of the block)@group(0) @binding(1) var<storage, read> blocks: array<vec2<u32>>;@group(0) @binding(2) var<storage, read> jobs: array<Job>;@group(0) @binding(3) var<storage, read> corners: array<Corner>;// Three rows a matrix.@group(0) @binding(4) var<storage, read> palette: array<vec4<f32>>;-@group(0) @binding(5) var<storage, read_write> verts: array<vec4<f32>>;-@group(0) @binding(6) var<storage, read_write> attrs: array<TriAttr>;-@group(0) @binding(7) var<storage, read_write> blas: array<f32>;+// The scene's vertices (pathtrace.wgsl `vertices`), three rows each: (position, u), (normal, v), (tangent, hand).+@group(0) @binding(5) var<storage, read_write> vertices: array<vec4<f32>>;struct Placed {p: vec3<f32>,@@ -109,78 +93,21 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lif local >= job.count {return;}- let k = job.first + local;- let s = (job.source + local) * 3u;- let flags = bitcast<u32>(corners[s].t.w);- let c0 = place(corners[s], job.palette);- let c1 = place(corners[s + 1u], job.palette);- let c2 = place(corners[s + 2u], job.palette);- let e1 = c1.p - c0.p;- let e2 = c2.p - c0.p;- let area2 = cross(e1, e2);- var n0 = c0.n;- var n1 = c1.n;- var n2 = c2.n;- if (flags & CORNER_NORMAL) == 0u {- n0 = unit(area2);- n1 = n0;- n2 = n0;+ let k = (job.first + local) * 3u;+ let c = corners[job.source + local];+ let flags = bitcast<u32>(c.t.w);+ let q = place(c, job.palette);+ // (The BLASes are built from the positions: one that is not finite is the mesh's origin there.)+ var p = q.p;+ if !(finite(p.x) && finite(p.y) && finite(p.z)) {+ p = vec3<f32>(0.0);}- var at = attrs[k];- let uv0 = vec2<f32>(at.n0.w, at.n1.w);- let d1 = vec2<f32>(at.n2.w, at.uv.x) - uv0;- let d2 = vec2<f32>(at.uv.y, at.uv.z) - uv0;- let det = d1.x * d2.y - d2.x * d1.y;- // The tangent frame: the file's, its first corner's (its hand stays); or the triangle's own from its UVs.- var t = c0.t;- var hand = at.t.w;- if (flags & CORNER_TANGENT) == 0u {- if abs(det) < 1e-12 {- var any = vec3<f32>(0.0, 1.0, 0.0);- if abs(n0.x) < 0.9 {- any = vec3<f32>(1.0, 0.0, 0.0);- }- t = normalize(cross(n0, any));- hand = 1.0;- } else {- let r = 1.0 / det;- t = unit((e1 * d2.y - e2 * d1.y) * r);- let bt = (e2 * d1.x - e1 * d2.x) * r;- hand = -1.0;- if dot(cross(n0, t), bt) < 0.0 {- hand = 1.0;- }- }- }- at.n0 = vec4<f32>(n0, at.n0.w);- at.n1 = vec4<f32>(n1, at.n1.w);- at.n2 = vec4<f32>(n2, at.n2.w);- at.t = vec4<f32>(t, hand);- attrs[k] = at;- // (The flag word: the kernel takes a deforming mesh's motion from the previous frame's vertices.)- verts[k * 3u] = vec4<f32>(c0.p, bitcast<f32>(TRI_DYNAMIC));- verts[k * 3u + 1u] = vec4<f32>(e1, 0.0);- verts[k * 3u + 2u] = vec4<f32>(e2, 0.0);- if !BLAS {- return;+ vertices[k] = vec4<f32>(p, vertices[k].w);+ // A model without normals keeps zeros (the triangle's own is made where it is hit); one without tangents too.+ if (flags & CORNER_NORMAL) != 0u {+ vertices[k + 1u] = vec4<f32>(q.n, vertices[k + 1u].w);}- // The BLAS's vertices: a triangle that is not finite has no size there.- var q0 = c0.p;- var q1 = c1.p;- var q2 = c2.p;- if !(finite(q0.x) && finite(q0.y) && finite(q0.z) && finite(q1.x) && finite(q1.y) && finite(q1.z) && finite(q2.x) && finite(q2.y) && finite(q2.z)) {- q0 = vec3<f32>(0.0);- q1 = q0;- q2 = q0;+ if (flags & CORNER_TANGENT) != 0u {+ vertices[k + 2u] = vec4<f32>(q.t, vertices[k + 2u].w);}- let v = k * 9u;- blas[v] = q0.x;- blas[v + 1u] = q0.y;- blas[v + 2u] = q0.z;- blas[v + 3u] = q1.x;- blas[v + 4u] = q1.y;- blas[v + 5u] = q1.z;- blas[v + 6u] = q2.x;- blas[v + 7u] = q2.y;- blas[v + 8u] = q2.z;}diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgslindex 06d3eaf..b565b2f 100644--- a/renderer/shaders/trace_hw.wgsl+++ b/renderer/shaders/trace_hw.wgsl@@ -7,7 +7,7 @@@if(hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {// Ray tracing off (pathtrace.wgsl `rays_off`): past the camera ray, every ray misses.- if (rays_off) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }+ if (rays_off) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }let mask = select(0xffu, 1u, mode == TRACE_SHADOW);let any = mode != TRACE_CLOSEST;// (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both. Glass among an@@ -45,26 +45,26 @@if (h.tri == 0xffffffffu) {// (A shadow ray comes here in order only past a cutout that let it through, `shadow_hole`, or past glass.)if (any && !first && hole) { shadow_hole = true; }- return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST);+ return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);}let t = t0 + h.t;// A shadow ray passes the glass among an instance's sections (its row says so; an instance that is all glass is// out of its way by its mask).let passes = has(F_IGLASS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;if (!passes) {- if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || alpha_pass(h.tri, h.inst, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst); }+ if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || alpha_pass(h.tri, h.inst, h.part, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst, h.part); }hole = true;}if (first) { first = false; } else { t0 = t + 1e-4 * max(1.0, t); }}- if (any) { return Hit(t0, 0u, 0.0, 0.0, NO_INST); }- return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST);+ if (any) { return Hit(t0, 0u, 0.0, 0.0, NO_INST, 0u); }+ return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);}// The closest (or with `any`, the first found) hit, every triangle opaque.@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool) -> Hit {hit_row = NO_ROW;- @if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }+ @if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }var rq: ray_query;let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_FORCE_OPAQUE | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);rayQueryInitialize(&rq, acc, RayDesc(flags, mask, 0.0, tmax_in, o, d));@@ -94,12 +94,14 @@}let it = rayQueryGetCommittedIntersection(&rq);if (it.kind == RAY_QUERY_INTERSECTION_NONE) {- return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST);+ return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);}if (has(F_PROC) && it.kind == RAY_QUERY_INTERSECTION_GENERATED) { return proc_hit(it.t, pg, pprim, it.instance_custom_data); }let ti = hit_tri(it.instance_custom_data, it.geometry_index, it.primitive_index);- // Model instance (F_INST, custom data bit 23 | record): ti is its model-space pool triangle.- return Hit(it.t, ti, it.barycentrics.x, it.barycentrics.y, hit_inst(it.instance_custom_data));+ // Model instance (F_INST, custom data bit 23 | record): ti is its model-space pool triangle, and the geometry it+ // was hit in its section. A traversal group's triangle is in the world: its row is its own.+ let inst = hit_inst(it.instance_custom_data);+ return Hit(it.t, ti, it.barycentrics.x, it.barycentrics.y, inst, select(it.geometry_index, ti, inst == NO_INST));}// The first word of the row of the hit `trace_opaque` last found (its material and class bits), NO_ROW where its@@ -110,7 +112,7 @@// material has an alpha test, as the build flags TRI_MASKED.@if(hwrt) fn cutout_hit(h: Hit) -> bool {if (has(F_INST) && hit_row != NO_ROW) { return (hit_row & ROW_CUTOUT) != 0u; }- return material_at(triangle_material(attrs[h.tri])).uv2.w > 0.0;+ return material_at(tri_row(h.part).x).uv2.w > 0.0;}// The model-instance record a hit's custom data names (F_INST), or NO_INST for a traversal group.diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgslindex b3cc71f..6ef15a5 100644--- a/renderer/shaders/trace_units.wgsl+++ b/renderer/shaders/trace_units.wgsl@@ -37,10 +37,10 @@ const UNIT_SHADOW: u32 = 1u;const UNIT_SHIFTED: u32 = 2u;@if(units) var<private> stack: array<u32, 64>;-// The flags of a triangle of a unit with rows (from `first` on), which its vertices do not carry: its section's row-// says whether it is a cutout's (TRI_MASKED) or glass (TRI_NO_SHADOW). Asked of the units that have such a section.-@if(units) fn row_flags(first: u32, ti: u32) -> u32 {- let x = row_word(first, bitcast<u32>(attrs[ti].uv.w), 0u);+// The flags of a triangle of a unit with rows (from `first` on), of its section `part`: the section's row says+// whether it is a cutout's (TRI_MASKED) or glass (TRI_NO_SHADOW). Asked of the units that have such a section.+@if(units) fn row_flags(first: u32, part: u32) -> u32 {+ let x = row_word(first, part, 0u);return select(0u, TRI_MASKED, (x & ROW_CUTOUT) != 0u) | select(0u, TRI_NO_SHADOW, (x & ROW_GLASS) != 0u);}@@ -111,11 +111,13 @@ const UNIT_SHIFTED: u32 = 2u;let ti = first + n.left_or_first + k;let x = intersect_tri(ro, rd, ti, hit.t);if (x.x < hit.t) {- var flags = bitcast<u32>(tri_verts[ti * 3u].w);- if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags |= row_flags(urows, ti); }+ // (Its section: its leaf's id.)+ let part = leaf_id(ti, 0u);+ var flags = 0u;+ if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags = row_flags(urows, part); }if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }- if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, x.y, x.z, x.x)) { shadow_hole = true; continue; }- hit = Hit(x.x, ti, x.y, x.z, rec);+ if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, part, x.y, x.z, x.x)) { shadow_hole = true; continue; }+ hit = Hit(x.x, ti, x.y, x.z, rec, part);if (mode != TRACE_CLOSEST) { return hit; }}}diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgslindex 41dab3a..c1ef125 100644--- a/renderer/shaders/translucent.wgsl+++ b/renderer/shaders/translucent.wgsl@@ -57,11 +57,14 @@// Material of a translucent particle at triangle ti (barycentrics b): colour, opacity and emission after maps and its// material function.@if(hwrt) fn particle_material(ti: u32, b: vec2<f32>, view: vec3<f32>, lod: f32) -> MatOut {- let a = attrs[ti];+ // (Its row: the translucent triangles' rows follow the other rows, from `P.word_first[1].w` on.)+ let row = P.word_first[1].w + ti - TPS.size.z;+ let td = tri_data(ti, NO_INST, row);+ let a = td.a;// (A particle's triangle is in the world: no instance.)let m = material_at(material_of(a, NO_INST));let uv = mesh_uv(a, m, b.x, b.y);- let tl = mesh_lod(mesh_density(tri_verts[ti * 3u + 1u].xyz, tri_verts[ti * 3u + 2u].xyz, a, m), 1.0, 1.0) + lod - LOD_BIAS;+ let tl = mesh_lod(mesh_density(td.e1, td.e2, a, m), 1.0, 1.0) + lod - LOD_BIAS;var r = mat_base(m);if (has(F_TEX) && m.tex0.x >= 0) {let c = tex(m.tex0.x, uv, tl);@@ -70,7 +73,7 @@}r.emissive = emission(m, uv, tl) * obj_power(a);if (has(F_FUNC) && m.tex1.w > 0) {- r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, NO_INST, b.x, b.y, view, lod), m, r);+ r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, NO_INST, row, b.x, b.y, view, lod), m, r);}return r;}diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex f2ce09a..61db92d 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -161,8 +161,9 @@ pub struct Params {/// Each table's first vec4 in the tables' heap (`heap::Table`'s order; `Uploaded::place`).pub table_first: [[u32; 4]; 3],/// Each stream's first word in the words' heap (`heap::Stream`'s order): the environment's CDF, the procedural- /// data, the vertex colours, -.- pub word_first: [u32; 4],+ /// data, the vertex colours, the instances' rows; the triangles' indices, their rows. Then the first vertex that+ /// moves (the previous positions count from it), -.+ pub word_first: [[u32; 4]; 2],/// The merged layout (`KernelBufs::place`): each of group 1's vec4 sections' first vec4 in the tail of its one/// buffer (the cache's values, the specular rays, the motion vectors, the direct light; the light lists), and/// the last four's lengths. As written: zeros (the kernel asks the buffers).@@ -170,6 +171,9 @@ pub struct Params {pub live_len: [u32; 4],}+/// A vertex's bytes (`indexed::Vertex`): the stride the acceleration structures read positions by.+const VERTEX_STRIDE: u64 = crate::indexed::VERTEX_BYTES as u64;+/// Room the live view's in-place geometry edits grow into (live/edits.rs `edit_geometry`), past the scene's own data:/// triangles (verts, attrs, BLAS vertices), kernel records and TLAS instances (and a row a record: what an edit/// places has one section), object-table entries, procedural words.@@ -263,11 +267,11 @@ fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec<wgpu::BlasBuildEntr.zip(parts).map(|(size, &(first, _))| wgpu::BlasTriangleGeometry {size,- vertex_buffer: &accel.verts,- first_vertex: ((accel.pool_first + first as usize) * 3) as u32,- vertex_stride: 12,- index_buffer: None,- first_index: None,+ vertex_buffer: &accel.vertices,+ first_vertex: accel.mesh_verts[m as usize].0,+ vertex_stride: VERTEX_STRIDE,+ index_buffer: Some(&accel.indices),+ first_index: Some(accel.index_first + ((accel.pool_first + first as usize) * 3) as u32),transform_buffer: None,transform_buffer_offset: None,})@@ -288,11 +292,11 @@ fn dynamic_entries(accel: &Accel) -> Vec<wgpu::BlasBuildEntry<'_>> {blas,geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {size,- vertex_buffer: &accel.verts,- first_vertex: (*first * 3) as u32,- vertex_stride: 12,- index_buffer: None,- first_index: None,+ vertex_buffer: &accel.vertices,+ first_vertex: 0,+ vertex_stride: VERTEX_STRIDE,+ index_buffer: Some(&accel.indices),+ first_index: Some(accel.index_first + (*first * 3) as u32),transform_buffer: None,transform_buffer_offset: None,}]),@@ -334,13 +338,12 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLuse crate::merged::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};let LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard } = shape;let (read, write) = (storage_buffer(true), storage_buffer(false));- // Group 0: the parameters; triangles and their attributes; the tables' heap, the words' heap; the dynamic- // triangles' previous vertices; the texture pages and their sampler, the environment, the density grids' atlas+ // Group 0: the parameters; the vertices; the tables' heap, the words' heap; the previous frame's vertices of+ // those that move; the texture pages and their sampler, the environment, the density grids' atlas// (a 1-cell texture in scenes without grids, whose kernel does not read it); the accumulation buffer.let mut scene = vec![layout_entry(0, UNIFORM_BUFFER),layout_entry(1, read),- layout_entry(2, read),layout_entry(4, read),layout_entry(5, read),layout_entry(6, read),@@ -350,8 +353,9 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLlayout_entry(10, float_texture(wgpu::TextureViewDimension::D3)),layout_entry(11, write),];- // Software traversal's trees.+ // Software traversal's trees: their leaves' triangles, their nodes.if !hwrt {+ scene.push(layout_entry(2, read));scene.push(layout_entry(3, read));}// The tables the kernel reads at every hit or light, bound again as typed views of their sections (the merged@@ -405,6 +409,9 @@ fn uniform_copy_bytes(table: u64, copy: u64) -> u64 {/// What the scene bind group holds besides `Uploaded`'s buffers (`Gpu::rebind_scene` makes it again).pub struct BindParts {pub nodes: wgpu::Buffer,+ /// Software traversal: the trees' leaf triangles (`indexed::Leaf`: pathtrace.wgsl `leaves`), with room for an+ /// edit's. (Hardware traversal: unbound, of no triangle.)+ pub leaves: wgpu::Buffer,pub tex_view: wgpu::TextureView,pub env_view: wgpu::TextureView,pub sampler: wgpu::Sampler,@@ -415,11 +422,10 @@ pub struct BindParts {/// What the scene's bind group is made of (`Gpu::scene_bind_group`).struct SceneBuffers<'a> {params: &'a wgpu::Buffer,- verts: &'a wgpu::Buffer,- attrs: &'a wgpu::Buffer,+ vertices: &'a wgpu::Buffer,heap: &'a Heap<Table>,words: &'a Heap<Stream>,- prev_verts: &'a wgpu::Buffer,+ prev_vertices: &'a wgpu::Buffer,accum: &'a wgpu::Buffer,parts: &'a BindParts,accel: Option<&'a Accel>,@@ -430,11 +436,9 @@ struct SceneBuffers<'a> {/// section of the tables as a buffer of its own). The pass's bind group holds them: one replaced, the group is made/// again (`Gpu::rebind_scene`).struct ParticleTargets<'a> {- verts: &'a wgpu::Buffer,- prev_verts: &'a wgpu::Buffer,- blas_verts: &'a wgpu::Buffer,+ vertices: &'a wgpu::Buffer,+ prev_vertices: &'a wgpu::Buffer,heap: &'a Heap<Table>,- attrs: &'a wgpu::Buffer,}fn buffer_entry(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {@@ -444,7 +448,7 @@ fn buffer_entry(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {/// A particle pass's bind group: its `own` buffers at their bindings, and the scene's it writes.fn particle_bind_group(d: &wgpu::Device, pipeline: &wgpu::ComputePipeline, label: &str, own: &[(u32, &wgpu::Buffer)], t: &ParticleTargets) -> wgpu::BindGroup {let mut entries: Vec<wgpu::BindGroupEntry> = own.iter().map(|(binding, b)| buffer_entry(*binding, b)).collect();- entries.extend([buffer_entry(2, t.verts), buffer_entry(3, t.prev_verts), buffer_entry(4, t.blas_verts), wgpu::BindGroupEntry { binding: 5, resource: t.heap.binding(Table::Objects) }, buffer_entry(6, t.attrs)]);+ entries.extend([buffer_entry(2, t.vertices), buffer_entry(3, t.prev_vertices), wgpu::BindGroupEntry { binding: 5, resource: t.heap.binding(Table::Objects) }]);d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(label), layout: &pipeline.get_bind_group_layout(0), entries: &entries })}@@ -464,13 +468,10 @@ pub struct Uploaded {pub params: wgpu::Buffer,/// Kernel specialisation for this scene (`Gpu::pipeline`).pub kernel: Kernel,- /// Triangle vertices / shading attributes (posed models rewrite their ranges).- pub verts: wgpu::Buffer,- pub attrs: wgpu::Buffer,- /// The dynamic triangles' (posed models, movable objects: the tail from `dynamic_first`) vertices of the previous- /// frame, kernel layout: live motion vectors.- pub prev_verts: wgpu::Buffer,- pub dynamic_first: usize,+ /// The vertices (indexed.rs `Vertex`): a record of 48 bytes each; and those that move as they were the previous+ /// frame, whole records too (a copy on the GPU has no stride). What the kernel reads (bindings 1 and 6).+ pub vertices: wgpu::Buffer,+ pub prev_vertices: wgpu::Buffer,pub accel: Option<Accel>,/// Software traversal's units (units.rs), when the scene has any: what `accel` is to hardware traversal. Their/// trees are in the node buffer (`bg_parts.nodes`).@@ -529,9 +530,8 @@ pub struct ParticleGpu {params: wgpu::Buffer,/// The system table (`ParticleSystemGpu`) and each system's node (pivot updates when it moves).table: wgpu::Buffer,- /// The pass's own buffers besides: the last frame's vertices, the translucent BLAS input's stand-in.+ /// The pass's own buffer besides: the last frame's vertices.last: wgpu::Buffer,- no_trans: wgpu::Buffer,nodes: Vec<u32>,systems: u32,max_count: u32,@@ -562,14 +562,15 @@ enum Hidden {/// Volume training points per frame at most (translucent.wgsl `volume_train`).pub const VOLUME_TRAIN_CAP: u32 = 8192;-/// Translucent particles (`transparent` materials; hardware RT): their own BLAS + TLAS over the BLAS input the-/// particle pass writes (`verts`), from triangle `first` in the kernel's tables; the translucency pass's parameters and-/// volume training points (translucent.wgsl).+/// Translucent particles (`transparent` materials; hardware RT): their own BLAS + TLAS over their vertices, which the+/// particle pass writes (`vertices` from `first_vertex`, three a triangle), from triangle `first` in the kernel's+/// tables; the translucency pass's parameters and volume training points (translucent.wgsl).pub struct Translucent {blas: wgpu::Blas,pub tlas: wgpu::Tlas,size: wgpu::BlasTriangleGeometrySizeDescriptor,- verts: wgpu::Buffer,+ vertices: wgpu::Buffer,+ first_vertex: u32,pub first: u32,pub params: wgpu::Buffer,pub points: wgpu::Buffer,@@ -589,7 +590,9 @@ impl Uploaded {let first = self.heap.firsts();p.table_first = std::array::from_fn(|k| std::array::from_fn(|j| first.get(k * 4 + j).copied().unwrap_or(0)));let first = self.words.firsts();- p.word_first = std::array::from_fn(|k| first.get(k).copied().unwrap_or(0));+ for (k, at) in first.iter().enumerate().take(6) {+ p.word_first[k / 4][k % 4] = *at;+ }}}@@ -598,7 +601,7 @@ impl Translucent {fn build(&self, e: &mut wgpu::CommandEncoder) {let entry = wgpu::BlasBuildEntry {blas: &self.blas,- geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry { size: &self.size, vertex_buffer: &self.verts, first_vertex: 0, vertex_stride: 12, index_buffer: None, first_index: None, transform_buffer: None, transform_buffer_offset: None }]),+ geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry { size: &self.size, vertex_buffer: &self.vertices, first_vertex: self.first_vertex, vertex_stride: VERTEX_STRIDE, index_buffer: None, first_index: None, transform_buffer: None, transform_buffer_offset: None }]),};e.build_acceleration_structures([entry].iter(), [&self.tlas]);}@@ -756,6 +759,34 @@ struct SkinJob {palette: u32,}+/// leaf_gather.wgsl `Job`: a mesh: its first triangle in the scene's and how many, its first vertex.+#[repr(C)]+#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]+struct LeafJob {+ first: u32,+ count: u32,+ vertex: u32,+ spare: u32,+}++/// The leaf-gather pass (shaders/leaf_gather.wgsl; software traversal): after the skinning pass has written a+/// mesh's vertices, its tree's leaves take their triangles again from them. A job each skinned model, the skinning+/// pass's order.+struct LeafGather {+ pipeline: wgpu::ComputePipeline,+ bg: Option<wgpu::BindGroup>,+ params: wgpu::Buffer,+ /// A frame's work: (job, its first triangle of the block), `SKIN_BLOCK` triangles each.+ blocks: wgpu::Buffer,+ table: wgpu::Buffer,+ jobs: Vec<LeafJob>,+}++fn leaf_gather_bind_group(d: &wgpu::Device, l: &LeafGather, vertices: &wgpu::Buffer, words: &wgpu::Buffer, leaves: &wgpu::Buffer) -> wgpu::BindGroup {+ let entries: Vec<wgpu::BindGroupEntry> = [&l.params, &l.blocks, &l.table, vertices, words, leaves].iter().enumerate().map(|(k, b)| buffer_entry(k as u32, b)).collect();+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("leaf gather"), layout: &l.pipeline.get_bind_group_layout(0), entries: &entries })+}+/// The skinning pass of a scene (shaders/skin.wgsl): the meshes that deform (a job each, `scene::Skinned`'s index)/// are skinned from their models' corners and their poses' palettes into the scene's triangles, attributes and BLAS/// input. Hardware RT.@@ -774,8 +805,8 @@ pub struct SkinGpu {/// 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,- /// Software traversal: what stands at the BLAS input's binding (the pass writes none there).- no_blas: Option<wgpu::Buffer>,+ /// Software traversal: the pass that takes the trees' leaves again from the vertices this one wrote.+ leaves: Option<LeafGather>,}impl SkinGpu {@@ -827,9 +858,9 @@ impl SkinGpu {}}-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 {+fn skin_bind_group(d: &wgpu::Device, pipeline: &wgpu::ComputePipeline, own: [&wgpu::Buffer; 5], vertices: &wgpu::Buffer) -> wgpu::BindGroup {let mut entries: Vec<wgpu::BindGroupEntry> = own.iter().enumerate().map(|(k, b)| buffer_entry(k as u32, b)).collect();- entries.extend([buffer_entry(5, verts), buffer_entry(6, attrs), buffer_entry(7, blas_verts)]);+ entries.push(buffer_entry(5, vertices));d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("skin"), layout: &pipeline.get_bind_group_layout(0), entries: &entries })}@@ -916,8 +947,15 @@ fn particle_source(scene: &Scene) -> String {/// Hardware acceleration structures: one BLAS per non-empty traversal group, one TLAS over them.pub struct Accel {pub tlas: wgpu::Tlas,- /// Triangle vertices the BLASes are built from (12 B per vertex, 3 per triangle).- pub verts: wgpu::Buffer,+ /// What the BLASes are built from: the vertices (`Uploaded::vertices`: a record's first 12 bytes its position) and+ /// the triangles' indices (the words' heap, from word `index_first` on). Handles of the scene's buffers as they+ /// are now (`Gpu::rebind_scene` takes them again when one grew).+ pub vertices: wgpu::Buffer,+ pub indices: wgpu::Buffer,+ pub index_first: u32,+ /// By mesh: its first vertex and how many (`indexed::Indexed::meshes`); and the world-space triangles' vertices.+ pub mesh_verts: Vec<(u32, u32)>,+ pub flat_verts: u32,/// (BLAS, group, first triangle, size).blases: Vec<(wgpu::Blas, usize, usize, wgpu::BlasTriangleGeometrySizeDescriptor)>,/// One per instanced mesh (model space), referenced by the TLAS's model instances.@@ -2401,7 +2439,7 @@ impl Gpu {/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.#[allow(clippy::too_many_arguments)]- pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {+ pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {let d = &self.device;let t0 = Instant::now();// (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a@@ -2425,25 +2463,34 @@ impl Gpu {let records: Vec<crate::scene::GpuInstance> = scene.gpu_instances.iter().chain(&scene.proc_records).copied().collect();// (Software traversal's units have room as hardware traversal's instances do: `prepare` sized their trees'// by the same figures.)- let room = EditRoom::for_scene(scene, tri_verts.len() / 3, records.len(), self.hwrt, scene.units.is_some());+ let room = EditRoom::for_scene(scene, scene.indexed.rows.len(), records.len(), self.hwrt, scene.units.is_some());let st = wgpu::BufferUsages::STORAGE;// (COPY_SRC: the live view's in-place edits grow these past their room by a copy, live/edits.rs `edit_geometry`.)let edit = st | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC;- let b_verts = buf_room("verts", bytemuck::cast_slice(tri_verts), room.tris * 48, edit | wgpu::BufferUsages::COPY_SRC);let dynamic_first: usize = groups[..4].iter().sum();- // The dynamic tail (groups 4..8; the instanced pool follows it, its deforming meshes first: theirs too).- let dynamic_end: usize = groups.iter().sum::<usize>() + crate::scene::deforming_pool(&scene.meshes);- let prev = &tri_verts[(dynamic_first * 3).min(tri_verts.len())..(dynamic_end * 3).min(tri_verts.len())];- let b_prev = buf("prev verts", bytemuck::cast_slice(prev), edit);+ // A particle's triangle's first vertex: three vertices a triangle, from the first vertex that moves (a dynamic+ // world-space triangle) or the first translucent one.+ let (moving, translucent, trans_first) = (scene.indexed.dynamic.0, scene.indexed.translucent, scene.trans_first);+ let vertex_of = move |tri: u32, trans: bool| if trans { translucent + (tri - trans_first) * 3 } else { moving + (tri - dynamic_first as u32) * 3 };+ // The vertices, with room for three a triangle of the edit room; and those that move, as they are (their+ // previous frame's).+ let ix = &scene.indexed;+ anyhow::ensure!(scene.meshes.iter().all(|m| m.sect_count as usize <= crate::scene::MESH_SECTIONS), "a mesh with more than 65,536 sections");+ let b_vertices = buf_room("vertices", bytemuck::cast_slice(&ix.vertices), room.tris * 3 * crate::indexed::VERTEX_BYTES, edit | if self.hwrt { wgpu::BufferUsages::BLAS_INPUT } else { wgpu::BufferUsages::empty() });+ let b_prev = buf("previous vertices", bytemuck::cast_slice(&ix.vertices[ix.dynamic.0 as usize..(ix.dynamic.0 + ix.dynamic.1) as usize]), edit);+ // (A particle pass's own last positions of the vertices that move: 16 bytes each.)+ let last_bytes = ix.dynamic.1.max(1) as u64 * 16;// The vertex colours' bytes on the GPU (the edit room's included).timings.push(("vcolor_mb".into(), if scene.gpu_vcolors.is_empty() { 0.0 } else { (scene.gpu_vcolors.len() * 4 + room.tris * 12) as f64 / (1 << 20) as f64 }));- let b_attrs = buf_room("attrs", bytemuck::cast_slice(&scene.attrs), room.tris * std::mem::size_of::<crate::scene::GpuTriAttr>(), edit);// (With units, edits write trees into it: units.rs.)// (COPY_SRC: read back by the test that holds a refit tree to its triangles.)let b_nodes = buf("nodes", nodes, if scene.units.is_some() { st | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC } else { st });- // What the triangles hold on the GPU besides their BLASes: vertices (a, e1, e2), attributes, the software BVH's nodes+ // (Software traversal: the trees' leaves, with the edit room's.)+ let b_leaves = buf_room("leaves", bytemuck::cast_slice(&ix.leaves), if self.hwrt { 0 } else { room.tris * crate::indexed::LEAF_BYTES }, edit);+ // What the triangles hold on the GPU besides their BLASes: vertices (48 B each), indices (12 B a triangle), the+ // rows of those that have one (16 B), and the software BVH: its nodes and its leaves' triangles (48 B each)// (ROADMAP § 6 step 2's table: a meshed representation against voxel data).- timings.push(("tri_data_mb".into(), (std::mem::size_of_val(tri_verts) + std::mem::size_of_val(&scene.attrs[..]) + nodes.len()) as f64 / (1 << 20) as f64));+ timings.push(("tri_data_mb".into(), (ix.vertices.len() * crate::indexed::VERTEX_BYTES + ix.indices.len() * 12 + ix.gpu_rows().len() * 16 + ix.leaves.len() * crate::indexed::LEAF_BYTES + nodes.len()) as f64 / (1 << 20) as f64));let (words, region_words, proc_room) = self.upload_words(scene, env_cdf, room.proc_words, room.tris, room.records, timings)?;let room = EditRoom { proc_words: proc_room, ..room };// Density grids: field A of each in the atlas (stacked along z), their data; for a grid with a program, its@@ -2540,15 +2587,9 @@ impl Gpu {let mut accel = None;if self.hwrt {let tb = Instant::now();- let verts: Vec<[f32; 3]> = tri_verts- .chunks(3)- .flat_map(|t| {- let v0 = [t[0][0], t[0][1], t[0][2]];- crate::scene::blas_tri([v0, [v0[0] + t[1][0], v0[1] + t[1][1], v0[2] + t[1][2]], [v0[0] + t[2][0], v0[1] + t[2][1], v0[2] + t[2][2]]])- })- .collect();- let vbuf = buf_room("blas_verts", bytemuck::cast_slice(&verts), room.tris * 36, wgpu::BufferUsages::BLAS_INPUT | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::STORAGE);let huge_scene = huge(groups, !scene.gpu_instances.is_empty());+ // (The indices' first word in the words' heap.)+ let index_first = (words.at(Stream::Indices) / 4) as u32;let mut first = 0usize;let groups: Vec<(usize, usize, u8)> = groups.iter()@@ -2565,9 +2606,10 @@ impl Gpu {.iter().map(|&(_, count, _)| wgpu::BlasTriangleGeometrySizeDescriptor {vertex_format: wgpu::VertexFormat::Float32x3,- vertex_count: (count * 3) as u32,- index_format: None,- index_count: None,+ // (A world-space triangle's indices count from vertex 0: any of the world-space vertices.)+ vertex_count: ix.flat.max(1),+ index_format: Some(wgpu::IndexFormat::Uint32),+ index_count: Some((count * 3) as u32),// (Every geometry is flagged opaque, a cutout's too: every query forces opacity, trace_hw.wgsl.)flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,})@@ -2595,14 +2637,15 @@ impl Gpu {let mesh_parts: Vec<Vec<(u32, u32)>> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count)| (m.first + at, count)).collect()).collect();let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts.iter()- .map(|parts| {+ .zip(&ix.meshes)+ .map(|(parts, &(_, vertices))| {parts.iter().map(|&(_, count)| wgpu::BlasTriangleGeometrySizeDescriptor {vertex_format: wgpu::VertexFormat::Float32x3,- vertex_count: count * 3,- index_format: None,- index_count: None,+ vertex_count: vertices.max(1),+ index_format: Some(wgpu::IndexFormat::Uint32),+ index_count: Some(count * 3),flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,}).collect()@@ -2618,14 +2661,15 @@ impl Gpu {d.create_blas(&wgpu::CreateBlasDescriptor { label: None, flags, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: s.clone() })}).collect();- // What the triangle BLASes hold (Metal's own sizes; each instanced mesh once) and their vertex buffer.- let group_parts = groups.iter().filter(|g| g.1 > 0).map(|&(first, count, _)| vec![((first * 3) as u32, (count * 3) as u32)]);- let mesh_vertex_parts = mesh_parts.iter().map(|ps| ps.iter().map(|&(first, count)| ((pool_first as u32 + first) * 3, count * 3)).collect::<Vec<_>>());+ // What the triangle BLASes hold (Metal's own sizes; each instanced mesh once). A geometry: its first vertex+ // and how many, its first triangle and how many.+ let group_parts = groups.iter().filter(|g| g.1 > 0).map(|&(first, count, _)| vec![(0, ix.flat.max(1), first as u32, count as u32)]);+ let mesh_vertex_parts = mesh_parts.iter().zip(&ix.meshes).map(|(ps, &(vfirst, vcount))| ps.iter().map(|&(first, count)| (vfirst, vcount.max(1), pool_first as u32 + first, count)).collect::<Vec<_>>());let mut blas_per_tri = 0.0;- let parts: Vec<Vec<(u32, u32)>> = group_parts.chain(mesh_vertex_parts).collect();- if let Some(bytes) = parts.iter().map(|ps| self.tri_blas_bytes(&vbuf, ps)).sum::<Option<u64>>() {- timings.push(("tri_blas_mb".into(), (bytes + vbuf.size()) as f64 / (1 << 20) as f64));- let tris: u64 = parts.iter().flatten().map(|p| p.1 as u64 / 3).sum();+ let parts: Vec<Vec<(u32, u32, u32, u32)>> = group_parts.chain(mesh_vertex_parts).collect();+ if let Some(bytes) = parts.iter().map(|ps| self.tri_blas_bytes(&b_vertices, &words.buffer, index_first, ps)).sum::<Option<u64>>() {+ timings.push(("tri_blas_mb".into(), bytes as f64 / (1 << 20) as f64));+ let tris: u64 = parts.iter().flatten().map(|p| p.3 as u64).sum();blas_per_tri = bytes as f64 / tris.max(1) as f64;}let base = blases.len();@@ -2677,16 +2721,16 @@ impl Gpu {blas,geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {size,- vertex_buffer: &vbuf,- first_vertex: (*first * 3) as u32,- vertex_stride: 12,- index_buffer: None,- first_index: None,+ vertex_buffer: &b_vertices,+ first_vertex: 0,+ vertex_stride: VERTEX_STRIDE,+ index_buffer: Some(&words.buffer),+ first_index: Some(index_first + (*first * 3) as u32),transform_buffer: None,transform_buffer_offset: None,}]),})- .chain(meshes.iter().zip(&mesh_sizes).zip(&mesh_parts).map(|((blas, sizes), parts)| wgpu::BlasBuildEntry {+ .chain(meshes.iter().zip(&mesh_sizes).zip(&mesh_parts).zip(&ix.meshes).map(|(((blas, sizes), parts), &(first_vertex, _))| wgpu::BlasBuildEntry {blas,geometry: wgpu::BlasGeometries::TriangleGeometries(sizes@@ -2694,11 +2738,11 @@ impl Gpu {.zip(parts).map(|(size, &(first, _))| wgpu::BlasTriangleGeometry {size,- vertex_buffer: &vbuf,- first_vertex: ((pool_first + first as usize) * 3) as u32,- vertex_stride: 12,- index_buffer: None,- first_index: None,+ vertex_buffer: &b_vertices,+ first_vertex,+ vertex_stride: VERTEX_STRIDE,+ index_buffer: Some(&words.buffer),+ first_index: Some(index_first + ((pool_first + first as usize) * 3) as u32),transform_buffer: None,transform_buffer_offset: None,})@@ -2716,7 +2760,7 @@ impl Gpu {self.device.poll(wgpu::PollType::wait_indefinitely())?;drop(entries);let mesh_geo = mesh_parts.into_iter().zip(mesh_sizes).collect();- accel = Some(Accel { tlas: t, verts: vbuf, blases, meshes, mesh_geo, pool_first, inst_base: base, proc_base, blas_per_tri });+ accel = Some(Accel { tlas: t, vertices: b_vertices.clone(), indices: words.buffer.clone(), index_first, mesh_verts: ix.meshes.clone(), flat_verts: ix.flat, blases, meshes, mesh_geo, pool_first, inst_base: base, proc_base, blas_per_tri });timings.push(("accel_build_ms".into(), tb.elapsed().as_secs_f64() * 1000.0));}fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {@@ -2731,8 +2775,8 @@ impl Gpu {}self.uniform_copies(&heap)});- let bg_parts = BindParts { nodes: b_nodes, tex_view, env_view, sampler, grid_view };- let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, verts: &b_verts, attrs: &b_attrs, heap: &heap, words: &words, prev_verts: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });+ let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, sampler, grid_view };+ let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });let kernel = Kernel { approx: self.approx, ..Kernel::new(scene, groups) };// Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.let translucent = match &accel {@@ -2745,11 +2789,10 @@ impl Gpu {);let mut tlas = d.create_tlas(&wgpu::CreateTlasDescriptor { label: Some("translucent"), max_instances: 1, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });tlas[0] = Some(wgpu::TlasInstance::new(&blas, [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], 0, 0xff));- let verts = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent blas verts"), size: n as u64 * 36, usage: wgpu::BufferUsages::BLAS_INPUT | wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let points = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume points"), size: VOLUME_TRAIN_CAP as u64 * 16, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let count = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume point count"), size: 16, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let t = Translucent { blas, tlas, size, verts, first: scene.trans_first, params, points, count };+ let t = Translucent { blas, tlas, size, vertices: b_vertices.clone(), first_vertex: ix.translucent, first: scene.trans_first, params, points, count };// Built once now (collapsed quads): bind groups may use the TLAS before the first particle pass.let mut enc = d.create_command_encoder(&Default::default());t.build(&mut enc);@@ -2768,8 +2811,8 @@ impl Gpu {let sm = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("stamp"), source: wgpu::ShaderSource::Wgsl(STAMP_WGSL.into()) });let sp = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("stamp"), layout: None, module: &sm, entry_point: Some("stamp"), compilation_options: Default::default(), cache: self.cache() });// The stamps depend on what is rebuilt last: the translucent TLAS when there is one.- let (sv, stl) = translucent.as_ref().map_or((&a.verts, &a.tlas), |t| (&t.verts, &t.tlas));- let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, sv), wgpu::BindGroupEntry { binding: 1, resource: stl.as_binding() }] });+ let stl = translucent.as_ref().map_or(&a.tlas, |t| &t.tlas);+ let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, &b_vertices), wgpu::BindGroupEntry { binding: 1, resource: stl.as_binding() }] });let stamp = (sp, sbg);let systems: Vec<ParticleSystemGpu> = scene.particles@@ -2779,22 +2822,21 @@ impl Gpu {let mut p = [0.0f32; 32];p.copy_from_slice(&ps.params);// (A system hidden at build runs nothing: its quads stay collapsed at the node.)- ParticleSystemGpu { a: [ps.final_first, if ps.hidden { 0 } else { ps.count }, ps.object, ps.func], b: [ps.seed, dynamic_first as u32, ps.translucent as u32, scene.trans_first], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }+ ParticleSystemGpu { a: [vertex_of(ps.final_first, ps.translucent), if ps.hidden { 0 } else { ps.count }, ps.object, ps.func], b: [ps.seed, ix.dynamic.0, ps.translucent as u32, 0], c: [o[0], o[1], o[2], 0.0], p, d: ps.custom }}).collect();// COPY_DST: pivot updates (`set_particle_pivot`).let b_sys = buf("particle systems", bytemuck::cast_slice(&systems), edit);let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("particle params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let last = d.create_buffer(&wgpu::BufferDescriptor { label: Some("particles last"), size: b_prev.size(), usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });- let no_trans = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: 64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });- let written = ParticleTargets { verts: &b_verts, prev_verts: &b_prev, blas_verts: &a.verts, heap: &heap, attrs: &b_attrs };- let pbg = particle_bind_group(d, &pipeline, "particles", &[(0, ¶ms), (1, &b_sys), (7, &last), (8, translucent.as_ref().map_or(&no_trans, |t| &t.verts))], &written);+ let last = d.create_buffer(&wgpu::BufferDescriptor { label: Some("particles last"), size: last_bytes, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });+ let written = ParticleTargets { vertices: &b_vertices, prev_vertices: &b_prev, heap: &heap };+ let pbg = particle_bind_group(d, &pipeline, "particles", &[(0, ¶ms), (1, &b_sys), (7, &last)], &written);let nodes = scene.particles.iter().map(|p| p.seed).collect();let opaque = scene.particles.iter().any(|p| !p.translucent);let counts = scene.particles.iter().map(|p| p.count).collect();let translucent_sys = scene.particles.iter().map(|p| p.translucent).collect();let hidden = std::cell::RefCell::new(scene.particles.iter().map(|p| if p.hidden { Hidden::Idle } else { Hidden::Shown }).collect());- Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, last, no_trans, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque, counts, translucent: translucent_sys, hidden })+ Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, last, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque, counts, translucent: translucent_sys, hidden })}_ => None,};@@ -2810,7 +2852,7 @@ impl Gpu {.map(|ps| {let c = &ps.collide;let flags = u32::from(c.plane.is_some()) | if c.voxels { 2 } else { 0 };- GpuParticleSystemGpu { a: [ps.final_first, ps.capacity, ps.object, ps.program], b: [ps.seed, dynamic_first as u32, 0, 0], c: [ps.pivot[0], ps.pivot[1], ps.pivot[2], flags as f32], d: [c.plane.unwrap_or(0.0), c.restitution, c.friction, 0.0], e: [0; 4], p: ps.params }+ GpuParticleSystemGpu { a: [vertex_of(ps.final_first, false), ps.capacity, ps.object, ps.program], b: [ps.seed, ix.dynamic.0, 0, 0], c: [ps.pivot[0], ps.pivot[1], ps.pivot[2], flags as f32], d: [c.plane.unwrap_or(0.0), c.restitution, c.friction, 0.0], e: [0; 4], p: ps.params }}).collect();let table = buf("gpu particle systems", bytemuck::cast_slice(&systems), edit);@@ -2818,7 +2860,7 @@ impl Gpu {let state = d.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu particle states"), size: states, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let spawns = d.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu particle spawns"), size: (MAX_SPAWNS * 32) as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu particle params"), size: 80, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let last = d.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu particles last"), size: b_prev.size(), usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });+ let last = d.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu particles last"), size: last_bytes, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let occ = scene.voxel_occupancy.as_ref().filter(|_| scene.gpu_particles.iter().any(|p| p.collide.voxels)).map(|o| o.read().unwrap().clone());let (grid, grid_o, grid_n) = match &occ {Some(o) => (buf("voxel occupancy", bytemuck::cast_slice(&o.words), edit), [o.origin[0], o.origin[1], o.origin[2], o.cell], [o.dims[0], o.dims[1], o.dims[2], o.row_words() as u32]),@@ -2827,24 +2869,19 @@ impl Gpu {if let Some(o) = &scene.voxel_occupancy {o.write().unwrap().dirty.clear();}- let written = ParticleTargets { verts: &b_verts, prev_verts: &b_prev, blas_verts: &a.verts, heap: &heap, attrs: &b_attrs };+ let written = ParticleTargets { vertices: &b_vertices, prev_vertices: &b_prev, heap: &heap };let bg = particle_bind_group(d, &pipeline, "gpu particles", &[(0, ¶ms), (1, &table), (7, &last), (8, &state), (9, &spawns), (10, &grid)], &written);let host = scene.gpu_particles.iter().map(|ps| (0u32, 0.0f32, ps.rate)).collect();let sm = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("stamp"), source: wgpu::ShaderSource::Wgsl(STAMP_WGSL.into()) });let sp = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("stamp"), layout: None, module: &sm, entry_point: Some("stamp"), compilation_options: Default::default(), cache: self.cache() });- let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, &a.verts), wgpu::BindGroupEntry { binding: 1, resource: a.tlas.as_binding() }] });+ let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, &b_vertices), wgpu::BindGroupEntry { binding: 1, resource: a.tlas.as_binding() }] });Some(GpuParticlesGpu { pipeline, stamp: (sp, sbg), bg, params, table, last, state, spawns, grid, systems: std::cell::RefCell::new(systems), host: std::cell::RefCell::new(host), nodes: scene.gpu_particles.iter().map(|p| p.node).collect(), max_cap: scene.gpu_particles.iter().map(|p| p.capacity).max().unwrap_or(0), frame: std::cell::Cell::new(0), fresh: std::cell::Cell::new(true), grid_o, grid_n })}_ => None,};// The skinning pass, a job each mesh that deforms: under hardware traversal (it writes the BLASes' input too),// and under software traversal where such a mesh is a unit.- let skin = match (&accel, &scene.units) {- _ if scene.retained.skinned.is_empty() => None,- (Some(a), _) => Some(self.skin_pass(scene, a.pool_first, &b_verts, &b_attrs, Some(&a.verts))),- (None, Some(_)) => Some(self.skin_pass(scene, groups.iter().sum(), &b_verts, &b_attrs, None)),- _ => None,- };+ let skin = (!scene.retained.skinned.is_empty() && (accel.is_some() || scene.units.is_some())).then(|| self.skin_pass(scene, &b_vertices, scene.units.is_some().then_some((&words.buffer, &bg_parts.leaves))));self.queue.submit([]);self.device.poll(wgpu::PollType::wait_indefinitely())?;timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));@@ -2852,10 +2889,10 @@ impl Gpu {self.save_pipeline_cache();// (What moves emitters after the load needs hardware ray tracing: triangles reposed in place, the particle passes.)let fills = match &accel {- Some(_) => EmitterFills { moved: self.emitter_fill(&emitter_runs.moved, &b_verts, &heap), particles: self.emitter_fill(&emitter_runs.particles, &b_verts, &heap) },+ Some(_) => EmitterFills { moved: self.emitter_fill(&emitter_runs.moved, &b_vertices, &heap, &words), particles: self.emitter_fill(&emitter_runs.particles, &b_vertices, &heap, &words) },None => EmitterFills::default(),};- Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, skin, fills, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })+ Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, vertices: b_vertices, prev_vertices: b_prev, accel, units: scene.units.clone(), particles, gpu_particles, skin, fills, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })}/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None@@ -2877,24 +2914,25 @@ impl Gpu {}}- /// Bytes Metal allocates for a triangle BLAS over the (first vertex, vertex count) geometries of `verts`- /// (non-indexed Float32x3 flagged opaque, as every triangle BLAS here; None on other backends).- fn tri_blas_bytes(&self, verts: &wgpu::Buffer, parts: &[(u32, u32)]) -> Option<u64> {+ /// Bytes Metal allocates for a triangle BLAS over geometries (first vertex, vertices, first triangle, triangles) of+ /// the vertices and the indices from word `index_first` of `words` (flagged opaque, as every triangle+ /// BLAS here; None on other backends).+ fn tri_blas_bytes(&self, vertices: &wgpu::Buffer, words: &wgpu::Buffer, index_first: u32, parts: &[(u32, u32, u32, u32)]) -> Option<u64> {#[cfg(target_vendor = "apple")]{use wgpu::hal::{api::Metal, Device as _};let d = unsafe { self.device.as_hal::<Metal>() }?;- let b = unsafe { verts.as_hal::<Metal>() }?;+ let (b, i) = unsafe { (vertices.as_hal::<Metal>()?, words.as_hal::<Metal>()?) };let entries = wgpu::hal::AccelerationStructureEntries::Triangles(parts.iter()- .map(|&(first_vertex, vertex_count)| wgpu::hal::AccelerationStructureTriangles {+ .map(|&(first_vertex, vertex_count, first, count)| wgpu::hal::AccelerationStructureTriangles {vertex_buffer: Some(&*b),vertex_format: wgpu::VertexFormat::Float32x3,first_vertex,vertex_count,- vertex_stride: 12,- indices: None,+ vertex_stride: VERTEX_STRIDE,+ indices: Some(wgpu::hal::AccelerationStructureTriangleIndices { format: wgpu::IndexFormat::Uint32, buffer: Some(&*i), offset: (index_first + first * 3) * 4, count: count * 3 }),transform: None,flags: wgpu::hal::AccelerationStructureGeometryFlags::OPAQUE,})@@ -2905,7 +2943,7 @@ impl Gpu {}#[allow(unreachable_code)]{- let _ = (verts, parts);+ let _ = (vertices, words, index_first, parts);None}}@@ -2923,7 +2961,12 @@ impl Gpu {let color_bytes = if colors.is_empty() { 0 } else { colors.len() + room_tris * 12 };let rows: &[u8] = bytemuck::cast_slice(&scene.rows);let row_bytes = if rows.is_empty() && room_rows == 0 { 0 } else { rows.len() + room_rows * 16 };- let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64, row_bytes as u64];+ // The triangles' indices (one at least: the triangle a tree over nothing names, of vertex 0), and the rows of+ // those that have one (no mesh's triangle has, nor do those an edit places).+ let ix = &scene.indexed;+ let tri_rows = ix.gpu_rows();+ let (index_bytes, tri_bytes) = ((ix.indices.len() + room_tris).max(1) * 12, tri_rows.len().max(1) * 16);+ let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64, row_bytes as u64, index_bytes as u64, tri_bytes as u64];let (used, limit) = (Heap::<Stream>::size_for(&sizes(0)), self.device.limits().max_storage_buffer_binding_size as u64);if used > limit {return Err(anyhow!("procedural geometry: {} MB of data, more than this device binds in one buffer ({} MB)", used >> 20, limit >> 20));@@ -2934,26 +2977,32 @@ impl Gpu {let blob_at = (head * 4) as u64;let blob_bytes = (blob_words * 4) as u64;let key = l.map(|l| l.key());+ // (The BLASes are built from the indices' section.)+ let usage = crate::heap::USAGE | if self.hwrt { wgpu::BufferUsages::BLAS_INPUT } else { wgpu::BufferUsages::empty() };let mut cache = self.proc_cache.lock().unwrap();let reuse = cache.as_ref().filter(|c| blob_bytes > 0 && Some(&c.key) == key.as_ref() && c.bytes == blob_bytes);// Reused blobs: the small parts written through the queue, the blobs copied on the GPU (a mapped buffer of the// whole size would be zero-filled on the CPU first: 17 ms for 256 MB). New ones: written into the mapping.let heap = match (reuse, l) {(Some(c), Some(l)) => {- let heap = Heap::new(&self.device, &sizes);+ let heap = Heap::new_with(&self.device, &sizes, usage);heap.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));heap.write(&self.queue, Stream::Procs, 0, bytemuck::cast_slice(&l.head));heap.write(&self.queue, Stream::VertexColors, 0, colors);heap.write(&self.queue, Stream::Rows, 0, rows);+ heap.write(&self.queue, Stream::Indices, 0, bytemuck::cast_slice(&ix.indices));+ heap.write(&self.queue, Stream::Triangles, 0, bytemuck::cast_slice(&tri_rows));let mut e = self.device.create_command_encoder(&Default::default());e.copy_buffer_to_buffer(&c.buf, c.offset, &heap.buffer, heap.at(Stream::Procs) + blob_at, c.bytes);self.queue.submit([e.finish()]);heap}- _ => Heap::filled(&self.device, &sizes, |put| {+ _ => Heap::filled_with(&self.device, &sizes, usage, |put| {put(Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));put(Stream::VertexColors, 0, colors);put(Stream::Rows, 0, rows);+ put(Stream::Indices, 0, bytemuck::cast_slice(&ix.indices));+ put(Stream::Triangles, 0, bytemuck::cast_slice(&tri_rows));let Some(l) = l else { return };put(Stream::Procs, 0, bytemuck::cast_slice(&l.head));for (blob, off) in &l.blobs {@@ -3042,8 +3091,8 @@ impl Gpu {}}- fn emitter_fill_bind_group(&self, runs: &wgpu::Buffer, verts: &wgpu::Buffer, heap: &Heap<Table>) -> wgpu::BindGroup {- let entries = [buffer_entry(0, runs), buffer_entry(1, verts), wgpu::BindGroupEntry { binding: 2, resource: heap.binding(Table::EmitterTris) }, wgpu::BindGroupEntry { binding: 3, resource: heap.binding(Table::Instances) }];+ fn emitter_fill_bind_group(&self, runs: &wgpu::Buffer, vertices: &wgpu::Buffer, heap: &Heap<Table>, words: &Heap<Stream>) -> wgpu::BindGroup {+ let entries = [buffer_entry(0, runs), buffer_entry(1, vertices), wgpu::BindGroupEntry { binding: 2, resource: heap.binding(Table::EmitterTris) }, wgpu::BindGroupEntry { binding: 3, resource: heap.binding(Table::Instances) }, wgpu::BindGroupEntry { binding: 4, resource: words.binding(Stream::Indices) }];self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("emitter fill"), layout: &self.emitter_fill_pipeline().get_bind_group_layout(0), entries: &entries })}@@ -3055,16 +3104,16 @@ impl Gpu {}/// The fill of `runs` of the light list (none: no fill).- fn emitter_fill(&self, runs: &[[u32; 2]], verts: &wgpu::Buffer, heap: &Heap<Table>) -> Option<EmitterFill> {+ fn emitter_fill(&self, runs: &[[u32; 2]], vertices: &wgpu::Buffer, heap: &Heap<Table>, words: &Heap<Stream>) -> Option<EmitterFill> {let longest = runs.iter().map(|r| r[1]).max()?;let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitter runs"), size: (runs.len() * 8) as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });self.queue.write_buffer(&buffer, 0, bytemuck::cast_slice(runs));- Some(EmitterFill { bg: self.emitter_fill_bind_group(&buffer, verts, heap), runs: buffer, count: runs.len() as u32, longest })+ Some(EmitterFill { bg: self.emitter_fill_bind_group(&buffer, vertices, heap, words), runs: buffer, count: runs.len() as u32, longest })}/// `runs` of the light list taken again now (the instances an edit just moved: their records are queued).pub fn fill_emitter_runs(&self, up: &Uploaded, runs: &[[u32; 2]]) {- let Some(f) = self.emitter_fill(runs, &up.verts, &up.heap) else { return };+ let Some(f) = self.emitter_fill(runs, &up.vertices, &up.heap, &up.words) else { return };let mut e = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitter fill") });self.fill_emitters(&f, &mut e);self.queue.submit([e.finish()]);@@ -3420,15 +3469,12 @@ impl Gpu {}/// The BLAS vertex buffer grown to `bytes` (`grown`).- pub fn grow_blas_verts(&self, accel: &mut Accel, bytes: u64) {- accel.verts = self.grown(&accel.verts, bytes, "blas_verts");- }-/// Mesh `k` (one an edit no longer draws) made again over `count` triangles from `first`: a new BLAS in its slot.pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) {let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);accel.meshes[k as usize] = blas;accel.mesh_geo[k as usize] = geo;+ accel.mesh_verts[k as usize] = (mesh.vfirst, mesh.vcount);}fn mesh_blas_for(&self, accel: &Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> (wgpu::Blas, (Vec<(u32, u32)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {@@ -3438,9 +3484,9 @@ impl Gpu {.iter().map(|&(_, c)| wgpu::BlasTriangleGeometrySizeDescriptor {vertex_format: wgpu::VertexFormat::Float32x3,- vertex_count: c * 3,- index_format: None,- index_count: None,+ vertex_count: mesh.vcount.max(1),+ index_format: Some(wgpu::IndexFormat::Uint32),+ index_count: Some(c * 3),flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,}).collect();@@ -3457,6 +3503,7 @@ impl Gpu {let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);accel.meshes.push(blas);accel.mesh_geo.push(geo);+ accel.mesh_verts.push((mesh.vfirst, mesh.vcount));accel.meshes.len() as u32 - 1}@@ -3489,11 +3536,10 @@ impl Gpu {let p = b.parts;let mut entries = vec![buffer_entry(0, b.params),- buffer_entry(1, b.verts),- buffer_entry(2, b.attrs),+ buffer_entry(1, b.vertices),buffer_entry(4, &b.heap.buffer),buffer_entry(5, &b.words.buffer),- buffer_entry(6, b.prev_verts),+ buffer_entry(6, b.prev_vertices),view(7, &p.tex_view),wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::Sampler(&p.sampler) },view(9, &p.env_view),@@ -3501,6 +3547,7 @@ impl Gpu {buffer_entry(11, b.accum),];if !self.hwrt {+ entries.push(buffer_entry(2, &p.leaves));entries.push(buffer_entry(3, &p.nodes));}if !self.merged && !self.whole_tables {@@ -3522,19 +3569,27 @@ impl Gpu {/// live/edits.rs): the kernel's, the light list's fills', the skinning pass's and the particle passes'.pub fn rebind_scene(&self, up: &mut Uploaded) {for f in [&mut up.fills.moved, &mut up.fills.particles].into_iter().flatten() {- f.bg = self.emitter_fill_bind_group(&f.runs, &up.verts, &up.heap);+ f.bg = self.emitter_fill_bind_group(&f.runs, &up.vertices, &up.heap, &up.words);}if let Some(k) = &mut up.skin {- // (The BLASes' input, or what stands there under software traversal.)- if let Some(blas) = up.accel.as_ref().map(|a| &a.verts).or(k.no_blas.as_ref()) {- k.bg = skin_bind_group(&self.device, &k.pipeline, [&k.params, &k.blocks, &k.table, &k.corners, &k.palette], &up.verts, &up.attrs, blas);+ k.bg = skin_bind_group(&self.device, &k.pipeline, [&k.params, &k.blocks, &k.table, &k.corners, &k.palette], &up.vertices);+ if let Some(l) = &mut k.leaves {+ l.bg = Some(leaf_gather_bind_group(&self.device, l, &up.vertices, &up.words.buffer, &up.bg_parts.leaves));}}- up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, verts: &up.verts, attrs: &up.attrs, heap: &up.heap, words: &up.words, prev_verts: &up.prev_verts, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });- let Some(a) = &up.accel else { return };- let written = ParticleTargets { verts: &up.verts, prev_verts: &up.prev_verts, blas_verts: &a.verts, heap: &up.heap, attrs: &up.attrs };+ if let Some(a) = &mut up.accel {+ (a.vertices, a.indices, a.index_first) = (up.vertices.clone(), up.words.buffer.clone(), (up.words.at(Stream::Indices) / 4) as u32);+ }+ if let Some(t) = &mut up.translucent {+ t.vertices = up.vertices.clone();+ }+ up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, vertices: &up.vertices, heap: &up.heap, words: &up.words, prev_vertices: &up.prev_vertices, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });+ if up.accel.is_none() {+ return;+ }+ let written = ParticleTargets { vertices: &up.vertices, prev_vertices: &up.prev_vertices, heap: &up.heap };if let Some(p) = &mut up.particles {- p.bg = particle_bind_group(&self.device, &p.pipeline, "particles", &[(0, &p.params), (1, &p.table), (7, &p.last), (8, up.translucent.as_ref().map_or(&p.no_trans, |t| &t.verts))], &written);+ p.bg = particle_bind_group(&self.device, &p.pipeline, "particles", &[(0, &p.params), (1, &p.table), (7, &p.last)], &written);}if let Some(p) = &mut up.gpu_particles {p.bg = particle_bind_group(&self.device, &p.pipeline, "gpu particles", &[(0, &p.params), (1, &p.table), (7, &p.last), (8, &p.state), (9, &p.spawns), (10, &p.grid)], &written);@@ -3542,27 +3597,27 @@ impl Gpu {}/// The skinning pass of `scene`: its pipeline, the models' corners, a job each skinned model, and room for a frame's- /// work and every job's palette.- fn skin_pass(&self, scene: &Scene, pool_first: usize, verts: &wgpu::Buffer, attrs: &wgpu::Buffer, blas_verts: Option<&wgpu::Buffer>) -> SkinGpu {+ /// work and every job's palette. `tree`: software traversal's words' heap and leaves, for the pass that takes the+ /// leaves again.+ fn skin_pass(&self, scene: &Scene, vertices: &wgpu::Buffer, tree: Option<(&wgpu::Buffer, &wgpu::Buffer)>) -> SkinGpu {let d = &self.device;let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("skin"), source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/skin.wgsl").into()) });- let blas = [("BLAS", if blas_verts.is_some() { 1.0 } else { 0.0 })];- let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("skin"), layout: None, module: &module, entry_point: Some("main"), compilation_options: wgpu::PipelineCompilationOptions { constants: &blas, ..Default::default() }, cache: self.cache() });- let no_blas = blas_verts.is_none().then(|| d.create_buffer(&wgpu::BufferDescriptor { label: Some("skin no blas"), size: 64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false }));- let blas_verts = blas_verts.or(no_blas.as_ref()).unwrap();+ let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("skin"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: self.cache() });+ // The models' vertices one model after another (`indexed::Indexed::skins`).+ let ix = &scene.indexed;let mut source_first = vec![];let mut at = 0u32;- for source in &scene.skin_sources {+ for (vertices, _) in &ix.skins {source_first.push(at);- at += source.len() as u32;+ at += vertices.len() as u32;}- let corners: Vec<crate::skin::SkinCorner> = scene.skin_sources.iter().flatten().flatten().copied().collect();+ let corners: Vec<crate::skin::SkinCorner> = ix.skins.iter().flat_map(|s| s.0.iter().copied()).collect();let (mut jobs, mut matrices, mut blocks) = (vec![], 0u32, 0u32);for g in &scene.retained.skinned {- let m = &scene.meshes[g.mesh as usize];- jobs.push((SkinJob { first: pool_first as u32 + m.first, count: m.count, source: source_first[g.source as usize], palette: matrices }, g.palette_len));+ let (first, count) = ix.meshes[g.mesh as usize];+ jobs.push((SkinJob { first, count, source: source_first[g.source as usize], palette: matrices }, g.palette_len));matrices += g.palette_len;- blocks += m.count.div_ceil(SKIN_BLOCK);+ blocks += count.div_ceil(SKIN_BLOCK);}let table: Vec<SkinJob> = jobs.iter().map(|j| j.0).collect();let storage = wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST;@@ -3571,8 +3626,19 @@ impl Gpu {let (b_corners, b_table) = (init("skin corners", bytemuck::cast_slice(&corners)), init("skin jobs", bytemuck::cast_slice(&table)));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, [¶ms, &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, source_first, palette_end: matrices, no_blas }+ let bg = skin_bind_group(d, &pipeline, [¶ms, &b_blocks, &b_table, &b_corners, &palette], vertices);+ let leaves = tree.map(|(words, leaves)| {+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("leaf gather"), source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/leaf_gather.wgsl").into()) });+ let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("leaf gather"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: self.cache() });+ // (A mesh's triangles follow the world-space ones: `Indexed::pool_first`.)+ let jobs: Vec<LeafJob> = scene.retained.skinned.iter().map(|g| { let m = &scene.meshes[g.mesh as usize]; LeafJob { first: ix.pool_first + m.first, count: m.count, vertex: ix.meshes[g.mesh as usize].0, spare: 0 } }).collect();+ let blocks: u64 = jobs.iter().map(|j| j.count.div_ceil(SKIN_BLOCK) as u64).sum();+ let (params, b_blocks, b_jobs) = (room("leaf gather params", 16, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST), room("leaf gather blocks", blocks * 8, storage), init("leaf gather jobs", bytemuck::cast_slice(&jobs)));+ let mut l = LeafGather { pipeline, bg: None, params, blocks: b_blocks, table: b_jobs, jobs };+ l.bg = Some(leaf_gather_bind_group(d, &l, vertices, words, leaves));+ l+ });+ SkinGpu { pipeline, bg, params, blocks: b_blocks, table: b_table, corners: b_corners, palette, jobs, source_first, palette_end: matrices, leaves }}/// Skins the meshes of `work` (a job and its pose's palette each) on the GPU: their triangles, shading attributes@@ -3602,6 +3668,19 @@ impl Gpu {pass.set_bind_group(0, &s.bg, &[]);pass.dispatch_workgroups(n.min(SKIN_ROW), n.div_ceil(SKIN_ROW), 1);}+ // Software traversal: the same meshes' leaves, from the vertices just written.+ if let Some(l) = &s.leaves {+ let blocks: Vec<[u32; 2]> = work.iter().flat_map(|(job, _)| (0..l.jobs[*job as usize].count.div_ceil(SKIN_BLOCK)).map(|b| [*job, b * SKIN_BLOCK])).collect();+ if !blocks.is_empty() {+ let n = blocks.len() as u32;+ self.queue.write_buffer(&l.blocks, 0, bytemuck::cast_slice(&blocks));+ self.queue.write_buffer(&l.params, 0, bytemuck::cast_slice(&[n, (up.words.at(Stream::Indices) / 4) as u32, 0, 0]));+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("leaf gather"), timestamp_writes: None });+ pass.set_pipeline(&l.pipeline);+ pass.set_bind_group(0, l.bg.as_ref().expect("made with the pass"), &[]);+ pass.dispatch_workgroups(n.min(SKIN_ROW), n.div_ceil(SKIN_ROW), 1);+ }+ }self.queue.submit([e.finish()]);true}@@ -3763,10 +3842,10 @@ impl Gpu {#[cfg(not(target_arch = "wasm32"))]/// Render `spp` samples. `base` holds everything except the per-dispatch sample index.#[allow(clippy::too_many_arguments)]- pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {+ pub fn render(&self, scene: &Scene, groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {let d = &self.device;let (w, h) = (scene.width, scene.height);- let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, emitter_tris, emitter_runs, light_tree, env, env_cdf, energy, timings)?;+ let up = self.upload(scene, &self.accum_buffer(w, h), groups, nodes, emitters, emitter_tris, emitter_runs, light_tree, env, env_cdf, energy, timings)?;let pipeline = self.pipeline(&up.kernel, false);// Particles: placed once, at the scene time and camera.if up.particles.is_some() {@@ -4271,6 +4350,7 @@ mod tests {}wesl_wgsl(include_str!("../shaders/grid_sim.wgsl"), &[], &[]);wesl_wgsl(include_str!("../shaders/skin.wgsl"), &[], &[]);+ wesl_wgsl(include_str!("../shaders/leaf_gather.wgsl"), &[], &[]);}/// The kernel is compiled with its loops bounded and nothing else checked, unless asked.@@ -4288,6 +4368,12 @@ mod tests {naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&module).expect("skin.wgsl validates");assert!(src.contains(&format!("@compute @workgroup_size({SKIN_BLOCK})")) && src.contains(&format!("const ROW: u32 = {SKIN_ROW}u;")));assert_eq!((std::mem::size_of::<SkinJob>(), std::mem::size_of::<crate::skin::SkinCorner>(), std::mem::size_of::<crate::skin::PaletteRows>()), (16, 64, 48));+ // (The pass that takes the leaves again after it: the same blocks and rows.)+ let src = include_str!("../shaders/leaf_gather.wgsl");+ let module = naga::front::wgsl::parse_str(src).expect("leaf_gather.wgsl parses");+ naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&module).expect("leaf_gather.wgsl validates");+ assert!(src.contains(&format!("@compute @workgroup_size({SKIN_BLOCK})")) && src.contains(&format!("const ROW: u32 = {SKIN_ROW}u;")));+ assert_eq!(std::mem::size_of::<LeafJob>(), 16);}/// Each switch changes what it says, under both traversals (that every combination is valid WGSL:diff --git a/renderer/src/heap.rs b/renderer/src/heap.rsindex 6c9cd00..242202c 100644--- a/renderer/src/heap.rs+++ b/renderer/src/heap.rs@@ -74,10 +74,15 @@ pub enum Stream {VertexColors,/// The instances' rows (scene.rs `Row`): four words a section of an instance's mesh.Rows,+ /// The triangles' vertices (indexed.rs): three words a triangle, in the triangles' GPU order. What a hit and a+ /// candidate's test read, and what the BLASes are built from.+ Indices,+ /// The rows of the triangles that have one (`indexed::TriRow`, `Indexed::gpu_rows`): four words each.+ Triangles,}impl Section for Stream {- const COUNT: usize = 4;+ const COUNT: usize = 6;const UNIT: u64 = 4;const LABEL: &'static str = "words";fn index(self) -> usize {@@ -127,7 +132,7 @@ fn place(bytes: &[u64]) -> (Vec<u64>, Vec<u64>, u64) {(at, cap, size)}-const USAGE: wgpu::BufferUsages = wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST).union(wgpu::BufferUsages::COPY_SRC);+pub const USAGE: wgpu::BufferUsages = wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST).union(wgpu::BufferUsages::COPY_SRC);impl<S: Section> Heap<S> {/// The bytes of a heap whose sections hold `bytes` each.@@ -143,18 +148,28 @@ impl<S: Section> Heap<S> {/// A heap of zeros with sections of at least `bytes` each (`S::COUNT` of them), to be written through the queue.pub fn new(device: &wgpu::Device, bytes: &[u64]) -> Self {+ Self::new_with(device, bytes, USAGE)+ }++ /// `new` with a buffer of another usage (the words' heap is the BLASes' index buffer too), which it keeps as it+ /// grows.+ pub fn new_with(device: &wgpu::Device, bytes: &[u64], usage: wgpu::BufferUsages) -> Self {assert_eq!(bytes.len(), S::COUNT);let (at, cap, size) = place(bytes);- let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: false });+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage, mapped_at_creation: false });Heap { buffer, at, cap, _s: PhantomData }}/// The same, filled while it is made: `fill` is given `put(section, byte, data)`, which writes into the buffer's/// mapping (no copy through the queue).pub fn filled(device: &wgpu::Device, bytes: &[u64], fill: impl FnOnce(&mut dyn FnMut(S, u64, &[u8]))) -> Self {+ Self::filled_with(device, bytes, USAGE, fill)+ }++ pub fn filled_with(device: &wgpu::Device, bytes: &[u64], usage: wgpu::BufferUsages, fill: impl FnOnce(&mut dyn FnMut(S, u64, &[u8]))) -> Self {assert_eq!(bytes.len(), S::COUNT);let (at, cap, size) = place(bytes);- let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: true });+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage, mapped_at_creation: true });{let mut m = buffer.slice(..).get_mapped_range_mut().expect("mapped at creation");fill(&mut |s: S, byte: u64, data: &[u8]| {@@ -198,8 +213,15 @@ impl<S: Section> Heap<S> {/// The bytes of this heap with section `s` holding `bytes`.pub fn size_with(&self, s: S, bytes: u64) -> u64 {+ self.size_with_all(&[(s, bytes)])+ }++ /// The heap's size with each of `sections` holding its bytes.+ pub fn size_with_all(&self, sections: &[(S, u64)]) -> u64 {let mut want = self.cap.clone();- want[s.index()] = bytes;+ for &(s, bytes) in sections {+ want[s.index()] = bytes;+ }place(&want).2}@@ -207,10 +229,17 @@ impl<S: Section> Heap<S> {/// so writes queued after this land on the copy. The sections after it move: whoever holds the buffer or an/// offset (the scene's bind group, `Params`) reads them again.pub fn grow(&mut self, device: &wgpu::Device, q: &wgpu::Queue, s: S, bytes: u64) {+ self.grow_all(device, q, &[(s, bytes)]);+ }++ /// `grow` for several sections at once: one new buffer.+ pub fn grow_all(&mut self, device: &wgpu::Device, q: &wgpu::Queue, sections: &[(S, u64)]) {let mut want = self.cap.clone();- want[s.index()] = bytes;+ for &(s, bytes) in sections {+ want[s.index()] = bytes;+ }let (at, cap, size) = place(&want);- let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: false });+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: self.buffer.usage(), mapped_at_creation: false });let mut e = device.create_command_encoder(&Default::default());for k in 0..S::COUNT {e.copy_buffer_to_buffer(&self.buffer, self.at[k], &buffer, at[k], self.cap[k].min(cap[k]));diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rsnew file mode 100644index 0000000..7026437--- /dev/null+++ b/renderer/src/indexed.rs@@ -0,0 +1,390 @@+//! The scene's geometry as the GPU holds it: vertices kept once, a triangle three indices and a row. The build still+//! makes triangles with corners of their own (`Scene::tris`, `attrs`); what they share is found here, scope by scope:+//! a mesh's triangles share within the mesh, the still world-space triangles among themselves, and what a pass or the+//! CPU writes whole each frame (the dynamic world-space triangles, particles) has three vertices a triangle.++use crate::scene::GpuTriAttr;+use glam::Vec3A;+use std::collections::HashMap;+use std::hash::Hash;++/// `GpuTriAttr::x[0]` (bits): the triangle's tangent is its first corner's own (a file's, a particle's), not one made+/// from the triangle's UVs.+pub const OWN_TANGENT: u32 = 1;++/// A vertex, one record: (position, u), (normal, v), (tangent, hand). A tangent of zeros: the vertex has none. What a+/// hit reads of each of its triangle's three; an acceleration structure is built from the records' positions.+pub type Vertex = [[f32; 4]; 3];+pub const VERTEX_BYTES: usize = std::mem::size_of::<Vertex>();++/// The row of a triangle no instance places (a light's card, a particle's, a flattened scene's): its material, its+/// object, its flags (`scene::TRI_*`), its emitter entry + 1. A mesh's triangle needs none on the GPU: a ray's hit+/// says which section of its mesh it is in, and the rest is its instance's. (The build has one for every triangle,+/// a mesh's with its section and its index there: `Indexed::rows`.)+pub type TriRow = [u32; 4];++/// A triangle as a software tree keeps it in its leaves, the tree's own copy (hardware traversal's acceleration+/// structures keep theirs): (v0, id), (v1 - v0, id), (v2 - v0, -), so a candidate's test reads one place. The ids:+/// a world-space triangle's flags (`scene::TRI_*`), -; a mesh's section, and its index in the section. Three vec4s a+/// triangle, in the triangles' order (a tree's leaves name runs of it).+pub type Leaf = [[f32; 4]; 3];+pub const LEAF_BYTES: usize = std::mem::size_of::<Leaf>();++/// A triangle's leaf, of its corners.+pub fn leaf(p: [glam::Vec3A; 3], ids: [u32; 2]) -> Leaf {+ let (e1, e2) = (p[1] - p[0], p[2] - p[0]);+ [[p[0].x, p[0].y, p[0].z, f32::from_bits(ids[0])], [e1.x, e1.y, e1.z, f32::from_bits(ids[1])], [e2.x, e2.y, e2.z, 0.0]]+}++/// A scope's triangles as vertices and indices that count from the scope's first vertex.+#[derive(Clone, Debug, Default)]+pub struct Scope {+ pub vertices: Vec<Vertex>,+ pub indices: Vec<[u32; 3]>,+}++/// What a vertex's tangent slot is so far: no triangle's first corner yet; the first corner of triangles without a+/// tangent of their own (it stays zeros); the first corner of triangles with this one.+#[derive(Clone, Copy, PartialEq)]+enum Slot {+ Open,+ Without,+ Own([u32; 4]),+}++/// A triangle's corner `c` out of its attributes: (normal, uv).+fn corner(a: &GpuTriAttr, c: usize) -> ([f32; 3], [f32; 2]) {+ match c {+ 0 => ([a.n0[0], a.n0[1], a.n0[2]], [a.n0[3], a.n1[3]]),+ 1 => ([a.n1[0], a.n1[1], a.n1[2]], [a.n2[3], a.uv[0]]),+ _ => ([a.n2[0], a.n2[1], a.n2[2]], [a.uv[1], a.uv[2]]),+ }+}++/// The tangent a triangle's first corner carries, if it has one of its own.+fn own_tangent(a: &GpuTriAttr) -> Option<[f32; 4]> {+ (a.x[0].to_bits() & OWN_TANGENT != 0).then_some(a.t)+}++/// `n` triangles as shared vertices. `vertex(k, c)`: corner c of triangle k: what tells it from every other vertex,+/// and its (position, u) and (normal, v). `tangent(k)`: triangle k's own tangent, which its first vertex is to+/// carry. Two corners are one vertex where their keys are equal; a triangle's first corner is besides a vertex+/// whose tangent slot is its own (the same tangent, or none for both).+fn share<K: Hash + Eq>(n: usize, vertex: impl Fn(usize, usize) -> (K, [f32; 4], [f32; 4]), tangent: impl Fn(usize) -> Option<[f32; 4]>) -> Scope {+ let mut s = Scope { indices: Vec::with_capacity(n), ..Default::default() };+ let mut slots: Vec<Slot> = vec![];+ // (A key's vertices: one, but where triangles disagree on the tangent of a first corner.)+ let mut seen: HashMap<K, Vec<u32>> = HashMap::with_capacity(n);+ // (A triangle with a corner that is not finite: three times one vertex at the origin, a triangle without size,+ // which no ray meets. The BLASes are built from these positions.)+ let mut nowhere = None;+ for k in 0..n {+ if (0..3).any(|c| vertex(k, c).1[..3].iter().any(|x| !x.is_finite())) {+ let v = *nowhere.get_or_insert_with(|| {+ s.vertices.push([[0.0; 4]; 3]);+ slots.push(Slot::Without);+ slots.len() as u32 - 1+ });+ s.indices.push([v; 3]);+ continue;+ }+ let mut row = [0u32; 3];+ for (c, at) in row.iter_mut().enumerate() {+ let (key, p, nv) = vertex(k, c);+ let want = match (c, tangent(k)) {+ (0, Some(t)) => Slot::Own(t.map(f32::to_bits)),+ (0, None) => Slot::Without,+ _ => Slot::Open,+ };+ let list = seen.entry(key).or_default();+ let found = match want {+ Slot::Open => list.first().copied(),+ _ => list.iter().copied().find(|&v| slots[v as usize] == want).or_else(|| list.iter().copied().find(|&v| slots[v as usize] == Slot::Open)),+ };+ let v = found.unwrap_or_else(|| {+ s.vertices.push([p, nv, [0.0; 4]]);+ slots.push(Slot::Open);+ list.push(slots.len() as u32 - 1);+ slots.len() as u32 - 1+ });+ if want != Slot::Open {+ slots[v as usize] = want;+ if let Slot::Own(t) = want {+ s.vertices[v as usize][2] = t.map(f32::from_bits);+ }+ }+ *at = v;+ }+ s.indices.push(row);+ }+ s+}++/// A scope's triangles as shared vertices: corners with the same position, normal and UV (bit for bit) are one+/// vertex. (The attributes' tangent: see `share`.)+pub fn shared(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {+ share(+ tris.len(),+ |k, c| {+ let (p, (n, uv)) = (tris[k][c], corner(&attrs[k], c));+ let key = [p.x, p.y, p.z, n[0], n[1], n[2], uv[0], uv[1]].map(f32::to_bits);+ (key, [p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]])+ },+ |k| own_tangent(&attrs[k]),+ )+}++/// A skinned mesh's triangles as shared vertices: corners are one vertex where the model's corners they are skinned+/// from are the same (`source`, a triangle's three in the mesh's order: position, normal, tangent, joints and+/// weights, bit for bit) and their UVs are. A vertex's values are the build's pose's. One whose model has no normal+/// has a normal of zeros (its triangle's is made where it is hit), and none has a tangent that is not its own.+pub fn shared_skinned(source: &[[crate::skin::SkinCorner; 3]], tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {+ share(+ tris.len(),+ |k, c| {+ let (p, (n, uv), from) = (tris[k][c], corner(&attrs[k], c), source[k][c]);+ let mut key = [0u32; 18];+ key[..16].copy_from_slice(bytemuck::cast_slice(&[from]));+ (key[16], key[17]) = (uv[0].to_bits(), uv[1].to_bits());+ let n = if from.t[3].to_bits() & crate::skin::CORNER_NORMAL != 0 { n } else { [0.0; 3] };+ (key, [p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]])+ },+ |k| (source[k][0].t[3].to_bits() & crate::skin::CORNER_TANGENT != 0).then_some(attrs[k].t),+ )+}++/// The model's vertices a skinned mesh's are skinned from: for each vertex `scope` found (`shared_skinned`), the+/// corner of the model that was it first.+pub fn source_vertices(source: &[[crate::skin::SkinCorner; 3]], scope: &Scope) -> Vec<crate::skin::SkinCorner> {+ let mut out = vec![crate::skin::SkinCorner::default(); scope.vertices.len()];+ let mut seen = vec![false; out.len()];+ for (tri, from) in scope.indices.iter().zip(source) {+ for (c, &v) in tri.iter().enumerate() {+ if !std::mem::replace(&mut seen[v as usize], true) {+ out[v as usize] = from[c];+ }+ }+ }+ out+}++/// A scope's triangles with three vertices each: what is written whole, a triangle at a time.+pub fn apart(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {+ let mut s = Scope::default();+ for (k, (t, a)) in tris.iter().zip(attrs).enumerate() {+ let tangent = own_tangent(a).unwrap_or([0.0; 4]);+ // (One with a corner that is not finite: its three vertices at the origin, as `share` has it.)+ let finite = t.iter().all(|p| p.is_finite());+ for (c, p) in t.iter().enumerate() {+ let (n, uv) = corner(a, c);+ let p = if finite { *p } else { Vec3A::ZERO };+ s.vertices.push([[p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]], tangent]);+ }+ s.indices.push([k as u32 * 3, k as u32 * 3 + 1, k as u32 * 3 + 2]);+ }+ s+}++/// Triangles written whole as their vertices alone (their indices do not change): `corners`, three a triangle, and+/// their attributes; the vertices, as `apart` has them.+pub fn apart_vertices(corners: &[[f32; 3]], attrs: &[GpuTriAttr]) -> Vec<Vertex> {+ let mut out = Vec::with_capacity(corners.len());+ for (t, a) in corners.chunks_exact(3).zip(attrs) {+ let tangent = own_tangent(a).unwrap_or([0.0; 4]);+ let finite = t.iter().flatten().all(|x| x.is_finite());+ for (c, p) in t.iter().enumerate() {+ let (n, uv) = corner(a, c);+ let p = if finite { *p } else { [0.0; 3] };+ out.push([[p[0], p[1], p[2], uv[0]], [n[0], n[1], n[2], uv[1]], tangent]);+ }+ }+ out+}++/// The scene's geometry: every scope's vertices one after another, the triangles in the GPU's order.+#[derive(Clone, Debug, Default)]+pub struct Indexed {+ pub vertices: Vec<Vertex>,+ /// A triangle's three vertices: a mesh's count from the mesh's first vertex, a world-space triangle's from 0.+ pub indices: Vec<[u32; 3]>,+ pub rows: Vec<TriRow>,+ /// Software traversal: every triangle as its tree's leaf has it. Empty under hardware traversal.+ pub leaves: Vec<Leaf>,+ /// The meshes' first triangle: those before it are in world space. And the translucent particles' first (they+ /// lie after the meshes') and how many.+ pub pool_first: u32,+ pub translucent_tris: (u32, u32),+ /// By mesh (`Scene::meshes`): its first vertex and how many it has.+ pub meshes: Vec<(u32, u32)>,+ /// The world-space triangles' vertices: the first so many (the still ones', then those that move).+ pub flat: u32,+ /// The translucent particles' first vertex (three a triangle, after every mesh's).+ pub translucent: u32,+ /// By skin source (`Scene::skin_sources`): the model's vertices a mesh of it is skinned from (`source_vertices`)+ /// and its triangles' indices, which every mesh of the source has. Empty: no mesh is skinned from it.+ pub skins: Vec<(Vec<crate::skin::SkinCorner>, Vec<[u32; 3]>)>,+ /// The vertices that move (the dynamic world-space triangles', then the deforming meshes'): the first and how+ /// many. Their previous frame's positions are kept in this order.+ pub dynamic: (u32, u32),+}++impl Indexed {+ /// The rows the GPU holds: the world-space triangles', then the translucent particles' (found from `pool_first`+ /// on: the meshes' triangles lie between and have none).+ pub fn gpu_rows(&self) -> Vec<TriRow> {+ let (first, n) = (self.translucent_tris.0 as usize, self.translucent_tris.1 as usize);+ self.rows[..(self.pool_first as usize).min(self.rows.len())].iter().chain(self.rows.get(first..first + n).unwrap_or(&[])).copied().collect()+ }++ /// A scope's vertices after those there are, its triangles after those there are, their indices raised by `by`+ /// (0: they count from the scope's first vertex). The scope's first vertex.+ pub fn push(&mut self, s: Scope, by: u32) -> u32 {+ let first = self.vertices.len() as u32;+ self.vertices.extend(s.vertices);+ self.indices.extend(s.indices.iter().map(|i| i.map(|v| v + by)));+ first+ }++ /// Triangle `k` as the build had it, its vertices counted from `base`: its corners, and its attributes' normals,+ /// UVs and tangent (its first vertex's: zeros where that has none).+ pub fn triangle(&self, k: usize, base: u32) -> ([[f32; 3]; 3], [[f32; 3]; 3], [[f32; 2]; 3], [f32; 4]) {+ let v = self.indices[k].map(|i| (base + i) as usize);+ let [p, n] = [0, 1].map(|r| v.map(|i| [self.vertices[i][r][0], self.vertices[i][r][1], self.vertices[i][r][2]]));+ let uv = v.map(|i| [self.vertices[i][0][3], self.vertices[i][1][3]]);+ (p, n, uv, self.vertices[v[0]][2])+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use glam::{Vec2, Vec3};++ /// A sheet of `n` x `n` quads bent into a wave, as the build makes its triangles: every corner its own, with+ /// the normal and UV of its place on the sheet. `own`: each triangle has its first corner's tangent (a file's);+ /// else one made from its UVs.+ fn sheet(n: u32, own: bool) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>) {+ let at = |x: u32, y: u32| {+ let (u, v) = (x as f32 / n as f32, y as f32 / n as f32);+ let p = Vec3::new(u * 2.0, (u * 5.0).sin() * 0.3, v * 2.0);+ let normal = Vec3::new(-(u * 5.0).cos() * 0.75, 1.0, 0.0).normalize();+ let tangent = Vec3::new(1.0, (u * 5.0).cos() * 0.75, 0.0).normalize();+ (p, normal, Vec2::new(u, v), tangent)+ };+ let (mut tris, mut attrs) = (vec![], vec![]);+ for y in 0..n {+ for x in 0..n {+ for q in [[(x, y), (x + 1, y), (x + 1, y + 1)], [(x + 1, y + 1), (x, y + 1), (x, y)]] {+ let c = q.map(|(x, y)| at(x, y));+ tris.push(c.map(|c| Vec3A::from(c.0)));+ attrs.push(crate::scene::tri_attr(c.map(|c| c.0), c.map(|c| c.1), c.map(|c| c.2), own.then_some((c[0].3, -1.0)), 3));+ }+ }+ }+ (tris, attrs)+ }++ /// The scope's triangles are the build's, corner for corner and bit for bit: positions, normals, UVs, and the+ /// tangent of a triangle that has its own on its first vertex (zeros there for one that has none).+ fn same(what: &str, s: &Scope, tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) {+ let all = Indexed { vertices: s.vertices.clone(), indices: s.indices.clone(), ..Default::default() };+ assert_eq!(s.indices.len(), tris.len(), "{what}: a row of indices a triangle");+ let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();+ for (k, (t, a)) in tris.iter().zip(attrs).enumerate() {+ let (p, n, uv, tangent) = all.triangle(k, 0);+ for c in 0..3 {+ let (wn, wuv) = corner(a, c);+ assert_eq!((bits(&p[c]), bits(&n[c]), bits(&uv[c])), (bits(&t[c].to_array()), bits(&wn), bits(&wuv)), "{what}: triangle {k}, corner {c}");+ }+ assert_eq!(bits(&tangent), bits(&own_tangent(a).unwrap_or([0.0; 4])), "{what}: triangle {k}'s tangent on its first vertex");+ }+ }++ /// Triangles that the build made from a sheet of (n + 1)^2 vertices come back as that many, whether each has a+ /// tangent of its own (a file's: its first corner's) or none; and each triangle read through its indices is the+ /// build's. Written whole, they have three vertices each.+ #[test]+ fn a_scopes_triangles_share_their_vertices() {+ for own in [false, true] {+ let (tris, attrs) = sheet(12, own);+ let s = shared(&tris, &attrs);+ same(&format!("own tangents {own}"), &s, &tris, &attrs);+ assert_eq!(s.vertices.len(), 13 * 13, "own tangents {own}: the sheet's vertices, each once");+ let a = apart(&tris, &attrs);+ same(&format!("apart, own tangents {own}"), &a, &tris, &attrs);+ assert_eq!(a.vertices.len(), tris.len() * 3);+ }+ }++ /// Two triangles along an edge share its two corners; with another UV on one's side (a texture's seam) or another+ /// normal (a crease) each keeps its own.+ #[test]+ fn a_seam_or_a_crease_keeps_its_vertices() {+ let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)];+ let tris = vec![[p[0], p[1], p[2]].map(Vec3A::from), [p[2], p[1], p[3]].map(Vec3A::from)];+ let uv = |v: Vec3| Vec2::new(v.x, v.y);+ for (what, shift, normal, vertices) in [("one sheet", Vec2::ZERO, Vec3::Z, 4), ("a seam", Vec2::new(0.5, 0.0), Vec3::Z, 6), ("a crease", Vec2::ZERO, Vec3::new(0.6, 0.0, 0.8), 6)] {+ let attrs = vec![+ crate::scene::tri_attr([p[0], p[1], p[2]], [Vec3::Z; 3], [p[0], p[1], p[2]].map(uv), None, 3),+ crate::scene::tri_attr([p[2], p[1], p[3]], [normal; 3], [p[2], p[1], p[3]].map(|v| uv(v) + shift), None, 3),+ ];+ let s = shared(&tris, &attrs);+ same(what, &s, &tris, &attrs);+ assert_eq!(s.vertices.len(), vertices, "{what}: its vertices");+ }+ }++ /// A triangle with a corner that is not finite is three times one vertex at the origin (no ray meets it; a BLAS is+ /// built from these positions), shared or apart; the others are as they were.+ #[test]+ fn a_triangle_that_is_not_finite_has_no_size() {+ let (mut tris, attrs) = sheet(4, false);+ tris[5][1] = Vec3A::new(f32::NAN, 0.0, 0.0);+ tris[9][2] = Vec3A::new(0.0, f32::INFINITY, 0.0);+ for s in [shared(&tris, &attrs), apart(&tris, &attrs)] {+ assert!(s.vertices.iter().flat_map(|v| v[0]).all(|x| x.is_finite()), "every position is finite");+ for k in [5, 9] {+ let p = s.indices[k].map(|v| s.vertices[v as usize][0]);+ assert!(p[0][..3] == [0.0; 3] && p[0][..3] == p[1][..3] && p[1][..3] == p[2][..3], "triangle {k}: {p:?}");+ }+ let all = Indexed { vertices: s.vertices.clone(), indices: s.indices.clone(), ..Default::default() };+ for (k, t) in tris.iter().enumerate().filter(|(k, _)| ![5, 9].contains(k)) {+ assert_eq!(all.triangle(k, 0).0, t.map(|p| p.to_array()), "triangle {k}'s corners");+ }+ }+ let corners: Vec<[f32; 3]> = tris.iter().flatten().map(|p| p.to_array()).collect();+ assert!(apart_vertices(&corners, &attrs).iter().flat_map(|v| v[0]).all(|x| x.is_finite()));+ }++ /// Where triangles disagree about a first corner's tangent the corner is a vertex for each: a sheet whose+ /// triangles each have a tangent of their own that is no other's, one with and without a tangent by turns, and+ /// one where a corner is first met as a second corner and takes its tangent later.+ #[test]+ fn a_first_corner_has_its_triangles_tangent() {+ let (tris, mut attrs) = sheet(6, true);+ for (k, a) in attrs.iter_mut().enumerate() {+ a.t = [k as f32 + 1.0, 0.5, 0.25, 1.0];+ }+ let s = shared(&tris, &attrs);+ same("a tangent a triangle", &s, &tris, &attrs);+ // (Every vertex of the sheet but two corners is the first corner of one triangle or two.)+ assert!(s.vertices.len() > 7 * 7 && s.vertices.len() <= 7 * 7 + 6 * 6, "{} vertices", s.vertices.len());+ let (tris, mut attrs) = sheet(6, true);+ for (k, a) in attrs.iter_mut().enumerate() {+ if k % 2 == 1 {+ a.x[0] = 0.0;+ }+ }+ let s = shared(&tris, &attrs);+ same("with and without by turns", &s, &tris, &attrs);+ // Two triangles of one corner each way round: the corner is the first's second and the second's first.+ let p = [Vec3A::ZERO, Vec3A::X, Vec3A::Y];+ let a = |own: bool| crate::scene::tri_attr(p.map(Vec3::from), [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], own.then_some((Vec3::X, 1.0)), 0);+ // (The same triangle begun at its second corner.)+ let turned = |a: GpuTriAttr| GpuTriAttr { n0: [a.n1[0], a.n1[1], a.n1[2], a.n2[3]], n1: [a.n2[0], a.n2[1], a.n2[2], a.uv[0]], n2: [a.n0[0], a.n0[1], a.n0[2], a.uv[1]], uv: [a.uv[2], a.n0[3], a.n1[3], a.uv[3]], ..a };+ let (tris, attrs) = (vec![p, [p[1], p[2], p[0]]], vec![a(false), turned(a(true))]);+ let s = shared(&tris, &attrs);+ same("a corner met as a second corner first", &s, &tris, &attrs);+ assert_eq!(s.vertices.len(), 3, "three vertices: the shared corner took its tangent when a triangle began at it");+ }+}diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 20f09ef..5562c80 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -15,6 +15,7 @@ pub mod gpu;pub mod heap;#[cfg(not(target_arch = "wasm32"))]pub mod host;+pub mod indexed;pub mod live;pub mod ltree;pub mod merged;@@ -112,7 +113,7 @@ pub fn emitter_tri(k: usize, tri_verts: &[[f32; 4]], a: &scene::GpuTriAttr, mate}let c = v(0) + (e1 + e2) / 3.0;let moves = tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0;- Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal, in_tree: false, inst: NO_INST })+ Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal, in_tree: false, inst: NO_INST, part: 0 })}/// An emissive triangle of the emitter CDF: triangle (traversal order), material, object, area.@@ -134,6 +135,9 @@ pub struct EmitterTri {/// The instance that places its triangle (its record; the triangle is the mesh's, in model space), or `NO_INST`:/// a triangle in world space.pub inst: u32,+ /// Its section of that instance's mesh (0 without one): a mesh's triangle does not say which section it is of,+ /// so a light sample is told here, as a ray is by its hit.+ pub part: u32,}/// No instance (pathtrace.wgsl `NO_INST`).@@ -146,7 +150,8 @@ const _: () = assert!((ltree::PATH_BITS + 2) << ltree::PATH_BITS <= EMITTER_MOVE/// An emitter's triangle as the kernel's light sampling reads it (pathtrace.wgsl `EmitterTri`; `Table::EmitterTris`,/// entry i for `emitter_tris[i]`): in world space, the light list's own copy, so a sample reads no placement. v0, e1,/// e2 in world space; its triangle in the triangles' table (attributes); the instance that places it (`NO_INST`: the-/// triangle is in world space there too); where its weight is (`emitter_codes`) with `EMITTER_MOVES`.+/// triangle is in world space there too); where its weight is (`emitter_codes`) with `EMITTER_MOVES`; its section of+/// that instance's mesh. 64 bytes.#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]pub struct GpuEmitterTri {@@ -156,13 +161,17 @@ pub struct GpuEmitterTri {pub inst: u32,pub e2: [f32; 3],pub code: u32,+ pub part: u32,+ pub spare: [u32; 3],}impl GpuEmitterTri {/// `e`'s, from its triangle's rows (v0, e1, e2: `Prepared::tri_verts`), with path code `code`.pub fn new(e: &EmitterTri, rows: &[[f32; 4]], code: u32) -> GpuEmitterTri {let v = |r: usize| [rows[r][0], rows[r][1], rows[r][2]];- GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), inst: e.inst, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 } }+ // (As a hit has it: with an instance its section, without one its row, which is its triangle's.)+ let part = if e.inst == NO_INST { e.tri } else { e.part };+ GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), inst: e.inst, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 }, part, spare: [0; 3] }}/// As `new`, from its vertices.@@ -181,17 +190,17 @@ impl GpuEmitterTri {/// The emitters of an instance that has some (`count` of them: `scene::rows_emitters`, or a model's mesh's/// `InstMesh::emitters`): one a numbered/// triangle, in the numbers' order, each with its triangle as the instance places it. `tris`: the mesh's, in model-/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number and material, if-/// it emits; `record`: the instance's. A triangle of no area: no weight (area 0). A hidden instance's (an instanced+/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number, material and+/// section, if it emits; `record`: the instance's. A triangle of no area: no weight (area 0). A hidden instance's (an instanced/// object's copy not shown) keep their mesh's own area: its object has no power, so they weigh nothing, and the light/// tree has them (`switchable_power`) for when the copy is shown.-pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {- let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record };+pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {+ let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record, part: 0 };let mut out = vec![(dead, [glam::Vec3A::ZERO; 3]); count];for (k, t) in tris.iter().enumerate() {- let Some((slot, mat)) = numbered(k) else { continue };+ let Some((slot, mat, part)) = numbered(k) else { continue };let (area, c, w) = placed_emitter(inst, t, mat, materials);- out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c, ..dead }, w);+ out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c, part, ..dead }, w);}out}@@ -603,11 +612,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut}// (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).@@ -873,7 +877,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutlt_cam: [[0.0; 4]; 4],// (`gpu::Uploaded::place`, with the buffers.)table_first: [[0; 4]; 3],- word_first: [0; 4],+ word_first: [[0; 4]; 2],// (`gpu::KernelBufs::place`, with what is traced into.)live_first: [[0; 4]; 2],live_len: [0; 4],@@ -889,9 +893,114 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutfirst += u32::try_from(count).expect("more than 2^32 triangles");}let energy = energy_lut();+ let t = Instant::now();+ sc.indexed = index_geometry(sc, &tri_order, &tri_verts, &groups, pool_first, no_still);+ // Software traversal: the trees' leaves, every triangle as it was laid out for its tree above (v0, e1, e2), a+ // mesh's with its section and its index there, a world-space one's with its flags.+ if !hwrt {+ let pool = pool_first..pool_first + sc.pool_tris.len();+ let rows = &sc.indexed.rows;+ sc.indexed.leaves = tri_verts+ .chunks_exact(3)+ .enumerate()+ .map(|(k, t)| {+ let ids = if pool.contains(&k) { [rows[k][0], rows[k][3]] } else { [t[0][3].to_bits(), 0] };+ [[t[0][0], t[0][1], t[0][2], f32::from_bits(ids[0])], [t[1][0], t[1][1], t[1][2], f32::from_bits(ids[1])], [t[2][0], t[2][1], t[2][2], 0.0]]+ })+ .collect();+ }+ timings.push(("index_ms".into(), t.elapsed().as_secs_f64() * 1000.0));+ timings.push(("vertices".into(), sc.indexed.vertices.len() as f64));+ // An instance's triangles count their vertices from its mesh's first; the previous positions from the first+ // vertex that moves.+ // (A deforming mesh's previous positions: where its vertices are among those that move.)+ for (m, &(first, count)) in sc.meshes.iter_mut().zip(&sc.indexed.meshes) {+ (m.vfirst, m.vcount) = (first, count);+ }+ for (r, i) in sc.instances.iter_mut().enumerate() {+ i.verts = sc.indexed.meshes[i.mesh as usize].0;+ let deforms = sc.meshes[i.mesh as usize].deforms;+ i.prev = if deforms { i.verts - sc.indexed.dynamic.0 } else { 0 };+ i.bits = i.bits & !scene::INST_DEFORMS | if deforms { scene::INST_DEFORMS } else { 0 };+ let bits = sc.gpu_instances[r].n[1][3].to_bits();+ sc.gpu_instances[r].n[1][3] = f32::from_bits(bits & !scene::INST_DEFORMS | if deforms { scene::INST_DEFORMS } else { 0 });+ sc.gpu_instances[r].info[2] = i.verts;+ sc.gpu_instances[r].n[2][3] = f32::from_bits(i.prev);+ }+ params.word_first[1][2] = sc.indexed.dynamic.0;+ // (Hardware traversal: the translucent particles' rows follow the world-space triangles'.)+ params.word_first[1][3] = sc.indexed.pool_first;Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, moving_mats, tri_order }}+/// The scene's triangles, in the GPU's order (`tri_verts`, `sc.attrs`), as vertices and indices (indexed.rs). The+/// still world-space triangles share their vertices among themselves, the dynamic ones have three each (the CPU+/// writes them whole), each mesh of the pool shares within itself (the meshes in parallel; a skinned one by its+/// model's corners), the translucent particles' have three each. World-space triangles count their vertices from+/// 0, a mesh's from the mesh's first. The vertices lie in that order, so those that move are one run: the dynamic+/// world-space triangles', then the deforming meshes' (which are the pool's first).+fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], groups: &[usize; GROUPS], pool_first: usize, no_still: bool) -> indexed::Indexed {+ use rayon::prelude::*;+ let still: usize = groups[..4].iter().sum();+ let flat: Vec<[Vec3A; 3]> = order.iter().map(|&i| sc.tris[i as usize]).collect();+ let mut out = indexed::Indexed { meshes: vec![(0, 0); sc.meshes.len()], skins: vec![Default::default(); sc.skin_sources.len()], ..Default::default() };+ out.push(indexed::shared(&flat[..still], &sc.attrs[..still]), 0);+ let moving = out.vertices.len() as u32;+ out.push(indexed::apart(&flat[still..], &sc.attrs[still..pool_first]), moving);+ out.flat = out.vertices.len() as u32;+ // The pool, mesh by mesh as their triangles lie.+ let source_of: std::collections::HashMap<u32, u32> = sc.retained.skinned.iter().filter(|k| k.mesh != u32::MAX).map(|k| (k.mesh, k.source)).collect();+ let mut meshes: Vec<usize> = (0..sc.meshes.len()).filter(|&m| sc.meshes[m].count > 0).collect();+ meshes.sort_by_key(|&m| sc.meshes[m].first);+ // (A skinned mesh with its source: the model's vertices are found with its first mesh.)+ let scopes: Vec<(indexed::Scope, Option<u32>)> = meshes+ .par_iter()+ .map(|&m| {+ let im = sc.meshes[m];+ let r = im.first as usize..(im.first + im.count) as usize;+ let (tris, attrs) = (&sc.pool_tris[r.clone()], &sc.attrs[pool_first + r.start..pool_first + r.end]);+ match source_of.get(&(m as u32)).copied().filter(|&s| im.deforms && sc.skin_sources[s as usize].len() == tris.len()) {+ Some(s) => (indexed::shared_skinned(&sc.skin_sources[s as usize], tris, attrs), Some(s)),+ None => (indexed::shared(tris, attrs), None),+ }+ })+ .collect();+ let mut deforming = 0;+ for (&m, (s, source)) in meshes.iter().zip(scopes) {+ if let Some(k) = source.filter(|&k| out.skins[k as usize].1.is_empty()) {+ out.skins[k as usize] = (indexed::source_vertices(&sc.skin_sources[k as usize], &s), s.indices.clone());+ }+ // (A mesh's triangles follow the mesh's before it: the pool has no triangle that is no mesh's.)+ assert_eq!(out.indices.len(), pool_first + sc.meshes[m].first as usize, "the pool's triangles are its meshes', one after another");+ let n = s.vertices.len() as u32;+ out.meshes[m] = (out.push(s, 0), n);+ if sc.meshes[m].deforms {+ assert_eq!(out.meshes[m].0, moving + (pool_first - still) as u32 * 3 + deforming, "the deforming meshes are the pool's first");+ deforming += n;+ }+ }+ out.dynamic = (moving, (pool_first - still) as u32 * 3 + deforming);+ assert_eq!(out.indices.len(), pool_first + sc.pool_tris.len());+ // The triangle of a still tree over nothing: without area.+ if no_still {+ out.indices.push([0; 3]);+ }+ // The translucent particles' (what `tri_verts` has after the pool: under hardware traversal).+ if out.indices.len() < sc.attrs.len() {+ let first = out.indices.len();+ out.translucent = out.vertices.len() as u32;+ out.translucent_tris = (first as u32, sc.trans_tris.len() as u32);+ out.push(indexed::apart(&sc.trans_tris, &sc.attrs[first..]), out.translucent);+ }+ assert_eq!((out.indices.len(), tri_verts.len()), (sc.attrs.len(), sc.attrs.len() * 3), "a row of indices a triangle");+ // A row a triangle. One no instance places: its material, its object, its flags, its emitter + 1. A mesh's: its+ // section and its index in it (whether it deforms is its instance's to say: `scene::INST_DEFORMS`).+ let pool = pool_first..pool_first + sc.pool_tris.len();+ out.rows = sc.attrs.iter().enumerate().map(|(k, a)| if pool.contains(&k) { [a.uv[3].to_bits(), 0, 0, a.x[3].to_bits()] } else { [a.uv[3].to_bits(), a.x[1].to_bits(), tri_verts[k * 3][3].to_bits(), a.x[3].to_bits()] }).collect();+ out.pool_first = pool_first as u32;+ out+}+/// Instances as world-space triangles (software traversal), appended to the flattened ones with their objects./// Software traversal's units (units.rs): a tree for each instanced mesh that keeps its shape, its triangles (and/// what goes with them: attributes, vertex colours) put in the tree's order. None: no units (a mesh no tree can be@@ -1433,7 +1542,7 @@ mod light_lod_tests {// the one a load with all of them on builds: the plain build's, its powers summed bottom-up.let mats = [scene::GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }];let tris: Vec<EmitterTri> = (0..600u32)- .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: NO_INST })+ .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: NO_INST, part: 0 }).collect();let verts: Vec<[f32; 4]> = (0..600).flat_map(|i| [[2.0 * i as f32, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]).collect();let (off, on) = ([[0.0, 0.0, 0.0, 1.0], [0.0; 4]], [[0.0, 0.0, 0.0, 1.0]; 2]);@@ -1466,7 +1575,7 @@ mod light_lod_tests {let mut unit = || (rnd() >> 8) as f32 / (1 << 24) as f32;let mats: Vec<scene::GpuMaterial> = (0..4).map(|k| scene::GpuMaterial { emissive: [k as f32 * 3.0, k as f32, 0.5 * k as f32, 0.0], ..Default::default() }).collect();let tris: Vec<EmitterTri> = (0..3000)- .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false, inst: NO_INST })+ .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false, inst: NO_INST, part: 0 }).collect();let (t, total, _) = emitter_cdf(&tris, &emitter_order(&tris, None), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());let n = tris.len() as u32;@@ -1651,6 +1760,71 @@ mod units_tests {agree(&world(true), (3000, 400, 2000));}+ /// `prepare`'s vertices and indices (indexed.rs) are its triangles: every triangle read through its indices (a+ /// mesh's from the mesh's first vertex, a world-space one's from 0) has the corners, the edges, the normals and+ /// the UVs the kernel's arrays have for it, bit for bit, the tangent of one that has its own, and its row's four+ /// words. Flattened, with units, and as hardware traversal has the scene; with two posed skinned models. A mesh's+ /// vertices are fewer than its triangles' corners (the ring: 82 for 80 triangles), and the vertices that move are+ /// one run. No GPU.+ #[test]+ fn the_indexed_geometry_is_the_scenes_triangles() {+ let mut w = world(true);+ for (id, x) in [(30, -0.7), (31, 0.7)] {+ let pose = crate::desc::Animation { clip: "bend".into(), time: 0.25 * (id - 29) as f32, r#loop: true, nodes: Default::default() };+ w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/skin-blend.glb".into(), nodes: None, animation: Some(pose), functions: vec![] }, true, false).unwrap();+ w.set_transform(id, Vec3::new(x, -1.0, 0.8), Quat::IDENTITY, Vec3::splat(2.0)).unwrap();+ }+ for (what, hwrt, units) in [("flattened", false, false), ("units", false, true), ("hardware traversal", true, false)] {+ let mut sc = scene::build(&w, std::path::Path::new(".."), &default_presets_dir(), None).unwrap();+ let p = prepare_as(hwrt, units, &mut sc, &mut vec![]);+ let x = &sc.indexed;+ assert_eq!((x.indices.len(), x.rows.len()), (sc.attrs.len(), sc.attrs.len()), "{what}");+ // (A pool triangle's mesh: its vertices count from the mesh's first.)+ let pool_first = sc.attrs.len() - sc.pool_tris.len() - sc.trans_tris.len() * usize::from(hwrt) - usize::from(sc.units.is_some() && sc.tris.is_empty());+ let base = |k: usize| sc.meshes.iter().zip(&x.meshes).find(|(m, _)| m.count > 0 && (pool_first + m.first as usize..pool_first + (m.first + m.count) as usize).contains(&k)).map_or(0, |(_, v)| v.0);+ let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::<Vec<_>>();+ for (k, a) in sc.attrs.iter().enumerate() {+ let (q, n, uv, tangent) = x.triangle(k, base(k));+ let v = |r: usize| [p.tri_verts[k * 3 + r][0], p.tri_verts[k * 3 + r][1], p.tri_verts[k * 3 + r][2]];+ let edge = |c: usize| [q[c][0] - q[0][0], q[c][1] - q[0][1], q[c][2] - q[0][2]];+ assert_eq!((bits(&q[0]), bits(&edge(1)), bits(&edge(2))), (bits(&v(0)), bits(&v(1)), bits(&v(2))), "{what}: triangle {k}'s first corner and its edges");+ let skinned_without_normals = n.iter().flatten().all(|c| *c == 0.0);+ if !skinned_without_normals {+ assert_eq!([bits(&n[0]), bits(&n[1]), bits(&n[2])], [bits(&a.n0[..3]), bits(&a.n1[..3]), bits(&a.n2[..3])], "{what}: triangle {k}'s normals");+ }+ assert_eq!(bits(&uv.concat()), bits(&[a.n0[3], a.n1[3], a.n2[3], a.uv[0], a.uv[1], a.uv[2]]), "{what}: triangle {k}'s UVs");+ let own = a.x[0].to_bits() & indexed::OWN_TANGENT != 0;+ assert_eq!(bits(&tangent), bits(&if own { a.t } else { [0.0; 4] }), "{what}: triangle {k}'s own tangent on its first vertex, or none");+ // (A mesh's triangle: its section and its index in it, nothing else. One no instance places: its+ // material, its object, its flags, its emitter + 1.)+ let pool = (pool_first..pool_first + sc.pool_tris.len()).contains(&k);+ let row = if pool { [a.uv[3].to_bits(), 0, 0, a.x[3].to_bits()] } else { [a.uv[3].to_bits(), a.x[1].to_bits(), p.tri_verts[k * 3][3].to_bits(), a.x[3].to_bits()] };+ assert_eq!(x.rows[k], row, "{what}: triangle {k}'s row");+ // Software traversal: the triangle as its tree's leaf has it, with its ids (a mesh's: its section and+ // its index there; a world-space one's: its flags).+ if !hwrt {+ let ids = if pool { [row[0], row[3]] } else { [row[2], 0] };+ let corners = q.map(|c| Vec3A::new(c[0], c[1], c[2]));+ assert_eq!(x.leaves[k].map(|r| bits(&r)), indexed::leaf(corners, ids).map(|r| bits(&r)), "{what}: triangle {k}'s leaf");+ }+ }+ assert_eq!(x.leaves.len(), if hwrt { 0 } else { x.indices.len() }, "{what}: a leaf a triangle under software traversal, none under hardware traversal");+ if sc.meshes.is_empty() {+ continue;+ }+ // The ring's mesh: 80 triangles of 82 vertices. Each skinned model's mesh: its own vertices, as many as+ // the other's (one model), fewer than its corners; and they are the vertices that move.+ assert!(sc.attrs.iter().any(|a| a.x[0].to_bits() & indexed::OWN_TANGENT != 0) && sc.attrs.iter().any(|a| a.x[0].to_bits() & indexed::OWN_TANGENT == 0), "{what}: triangles with a tangent of their own and without");+ let ring = sc.meshes.iter().zip(&x.meshes).find(|(m, _)| m.count == 80).expect("the ring's mesh");+ assert_eq!(ring.1 .1, 82, "{what}: the ring's vertices");+ let skinned: Vec<(u32, u32)> = sc.meshes.iter().zip(&x.meshes).filter(|(m, _)| m.deforms).map(|(_, v)| *v).collect();+ assert_eq!(skinned.len(), 2, "{what}: two skinned meshes");+ let corners = sc.meshes.iter().find(|m| m.deforms).unwrap().count * 3;+ assert!(skinned[0].1 == skinned[1].1 && skinned[0].1 < corners && skinned[0].1 >= corners / 6, "{what}: {} vertices for {corners} corners", skinned[0].1);+ assert_eq!((x.dynamic.0, x.dynamic.1), (skinned[0].0.min(skinned[1].0), skinned[0].1 * 2), "{what}: the vertices that move are the skinned meshes'");+ }+ }+/// The same with no still triangle at all: the still tree is then the leaf of one triangle (bvh.rs `EMPTY`), and/// that triangle must be one no ray meets, not the first of the units' (a mesh's, in its model space). First seen/// on a GPU: `geometry/instanced`, two planes, darker towards a triangle standing at the origin.@@ -1715,13 +1889,13 @@ mod units_tests {assert_eq!(pu.nodes.len(), u.layout.top_first as usize + u.layout.top_cap as usize);let kernel = |p: &Prepared, sc: &scene::Scene| {let (top, units) = (p.params.motion[2].to_bits(), p.params.motion[3].to_bits());- (p.nodes.clone(), p.tri_verts.clone(), sc.gpu_instances.clone(), top, units, sc.attrs.iter().map(|a| a.uv[3].to_bits()).collect::<Vec<u32>>(), sc.rows.clone())+ (p.nodes.clone(), sc.indexed.leaves.clone(), sc.gpu_instances.clone(), top, units, sc.rows.clone())};let (ku, kf) = (kernel(&pu, &su), kernel(&pf, &sf));#[allow(clippy::type_complexity)]- let walk = |k: &(Vec<bvh::GpuNode>, Vec<[f32; 4]>, Vec<scene::GpuInstance>, u32, u32, Vec<u32>, Vec<scene::Row>), o: Vec3A, d: Vec3A, mode: u32| {+ let walk = |k: &(Vec<bvh::GpuNode>, Vec<indexed::Leaf>, Vec<scene::GpuInstance>, u32, u32, Vec<scene::Row>), o: Vec3A, d: Vec3A, mode: u32| {let instances = if k.2.is_empty() { vec![scene::GpuInstance::default()] } else { k.2.clone() };- let kernel = Kernel { nodes: &k.0, tri_verts: &k.1, instances: &instances, sections: &k.5, rows: &k.6, top: k.3, units: k.4, steps: Default::default(), budget: 1 << 20, deepest: Default::default(), reads: Default::default() };+ let kernel = Kernel { nodes: &k.0, leaves: &k.1, instances: &instances, rows: &k.5, top: k.3, units: k.4, steps: Default::default(), budget: 1 << 20, deepest: Default::default(), reads: Default::default() };kernel.trace(o, d, INF, mode).unwrap_or_else(|e| panic!("ray {o} {d}, mode {mode}: the kernel {e}"))};let mut s = 12345u64;diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex 7a1a950..141cb8d 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -115,10 +115,12 @@ 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.+ /// The previous frame's positions (a vertex each) 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,+ /// The vertices edits can place (a mesh's run: `InstMesh::vfirst`), as the triangles are.+ pub(super) verts: Holes,pub(super) free_skinned: Vec<u32>,}@@ -274,7 +276,7 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::let (place, of) = (mesh_places(&im, cx.sections, cx.pool_place), mine.iter().map(scene::row_material).collect::<Vec<u32>>());let numbered = |j: usize| {let (s, i) = place[j];- starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize]))+ starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize], s))};let (a, b) = (im.first as usize, (im.first + im.count) as usize);let made = crate::instance_emitters(inst, record as u32, &cx.pool_tris[a..b], (cx.edit.pool_first + a) as u32, &numbered, n, &cx.tables.materials, moves);@@ -297,6 +299,7 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::cx.rows.resize(row_at + mine.len(), [0; 4]);}cx.rows[row_at..row_at + mine.len()].copy_from_slice(mine);+ inst.verts = im.vfirst;let gpu = cx.top.record(inst.gpu(cx.edit.pool_first as u32 + im.first), inst.mesh, inst.cast_shadow);cx.w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));if record >= cx.gpu_instances.len() {@@ -350,11 +353,26 @@ pub(super) fn drop_mesh_user(k: u32, edit: &mut EditState, tables: &mut tables::if *n == 0 && edit.managed.remove(&k) {let im = meshes[k as usize];edit.tris.give(edit.pool_first + im.first as usize, im.count as usize);+ edit.verts.give(im.vfirst as usize, im.vcount as usize);tables.retained.own_mesh.retain(|_, v| *v != k);edit.dead_meshes.push(k);}}+/// `n` vertices of the room: a hole that fits, else its end, grown if it lacks room (`sw`: software traversal's does+/// not grow).+fn take_verts(edit: &mut EditState, grow: &Grow, vertices: &mut wgpu::Buffer, n: usize, sw: bool) -> std::result::Result<usize, String> {+ if let Some(first) = edit.verts.take(n) {+ return Ok(first);+ }+ if !sw && grow.verts(&mut edit.verts, n, vertices) {+ edit.grows += 1;+ edit.rebind = true;+ return edit.verts.take(n).ok_or_else(|| "edit room: vertices".to_string());+ }+ Err(if sw { "edit room: vertices (software traversal's does not grow)" } else { "edit room: vertices (particles, or the device's limits)" }.into())+}+/// The room's buffers past their end, doubled at least (ROADMAP § 6 step 5): new buffers, the old contents copied on/// the GPU; the scene bind group is made again after the edit (`EditState::rebind`). Not with particles, whose pass/// keeps a bind group of its own over these buffers.@@ -375,39 +393,44 @@ impl Grow<'_> {sizes.iter().all(|&s| self.g.buffer_fits(s))}- /// Triangles: vertices, attributes, the BLASes' vertices, and in a scene with them (`colors`) vertex colours.- pub(super) fn tris(&self, h: &mut Holes, extra: usize, verts: &mut wgpu::Buffer, attrs: &mut wgpu::Buffer, words: &mut Heap<Stream>, colors: bool, accel: &mut gpu::Accel) -> bool {+ /// Triangles: their indices, and in a scene with them (`colors`) vertex colours: sections of the words' heap,+ /// grown together. (A mesh's triangle has no row under hardware traversal, whose rooms these are.)+ pub(super) fn tris(&self, h: &mut Holes, extra: usize, words: &mut Heap<Stream>, colors: bool) -> bool {if !self.ok {return false;}let cap = Self::cap(h, extra);- let color_bytes = (cap * 12) as u64;- if !self.fits(&[(cap * 48) as u64, (cap * std::mem::size_of::<scene::GpuTriAttr>()) as u64, (cap * 36) as u64, if colors { words.size_with(Stream::VertexColors, color_bytes) } else { 0 }]) {- return false;- }- *verts = self.g.grown(verts, (cap * 48) as u64, "verts");- *attrs = self.g.grown(attrs, (cap * std::mem::size_of::<scene::GpuTriAttr>()) as u64, "attrs");- self.g.grow_blas_verts(accel, (cap * 36) as u64);+ let mut sections = vec![(Stream::Indices, (cap * 12) as u64)];if colors {- words.grow(&self.g.device, &self.g.queue, Stream::VertexColors, color_bytes);+ sections.push((Stream::VertexColors, (cap * 12) as u64));+ }+ if !self.fits(&[words.size_with_all(§ions)]) {+ return false;}+ words.grow_all(&self.g.device, &self.g.queue, §ions);h.cap = cap;true}- /// The previous frame's vertices of deforming meshes.- pub(super) fn prev(&self, h: &mut Holes, extra: usize, prev: &mut wgpu::Buffer) -> bool {+ /// Vertices (`vertices`), or the previous frame's of deforming meshes (`prev`: whole records too): a record each.+ fn vertex_room(&self, h: &mut Holes, extra: usize, buffer: &mut wgpu::Buffer, label: &str) -> bool {if !self.ok {return false;}- let cap = Self::cap(h, extra);- if !self.fits(&[(cap * 48) as u64]) {+ let bytes = (Self::cap(h, extra) * crate::indexed::VERTEX_BYTES) as u64;+ if !self.fits(&[bytes]) {return false;}- *prev = self.g.grown(prev, (cap * 48) as u64, "prev verts");- h.cap = cap;+ *buffer = self.g.grown(buffer, bytes, label);+ h.cap = Self::cap(h, extra);true}+ pub(super) fn verts(&self, h: &mut Holes, extra: usize, vertices: &mut wgpu::Buffer) -> bool {+ self.vertex_room(h, extra, vertices, "vertices")+ }+ pub(super) fn prev(&self, h: &mut Holes, extra: usize, prev: &mut wgpu::Buffer) -> bool {+ self.vertex_room(h, extra, prev, "previous vertices")+ }/// 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 {@@ -1261,7 +1284,8 @@ impl LiveCore {return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());}let Some(top) = top.as_mut() else { return Err("software traversal".into()) };- (inst.bits, inst.cast_shadow) = (bits, cast);+ // (Its rows' bits; whether its mesh deforms is its own.)+ (inst.bits, inst.cast_shadow) = (bits | inst.bits & scene::INST_DEFORMS, cast);up.words.write(q, Stream::Rows, (at * 16) as u64, bytemuck::cast_slice(mine));let old = gpu_instances[r];let mut rec = top.record(inst.gpu(old.info[0]), inst.mesh, cast);@@ -1289,7 +1313,7 @@ impl LiveCore {let area = 0.5 * (b - a).cross(c - a).length();if area > 0.0 {let centre = (a + b + c) / 3.0;- let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false, inst: crate::NO_INST };+ let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0 };new.push((sc.tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, [a, b, c], 0)));sc.tables.emitter_tris.push(e);}@@ -1351,7 +1375,7 @@ impl LiveCore {up.words.write(q, Stream::Rows, (at * 16) as u64, bytemuck::cast_slice(&rows[at..at + sects.len()]));let numbered = |j: usize| {let (s, i) = place[j];- starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, scene::row_material(&mine[s as usize])))+ starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, scene::row_material(&mine[s as usize]), s))};let first_tri = edit.pool_first + im.first as usize;let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);@@ -1380,15 +1404,15 @@ impl LiveCore {let g = &self.g;let LoadedScene { tables: e, base: b, up, pool_tris, tris: flat, tri_order, edit, instances, codes_sent: sent, .. } = &mut self.sc;let size = std::mem::size_of::<crate::GpuEmitterTri>();- let (mut w_tris, mut w_attrs) = (Gather::default(), Gather::default());+ let (mut w_tris, mut w_rows) = (Gather::default(), Gather::default());for (i, t) in new {w_tris.put((*i as usize * size) as u64, bytemuck::bytes_of(t));// (A triangle in world space names its emitter; a mesh's is numbered among its mesh's.)if t.inst == crate::NO_INST {- w_attrs.put((t.tri as usize * std::mem::size_of::<scene::GpuTriAttr>() + std::mem::offset_of!(scene::GpuTriAttr, x) + 12) as u64, bytemuck::bytes_of(&(i + 1)));+ w_rows.put((t.tri as usize * 16 + 12) as u64, bytemuck::bytes_of(&(i + 1)));}}- w_attrs.flush(&g.queue, &up.attrs);+ w_rows.flush_section(&g.queue, &up.words, Stream::Triangles);// Emitters added in place, with the tree's slot for them (`ltree::build_slotted`): its subtree grown again over// those alive, their entries right after the static ones in the CDF (the tree's order: `emitter_order`) and// their path codes with their triangles in the list (written over the code 0 they were made with).@@ -1640,7 +1664,7 @@ impl LiveCore {let at = sc.tables.emitter_tris.len();(inst.first_emitter, row[2]) = (at as u32, at as u32);let (a, b) = (mesh.first as usize, (mesh.first + mesh.count) as usize);- let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], (sc.edit.pool_first + a) as u32, &|k| Some((k, mat)), mesh.count as usize, &sc.tables.materials, true);+ let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], (sc.edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), mesh.count as usize, &sc.tables.materials, true);for (j, (e, w)) in made.into_iter().enumerate() {self.pending_emitters.push(((at + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));sc.tables.emitter_tris.push(e);@@ -1861,12 +1885,7 @@ impl LiveCore {self.keep_prev(both);self.prev_span = Some((lo, hi));self.reposed = true;- let (q, up, (first, verts, attrs, blas)) = (&self.g.queue, &self.sc.up, &self.sc.dynamic);- let accel = up.accel.as_ref().unwrap();- let k = (first + lo) as u64;- q.write_buffer(&up.verts, k * 48, bytemuck::cast_slice(&verts[lo * 3..hi * 3]));- q.write_buffer(&up.attrs, k * 96, bytemuck::cast_slice(&attrs[lo..hi]));- q.write_buffer(&accel.verts, k * 36, bytemuck::cast_slice(&blas[lo * 3..hi * 3]));+ self.upload_dynamic(lo, hi);}build.instances = true;build.dynamic |= lo < hi;@@ -1926,15 +1945,17 @@ impl LiveCore {// models in parallel). Nothing is written unless every one is a unit with such a tree.let mut trees: Vec<(u32, u32, Vec<crate::bvh::GpuNode>, (glam::Vec3A, glam::Vec3A))> = vec![];if let Some(units) = &self.sc.up.units {- let (sources, shapes) = (&self.sc.skin_sources, &self.sc.skin_trees);+ let (skins, shapes) = (&self.sc.skins, &self.sc.skin_trees);let made: Vec<Option<(u32, u32, Vec<crate::bvh::GpuNode>, (glam::Vec3A, glam::Vec3A))>> = work.par_iter().map(|(g, rows)| {let sk = &r.skinned[*g as usize];- let (corners, shape) = (sources.get(sk.source as usize)?, shapes.get(sk.source as usize)?);- let tree = units.trees.get(sk.mesh as usize).copied().flatten().filter(|t| t.len as usize == shape.len() && !shape.is_empty() && corners.len() == sk.order.len())?;+ let ((vertices, index), shape) = (skins.get(sk.source as usize)?, shapes.get(sk.source as usize)?);+ let tree = units.trees.get(sk.mesh as usize).copied().flatten().filter(|t| t.len as usize == shape.len() && !shape.is_empty() && index.len() == sk.order.len())?;let mut nodes = shape.clone();- let bounds = crate::units::refit(&mut nodes, |i| corners[i].map(|c| glam::Vec3A::from(crate::skin::skin_corner(&c, rows).0)));+ // (The model's vertices placed once each; a triangle's corners through its indices.)+ let placed: Vec<glam::Vec3A> = vertices.iter().map(|c| glam::Vec3A::from(crate::skin::skin_corner(c, rows).0)).collect();+ let bounds = crate::units::refit(&mut nodes, |i| index[i].map(|v| placed[v as usize]));Some((sk.mesh, tree.root, nodes, bounds))}).collect();@@ -1951,7 +1972,8 @@ impl LiveCore {.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())+ let i = &self.sc.instances[sk.instance as usize];+ (i.verts as usize, i.prev as usize, self.sc.meshes[sk.mesh as usize].vcount as usize)}).collect();self.keep_prev_spans(&posed.iter().chain(&self.pose_spans).copied().collect::<Vec<_>>());@@ -2004,13 +2026,8 @@ impl LiveCore {self.prev_span = Some((lo, hi));self.reposed = true;// Upload the touched span of the dynamic tail; the commit builds the dynamic BLASes and the TLAS.- let (q, up, (first, verts, attrs, blas)) = (&self.g.queue, &self.sc.up, &self.sc.dynamic);- let accel = up.accel.as_ref().unwrap();- let k = (first + lo) as u64;- q.write_buffer(&up.verts, k * 48, bytemuck::cast_slice(&verts[lo * 3..hi * 3]));- q.write_buffer(&up.attrs, k * 96, bytemuck::cast_slice(&attrs[lo..hi]));- q.write_buffer(&accel.verts, k * 36, bytemuck::cast_slice(&blas[lo * 3..hi * 3]));- up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));+ self.upload_dynamic(lo, hi);+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));build.dynamic = true;self.cpu_upload_ms += t_up.elapsed().as_secs_f32() * 1000.0;Ok(true)@@ -2019,9 +2036,13 @@ impl LiveCore {/// The emitters of instances that moved (those of a mesh that emits): their runs of the light list taken again on/// the GPU, through the records just queued; the light tree's moving subtree after (`move_emitters`).pub(super) fn fill_moved(&mut self, records: impl Iterator<Item = u32>) {+ // An instance whose emitters this commit has still to write (`pending_emitters`: a still mesh's first move+ // makes it new ones, at the list's end) needs no fill: they are made where it stands now, and the list on the+ // GPU does not hold them yet (a write past its end lands on its last row).+ let pending: std::collections::HashSet<u32> = self.pending_emitters.iter().map(|p| p.0).collect();// (Runs that follow each other as one: an instanced object's copies'.)let mut runs: Vec<[u32; 2]> = vec![];- for r in records.map(|i| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty()) {+ for r in records.map(|i| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty() && !pending.contains(&(r.start as u32))) {match runs.last_mut() {Some(l) if l[0] + l[1] == r.start as u32 => l[1] += r.len() as u32,_ => runs.push([r.start as u32, r.len() as u32]),@@ -2063,18 +2084,29 @@ impl LiveCore {heap.write(q, Table::LightTree, t.moving_nodes as u64 * 16, bytemuck::cast_slice(&t.nodes[t.moving_nodes..]));}- /// Copies the GPU's current vertices of a dynamic-tail span into `prev_verts` (submitted before any write queued- /// after it, so it reads what the last frame traced).+ /// The dynamic tail's triangles `lo..hi` as the CPU has them now (`sc.dynamic`), to the GPU: their vertices, three+ /// a triangle from the first vertex that moves (their indices and rows are the build's).+ fn upload_dynamic(&self, lo: usize, hi: usize) {+ let (_, _, attrs, corners) = &self.sc.dynamic;+ let vertices = crate::indexed::apart_vertices(&corners[lo * 3..hi * 3], &attrs[lo..hi]);+ let at = (self.sc.dynamic_verts.0 as usize + lo * 3) * crate::indexed::VERTEX_BYTES;+ self.g.queue.write_buffer(&self.sc.up.vertices, at as u64, bytemuck::cast_slice(&vertices));+ }++ /// Copies the GPU's current vertices of a span of the dynamic tail's triangles (three each, the first of the+ /// vertices that move) into the previous frame's (submitted before any write queued after it, so it reads what the+ /// last frame traced).pub(super) fn keep_prev(&self, (lo, hi): (usize, usize)) {let up = &self.sc.up;- let first = self.sc.dynamic.0;+ let first = self.sc.dynamic_verts.0 as usize;let mut e = self.g.device.create_command_encoder(&Default::default());- e.copy_buffer_to_buffer(&up.verts, ((first + lo) * 48) as u64, &up.prev_verts, (lo * 48) as u64, ((hi - lo) * 48) as u64);+ let size = crate::indexed::VERTEX_BYTES;+ e.copy_buffer_to_buffer(&up.vertices, ((first + lo * 3) * size) as u64, &up.prev_vertices, (lo * 3 * size) as u64, ((hi - lo) * 3 * size) as u64);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).+ /// Likewise for deforming meshes, each where it lies: (its first vertex in the scene's, its first among the+ /// previous frame's, how many vertices).pub(super) fn keep_prev_spans(&self, spans: &[(usize, usize, usize)]) {if spans.is_empty() {return;@@ -2082,7 +2114,8 @@ impl LiveCore {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);+ let size = crate::indexed::VERTEX_BYTES;+ e.copy_buffer_to_buffer(&up.vertices, (verts * size) as u64, &up.prev_vertices, (prev * size) as u64, (n * size) as u64);}self.g.queue.submit([e.finish()]);}@@ -2203,7 +2236,7 @@ impl LiveCore {if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {return Err("THREERT_EDIT_REBUILD=1".into());}- let LoadedScene { up, tables, edit, meshes, pool_tris, pool_place, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, .. } = &mut self.sc;+ let LoadedScene { up, tables, edit, meshes, pool_tris, pool_place, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, skins, .. } = &mut self.sc;let (g, assets) = (&self.g, &self.assets);let features = up.kernel.features;let grow = Grow { g: &self.g, ok: up.particles.is_none() && up.gpu_particles.is_none() };@@ -2321,8 +2354,8 @@ impl LiveCore {}) {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;+ edit.prev.give(inst.prev as usize, im.vcount as usize);+ let first = im.vfirst as usize;self.pose_spans.retain(|s| s.0 != first);}tables.retained.skinned[g].mesh = u32::MAX;@@ -2347,7 +2380,8 @@ impl LiveCore {let mut new_meshes = vec![];let mut pending_procs = vec![];let mut split = EditSplit::default();- let (mut w_cdf, mut w_verts, mut w_attrs, mut w_blas, mut w_records, mut w_objects) = (Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default());+ // (Vertices; triangles' indices; under software traversal a unit's tree's leaves.)+ let (mut w_cdf, mut w_vert, mut w_index, mut w_leaf, mut w_records, mut w_objects) = (Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default());// Vertex colours (F_VCOLOR).let mut w_colors = Gather::default();let vcolors = up.vcolors;@@ -2495,31 +2529,50 @@ impl LiveCore {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() {+ // Its vertices as it is posed, each from a corner that is it (the model's vertices and its+ // triangles' indices are the source's, as every mesh of the model has them).+ let (model, index) = skins.get(source as usize).ok_or("a skinned model without its vertices")?;+ let nv = model.len();+ if index.len() != n {+ return Err("a skinned model whose triangles are not the scene's".into());+ }+ let mut vertices: Vec<crate::indexed::Vertex> = vec![[[0.0f32; 4]; 3]; nv];+ let mut t = Vec::with_capacity(n);+ for (j, &(k, _, _)) in order.iter().enumerate() {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())));+ for c in 0..3 {+ let v = index[j][c] as usize;+ // (A position that is not finite is the mesh's origin, as the pass writes it; a+ // model without normals has none: the triangle's own where it is hit.)+ let p = if q.p[c].is_finite() { q.p[c] } else { glam::Vec3::ZERO };+ let normal = if model[v].t[3].to_bits() & crate::skin::CORNER_NORMAL != 0 { q.n[c] } else { glam::Vec3::ZERO };+ vertices[v][0] = [p.x, p.y, p.z, q.uv[c].x];+ vertices[v][1] = [normal.x, normal.y, normal.z, q.uv[c].y];+ }+ let v0 = index[j][0] as usize;+ if let Some((tangent, hand)) = q.tangent.filter(|_| model[v0].t[3].to_bits() & crate::skin::CORNER_TANGENT != 0) {+ vertices[v0][2] = [tangent.x, tangent.y, tangent.z, hand];+ }t.push(q.p.map(glam::Vec3A::from));}- // Its triangles, and their previous frame's vertices: holes that fit, else the rooms' ends.+ // Its triangles, its vertices and their previous frame's positions: 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 } => {+ None if !top.sw() && grow.tris(&mut edit.tris, n, &mut up.words, vcolors) => {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) {+ let vfirst = take_verts(edit, &grow, &mut up.vertices, nv, top.sw())?;+ let prev = match edit.prev.take(nv) {Some(f) => f,- None if grow.prev(&mut edit.prev, n, &mut up.prev_verts) => {+ None if grow.prev(&mut edit.prev, nv, &mut up.prev_vertices) => {edit.grows += 1;edit.rebind = true;- edit.prev.take(n).ok_or("edit room: previous vertices")?+ edit.prev.take(nv).ok_or("edit room: previous vertices")?}None => return Err("edit room: previous vertices (particles, or the device's limits)".into()),};@@ -2539,7 +2592,7 @@ impl LiveCore {// (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 im = scene::InstMesh { lo: own.lo - pad, hi: own.hi + pad, deforms: true, sect_first, sect_count: ns as u32, vfirst: vfirst as u32, vcount: nv as u32, ..own };let mesh = match &mut top {gpu::Top::Hw(accel) => match dead {Some(k) => {@@ -2559,14 +2612,13 @@ impl LiveCore {*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));+ w_vert.put((vfirst * crate::indexed::VERTEX_BYTES) as u64, bytemuck::cast_slice(&vertices));+ w_index.put((first * 12) as u64, bytemuck::cast_slice(&index[..]));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));+ q.write_buffer(&up.prev_vertices, (prev * crate::indexed::VERTEX_BYTES) as u64, bytemuck::cast_slice(&vertices));let rel = first - edit.pool_first;if pool_tris.len() < rel + n {pool_tris.resize(rel + n, [glam::Vec3A::ZERO; 3]);@@ -2581,8 +2633,8 @@ impl LiveCore {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 };+ edit.rebind |= pass.set_job(&g.device, q, slot as usize, vfirst as u32, nv 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) | scene::INST_DEFORMS, prev: prev as u32, verts: 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]);(None, Placed::Skinned(inst, mine, slot), entry)@@ -2603,7 +2655,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), prev: 0 };+ 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, verts: 0 };placed.push((node, inst, mine));}for &(_, mesh) in &parts {@@ -2626,7 +2678,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), prev: 0 };+ 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, verts: 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)@@ -2706,21 +2758,37 @@ impl LiveCore {Some(tree)}};- // (No flag on the triangles: a unit's cutouts and glass are its rows'.)- let flags = 0.0f32;- // As `prepare` lays the pool out: (a, flags), e1, e2; attributes; the BLAS's vertices.- let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, flags], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();- let blas_verts: Vec<[f32; 3]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]]).collect();+ // As `prepare` lays the pool out: the mesh's vertices, each once (indexed.rs), its triangles'+ // indices from its first vertex, and for a tree its leaves: each triangle with its section+ // and its index in it.+ let scope = crate::indexed::shared(&t, &a);+ let nv = scope.vertices.len();+ let leaves: Vec<crate::indexed::Leaf> = if tree.is_some() { t.iter().zip(&a).map(|(t, x)| crate::indexed::leaf(*t, [x.uv[3].to_bits(), x.x[3].to_bits()])).collect() } else { vec![] };split.tris += t0.elapsed().as_secs_f64() * 1e3;// The same sections as the mesh it replaces (as many triangles in each: a BLAS's geometries keep// their sizes): rewritten where it is, its BLAS rebuilt (no room used; a geometry that moves// every frame, three.js's dynamic draw usage). Otherwise new triangles in the room and a new// BLAS.+ if sects.len() > scene::MESH_SECTIONS {+ return Err("a mesh with more than 65,536 sections".into());+ }let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].sections(sections) == sects.as_slice());let (k, first, im) = match same {Some(k) => {// (Its colours stay its own while another object of it reads them.)meshes[k as usize].colored |= colored;+ // Its vertices where they were, if the run holds them; else another run, and its+ // BLAS made again for as many (the objects that draw it are all placed again by+ // this edit: their records and TLAS instances take what it has now).+ let old = meshes[k as usize];+ if nv > old.vcount as usize {+ let vfirst = take_verts(edit, &grow, &mut up.vertices, nv, top.sw())?;+ edit.verts.give(old.vfirst as usize, old.vcount as usize);+ (meshes[k as usize].vfirst, meshes[k as usize].vcount) = (vfirst as u32, nv as u32);+ if let gpu::Top::Hw(accel) = &mut top {+ g.set_mesh(accel, k, edit.pool_first + old.first as usize, &meshes[k as usize], sections);+ }+ }let im = meshes[k as usize];split.deformed += 1;// (Its tree again: the records of the objects that draw it, all placed again by@@ -2739,13 +2807,14 @@ impl LiveCore {let first = match edit.tris.take(t.len()) {Some(f) => f,// (Software traversal's room does not grow: the rebuild makes a larger one.)- None if match &mut top { gpu::Top::Hw(accel) => grow.tris(&mut edit.tris, t.len(), &mut up.verts, &mut up.attrs, &mut up.words, vcolors, accel), gpu::Top::Sw(_) => false } => {+ None if !top.sw() && grow.tris(&mut edit.tris, t.len(), &mut up.words, vcolors) => {edit.grows += 1;edit.rebind = true;edit.tris.take(t.len()).ok_or("edit room: triangles")?}None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),};+ let vfirst = take_verts(edit, &grow, &mut up.vertices, nv, top.sw())?;let t1 = Instant::now();// A freed mesh's slot (and its sections', where they are as many at least), else new ones.let dead = edit.dead_meshes.pop();@@ -2758,7 +2827,7 @@ impl LiveCore {}};sections[sect_first as usize..][..n].copy_from_slice(§s);- let im = scene::InstMesh { sect_first, sect_count: n as u32, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };+ let im = scene::InstMesh { sect_first, sect_count: n as u32, colored, vfirst: vfirst as u32, vcount: nv as u32, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };let k = match &mut top {gpu::Top::Hw(accel) => match dead {Some(k) => {@@ -2795,10 +2864,11 @@ impl LiveCore {}};let t2 = Instant::now();- 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));- if !top.sw() {- w_blas.put((first * 36) as u64, bytemuck::cast_slice(&blas_verts));+ w_vert.put((im.vfirst as usize * crate::indexed::VERTEX_BYTES) as u64, bytemuck::cast_slice(&scope.vertices));+ w_index.put((first * 12) as u64, bytemuck::cast_slice(&scope.indices));+ // (A unit's tree's leaves; a BLAS is built from the vertices.)+ if top.sw() {+ w_leaf.put((first * crate::indexed::LEAF_BYTES) as u64, bytemuck::cast_slice(&leaves));}if vcolors {// White where it has none: the room's slots may hold an earlier mesh's.@@ -2864,7 +2934,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, prev: 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, verts: 0 };instances.resize(r0 + cap, filler);}if gpu_instances.len() < r0 + cap {@@ -2879,14 +2949,14 @@ 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]), prev: 0 };+ 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, verts: im.vfirst };// 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 {let first = tables.emitter_tris.len();(inst.first_emitter, row[2]) = (first as u32, first as u32);let (a, b) = (im.first as usize, (im.first + im.count) as usize);- let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.count as usize, &tables.materials, true);+ let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat, 0)), im.count as usize, &tables.materials, true);for (j, (e, w)) in made.into_iter().enumerate() {new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));tables.emitter_tris.push(e);@@ -2919,7 +2989,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), prev: 0 };+ 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, verts: 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)@@ -3014,11 +3084,9 @@ impl LiveCore {// The gathered writes, merged, before the builds that read them.let tw = Instant::now();w_cdf.flush_section(q, &up.words, Stream::Procs);- w_verts.flush(q, &up.verts);- w_attrs.flush(q, &up.attrs);- if let gpu::Top::Hw(accel) = &top {- w_blas.flush(q, &accel.verts);- }+ w_vert.flush(q, &up.vertices);+ w_index.flush_section(q, &up.words, Stream::Indices);+ w_leaf.flush(q, &up.bg_parts.leaves);w_colors.flush_section(q, &up.words, Stream::VertexColors);w_rows.flush_section(q, &up.words, Stream::Rows);w_records.flush_section(q, &up.heap, Table::Instances);diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex f9dc9fa..01f7b66 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -91,15 +91,14 @@ pub(super) struct Raster {}pub(super) const RASTER_WGSL: &str = r#"-struct R { pos: vec4<f32>, fwd: vec4<f32>, right: vec4<f32>, up: vec4<f32>, jit: vec4<f32> }; // pos.w = tan(fov/2), fwd.w = aspect, jit = ndc offset xy, near+struct R { pos: vec4<f32>, fwd: vec4<f32>, right: vec4<f32>, up: vec4<f32>, jit: vec4<f32> }; // pos.w = tan(fov/2), fwd.w = aspect, right.w = the indices' first word, jit = ndc offset xy, near@group(0) @binding(0) var<uniform> r: R;-@group(0) @binding(1) var<storage, read> tri_verts: array<vec4<f32>>; // per triangle: a, b - a, c - a (kernel layout)+@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>; // a vertex: three rows, the first (position, u) (kernel layout)+@group(0) @binding(2) var<storage, read> words: array<u32>; // the triangles' indices, three a trianglestruct V { @builtin(position) p: vec4<f32>, @location(0) @interpolate(flat) id: u32 };@vertex fn vs(@builtin(vertex_index) vi: u32) -> V {let ti = vi / 3u;- let k = vi % 3u;- var p = tri_verts[ti * 3u].xyz;- if (k != 0u) { p += tri_verts[ti * 3u + k].xyz; }+ let p = vertices[words[bitcast<u32>(r.right.w) + vi] * 3u].xyz;let d = p - r.pos.xyz;let z = dot(d, r.fwd.xyz);// Reversed infinite depth: near / z.@@ -117,6 +116,7 @@ impl Raster {entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, count: None },wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None }, count: None },+ wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None }, count: None },],});let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });@@ -142,13 +142,14 @@ impl Raster {Raster { pipeline, layout, uniform, vis, depth }}- /// Records the visibility pass for `tris` triangles at internal size (iw, ih), sampling at jitter (jx, jy).+ /// Records the visibility pass for the scene's first `tris` triangles (their vertices; their indices in+ /// the words' heap) at internal size (iw, ih), sampling at jitter (jx, jy).#[allow(clippy::too_many_arguments)]- pub(super) fn record(&self, g: &gpu::Gpu, e: &mut wgpu::CommandEncoder, verts: &wgpu::Buffer, tris: u32, cam: &Camera, aspect: f32, (iw, ih): (u32, u32), (jx, jy): (f32, f32), timestamps: Option<wgpu::RenderPassTimestampWrites>) {+ pub(super) fn record(&self, g: &gpu::Gpu, e: &mut wgpu::CommandEncoder, vertices: &wgpu::Buffer, words: &crate::heap::Heap<crate::heap::Stream>, tris: u32, cam: &Camera, aspect: f32, (iw, ih): (u32, u32), (jx, jy): (f32, f32), timestamps: Option<wgpu::RenderPassTimestampWrites>) {let u: [[f32; 4]; 5] = [[cam.pos.x, cam.pos.y, cam.pos.z, cam.tan_half_fov],[cam.fwd.x, cam.fwd.y, cam.fwd.z, aspect],- [cam.right.x, cam.right.y, cam.right.z, 0.0],+ [cam.right.x, cam.right.y, cam.right.z, f32::from_bits((words.at(crate::heap::Stream::Indices) / 4) as u32)],[cam.up.x, cam.up.y, cam.up.z, 0.0],// Pixel centres sample at +0.5; shift the image so they sample at the jittered position instead.[2.0 * (0.5 - jx) / iw as f32, -2.0 * (0.5 - jy) / ih as f32, 0.01, 0.0],@@ -157,7 +158,7 @@ impl Raster {let bg = g.device.create_bind_group(&wgpu::BindGroupDescriptor {label: None,layout: &self.layout,- entries: &[wgpu::BindGroupEntry { binding: 0, resource: self.uniform.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: verts.as_entire_binding() }],+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: self.uniform.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: vertices.as_entire_binding() }, wgpu::BindGroupEntry { binding: 2, resource: words.buffer.as_entire_binding() }],});let mut pass = e.begin_render_pass(&wgpu::RenderPassDescriptor {label: Some("raster vis"),@@ -464,7 +465,7 @@ impl LiveCore {}if let (Some(r), 0, false) = (&self.raster, k, self.sc.instanced) {let tw = self.timer.as_ref().zip(timed).map(|(t, slot)| wgpu::RenderPassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * 8 + 4), end_of_pass_write_index: Some(slot as u32 * 8 + 5) });- r.record(g, &mut e, &self.sc.up.verts, self.sc.tris.len() as u32, &cam, self.aspect, (iw, ih), jitter, tw);+ r.record(g, &mut e, &self.sc.up.vertices, &self.sc.up.words, self.sc.tris.len() as u32, &cam, self.aspect, (iw, ih), jitter, tw);}{let tw = match (&self.profile, &self.timer, timed) {diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex d50b9be..2021a67 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -126,12 +126,609 @@ fn seen_by_rays(c: &LiveCore, record: u32) -> bool {}}+/// Part of a GPU buffer, read back.+fn read_back<T: bytemuck::Pod>(c: &LiveCore, b: &wgpu::Buffer, at: u64, bytes: u64) -> Vec<T> {+ 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+}++/// Triangles as the kernel reads them (through their indices): a triangle's corners (9 numbers), their normals (9),+/// their UVs (6), its first vertex's tangent (4; zeros: none), its row (4 words), and its corners' positions of the+/// previous frame (9; a mesh that deforms).+#[derive(Default)]+struct Triangles {+ p: Vec<f32>,+ n: Vec<f32>,+ uv: Vec<f32>,+ t: Vec<f32>,+ rows: Vec<u32>,+ prev: Vec<f32>,+}++/// `n` triangles from `first` as the GPU has them, their vertices counted from `base`; their previous positions from+/// `prev` on (None: not read). Software traversal: each one's leaf is held to the triangle its indices name (v0, e1,+/// e2, bit for bit), and `rows` has the leaves' ids as a row (a mesh's: its section, -, -, its index there).+fn triangles_on_gpu(c: &LiveCore, first: u64, n: u64, base: u32, prev: Option<u32>) -> Triangles {+ use crate::heap::Stream;+ let up = &c.sc.up;+ let index: Vec<u32> = read_back(c, &up.words.buffer, up.words.at(Stream::Indices) + first * 12, n * 12);+ let vertices: Vec<crate::indexed::Vertex> = read_back(c, &up.vertices, 0, up.vertices.size());+ let mut rows = vec![];+ if !c.g.hwrt {+ let size = crate::indexed::LEAF_BYTES as u64;+ let leaves: Vec<crate::indexed::Leaf> = read_back(c, &up.bg_parts.leaves, first * size, n * size);+ let bits = |l: &crate::indexed::Leaf| l.map(|r| r.map(f32::to_bits));+ for (j, (l, tri)) in leaves.iter().zip(index.chunks_exact(3)).enumerate() {+ let p = |k: usize| glam::Vec3A::from_slice(&vertices[(base + tri[k]) as usize][0][..3]);+ let ids = [l[0][3].to_bits(), l[1][3].to_bits()];+ assert_eq!(bits(l), bits(&crate::indexed::leaf([p(0), p(1), p(2)], ids)), "triangle {}: its leaf is the triangle its indices name", first + j as u64);+ rows.extend([ids[0], 0, 0, ids[1]]);+ }+ }+ let before: Vec<crate::indexed::Vertex> = prev.map_or(vec![], |_| read_back(c, &up.prev_vertices, 0, up.prev_vertices.size()));+ let mut out = Triangles { rows, ..Default::default() };+ for tri in index.chunks_exact(3) {+ for (k, &i) in tri.iter().enumerate() {+ let v = &vertices[(base + i) as usize];+ out.p.extend(&v[0][..3]);+ out.n.extend(&v[1][..3]);+ out.uv.extend([v[0][3], v[1][3]]);+ if k == 0 {+ out.t.extend(v[2]);+ }+ if let Some(p) = prev {+ out.prev.extend(&before[(p + i) as usize][0][..3]);+ }+ }+ }+ out+}++/// A skinned model's mesh as the CPU skin gives it for a pose, in the same form: a normal where the model has one+/// (else zeros: the triangle's own is made where it is hit), a tangent where the model has its own.+fn skinned_on_cpu(c: &LiveCore, sk: &scene::Skinned, a: &crate::desc::Animation) -> Triangles {+ let tris = scene::model_gltf(&sk.uri, Path::new("..")).unwrap().triangles(glam::Mat4::IDENTITY, None, Some(a)).unwrap();+ let (model, index) = &c.sc.skins[sk.source as usize];+ let has = |j: usize, k: usize, bit: u32| model[index[j][k] as usize].t[3].to_bits() & bit != 0;+ let mut out = Triangles::default();+ for (j, &(k, section, rank)) in sk.order.iter().enumerate() {+ let q = &tris[k as usize];+ for corner in 0..3 {+ out.p.extend(q.p[corner].to_array());+ out.n.extend(if has(j, corner, crate::skin::CORNER_NORMAL) { q.n[corner].to_array() } else { [0.0; 3] });+ out.uv.extend(q.uv[corner].to_array());+ }+ out.t.extend(match q.tangent.filter(|_| has(j, 0, crate::skin::CORNER_TANGENT)) {+ Some((t, hand)) => [t.x, t.y, t.z, hand],+ None => [0.0; 4],+ });+ out.rows.extend([section, 0, 0, rank]);+ }+ out+}++/// Numbers within a rounding of each other.+fn same_numbers(what: &str, got: &[f32], want: &[f32], stride: usize) {+ assert_eq!(got.len(), want.len(), "{what}: its length");+ for (i, (g, x)) in got.iter().zip(want).enumerate() {+ assert!((g - x).abs() <= 2e-5 * x.abs().max(1.0), "{what}: number {} of triangle {}: {g} ({:#x}), the CPU's {x} ({:#x})", i % stride, i / stride, g.to_bits(), x.to_bits());+ }+}++/// A posed skinned model's mesh on the GPU against the CPU skin of `now` (corners, normals, UVs, tangents), its+/// vertices' previous positions against that of `before`, and the mesh as the CPU has it when asked (`name`: its+/// node). Its record has where its vertices and their previous positions are, and that its mesh deforms. Which+/// section a triangle is in and its index there: under software traversal the tree's rows, word for word; under+/// hardware traversal the triangle is its section's first (its instance's row's) and its index on. The CPU's corners.+fn skinned_is_the_cpus(what: &str, c: &LiveCore, sk: &scene::Skinned, name: &str, now: &crate::desc::Animation, before: &crate::desc::Animation) -> Vec<f32> {+ let (inst, record, mesh) = (&c.sc.instances[sk.instance as usize], &c.sc.gpu_instances[sk.instance as usize], &c.sc.meshes[sk.mesh as usize]);+ assert_eq!((record.n[2][3].to_bits(), record.info[2], inst.verts), (inst.prev, mesh.vfirst, mesh.vfirst), "{what}: the record has where the mesh's vertices and their previous positions are");+ let got = triangles_on_gpu(c, record.info[0] as u64, sk.order.len() as u64, inst.verts, Some(inst.prev));+ let want = skinned_on_cpu(c, sk, now);+ same_numbers(&format!("{what}: the corners"), &got.p, &want.p, 9);+ same_numbers(&format!("{what}: the normals"), &got.n, &want.n, 9);+ same_numbers(&format!("{what}: the UVs"), &got.uv, &want.uv, 6);+ same_numbers(&format!("{what}: the tangents"), &got.t, &want.t, 4);+ assert!(record.n[1][3].to_bits() & scene::INST_DEFORMS != 0 && inst.bits & scene::INST_DEFORMS != 0, "{what}: the record says its mesh deforms");+ if c.g.hwrt {+ for (j, &(_, section, rank)) in sk.order.iter().enumerate() {+ assert_eq!(c.sc.rows[(inst.rows + section) as usize][1] + rank, record.info[0] + j as u32, "{what}: triangle {j} is its section's first and its index on (section {section}, index {rank})");+ }+ } else {+ assert_eq!(got.rows, want.rows, "{what}: the tree's rows (a triangle's section, -, -, its index in the section)");+ }+ same_numbers(&format!("{what}: the previous frame's positions"), &got.prev, &skinned_on_cpu(c, sk, before).p, 9);+ let asked: Vec<f32> = c.node_tris(name).iter().flatten().flat_map(|p| p.to_array()).collect();+ let placed: Vec<f32> = want.p.chunks_exact(3).flat_map(|p| inst.world.transform_point3(Vec3::new(p[0], p[1], p[2])).to_array()).collect();+ same_numbers(&format!("{what}: the mesh as the CPU has it when asked"), &asked, &placed, 9);+ want.p+}++/// An object's mesh on the GPU, read through its triangles' indices from its instance's first vertex, is the mesh+/// the CPU has (its corners, bit for bit); its record and its mesh agree on where its vertices are.+fn mesh_is_the_cpus(what: &str, c: &LiveCore, id: u32) {+ let i = c.sc.tables.retained.instance(id).expect("an instance").instance as usize;+ let (inst, record) = (&c.sc.instances[i], &c.sc.gpu_instances[i]);+ let m = c.sc.meshes[inst.mesh as usize];+ assert_eq!((record.info[2], inst.verts), (m.vfirst, m.vfirst), "{what}: the record has the mesh's first vertex");+ let got = triangles_on_gpu(c, record.info[0] as u64, m.count as u64, inst.verts, None);+ let want: Vec<f32> = c.sc.pool_tris[m.first as usize..(m.first + m.count) as usize].iter().flatten().flat_map(|p| p.to_array()).collect();+ assert_eq!(got.p, want, "{what}: the mesh's corners through its indices");+}++/// The world-space triangles that move, on the GPU through their indices, are the CPU's (`LoadedScene::dynamic`).+fn moving_triangles_are_the_cpus(what: &str, c: &LiveCore) {+ let (first, rows, _, corners) = &c.sc.dynamic;+ let got = triangles_on_gpu(c, *first as u64, rows.len() as u64 / 3, 0, None);+ assert_eq!(got.p, corners.iter().flatten().copied().collect::<Vec<f32>>(), "{what}: the moving triangles' corners through their indices");+}+/// Mean absolute difference of two pictures, in 8-bit steps.fn apart(a: &[u8], b: &[u8]) -> f64 {assert_eq!(a.len(), b.len());a.iter().zip(b).map(|(x, y)| x.abs_diff(*y) as f64).sum::<f64>() / a.len() as f64}+/// The mean of a picture's colour bytes (BGRA8, 96 pixels a row) over the pixels x0..x1 of the rows y0..y1.+fn region_mean(p: &[u8], [x0, y0, x1, y1]: [usize; 4]) -> f64 {+ assert_eq!(p.len(), 96 * 54 * 4);+ let sum: f64 = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (y * 96 + x) * 4)).map(|k| p[k] as f64 + p[k + 1] as f64 + p[k + 2] as f64).sum();+ sum / (3 * (x1 - x0) * (y1 - y0)) as f64+}++/// A world of a white wall (2 m, at z = 0), a black sky and a camera before the wall at `z`, with three materials:+/// 1 white, 2 black, 3 as given.+fn wall_world(z: f32, third: serde_json::Value) -> World {+ let json = |v: serde_json::Value| serde_json::from_value::<crate::desc::Material>(v).unwrap();+ let plain = |c: f32| serde_json::json!({ "name": "m", "color": [c, c, c], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });+ let mut w = World::default();+ w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [0.0, 0.0, 0.0], "intensity": 0, "skyLightIntensity": 0 })), ..w.environment.clone() });+ w.set_material(1, json(plain(0.8)));+ w.set_material(2, json(plain(0.0)));+ w.set_material(3, json(third));+ w.set_geometry(1, Geometry { positions: vec![-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 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(10, "wall".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();+ w.set_object(4, "camera".into(), None, Kind::Camera(camera(50.0, None, manual(0.0))), true, false).unwrap();+ w.set_transform(4, Vec3::new(0.0, 0.0, z), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ w.set_settings(Settings { camera: Some(4), ..Default::default() });+ w+}++/// Triangles as a geometry of corners of their own, with one normal.+fn soup(t: &[[[f32; 3]; 3]], normal: [f32; 3], groups: Vec<[u32; 3]>) -> Geometry {+ Geometry { positions: t.iter().flatten().flatten().copied().collect(), normals: normal.repeat(3 * t.len()), uvs: vec![0.0; 6 * t.len()], indices: (0..3 * t.len() as u32).collect(), groups, colors: vec![] }+}++/// A wall with a dark triangle and three emitting ones close before it, at right angles to each other (one parallel+/// to the wall, one upright, one level): one mesh of two sections (the emitters its second), or with `apart` a mesh+/// each. (At right angles: light sampling picks between emitters of one material by power, so a ray's weight for+/// one read as another's differs by their cosines alone. Three: whichever entry a wrong index names, one of the+/// first two is not it.)+fn emitters_world(apart: bool) -> World {+ let dark = [[-0.95, -0.95, 0.05], [-0.8, -0.95, 0.05], [-0.8, -0.8, 0.05]];+ let lit = [[[-0.4, -0.1, 0.12], [-0.1, -0.1, 0.12], [-0.25, 0.16, 0.12]], [[0.3, -0.65, 0.02], [0.3, -0.35, 0.02], [0.3, -0.5, 0.3]], [[0.4, 0.6, 0.02], [0.8, 0.6, 0.02], [0.6, 0.6, 0.3]]];+ let mut w = wall_world(2.6, serde_json::json!({ "name": "glow", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 1.5, "doubleSided": true }));+ if apart {+ for (k, (t, material)) in [(dark, 2), (lit[0], 3), (lit[1], 3), (lit[2], 3)].into_iter().enumerate() {+ w.set_geometry(20 + k as u32, soup(&[t], [0.0, 0.0, 1.0], vec![])).unwrap();+ w.set_object(20 + k as u32, format!("part{k}"), None, Kind::Mesh { geometry: 20 + k as u32, material, own_blas: false, materials: vec![] }, true, false).unwrap();+ }+ } else {+ w.set_geometry(20, soup(&[dark, lit[0], lit[1], lit[2]], [0.0, 0.0, 1.0], vec![[0, 3, 0], [3, 9, 1]])).unwrap();+ w.set_object(20, "lamps".into(), None, Kind::Mesh { geometry: 20, material: 2, own_blas: false, materials: vec![2, 3] }, true, false).unwrap();+ }+ w+}++/// The wall beside `emitters_world`'s first two emitters, in a picture of 96 x 54: x0, y0, x1, y1.+const BESIDE_EMITTERS: [[usize; 4]; 2] = [[34, 19, 50, 35], [49, 33, 61, 44]];++/// Emitters in a section that is not its mesh's first, close before a wall: the wall beside two of them is lit as+/// by the same triangles a mesh each (the same rays: the two pictures are one). A light sample is told its emitter's section, whose row has the material that emits; a surface's own ray+/// that meets one finds it in that section.+#[test]+fn emitters_in_a_meshs_second_section_light_as_meshes_of_their_own() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let (mut one, mut each) = match (open(&emitters_world(false)), open(&emitters_world(true))) {+ (Ok(a), Ok(b)) => (a, b),+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),+ };+ let e = &one.sc.tables.emitter_tris;+ assert!(e.len() == 3 && e.iter().all(|e| e.inst != crate::NO_INST && e.part == 1), "the mesh's three emitters, of its second section");+ let (pa, pb) = (picture(&mut one, 96), picture(&mut each, 96));+ for region in BESIDE_EMITTERS {+ let (a, b) = (region_mean(&pa, region), region_mean(&pb, region));+ assert!(b > 30.0 && (a / b - 1.0).abs() < 0.01, "the wall beside an emitter ({region:?}): {a:.1} of 255 as one mesh's second section, {b:.1} as meshes of their own");+ }+}++/// Offline, a surface's own ray that meets an emitter weighs it against the light sample that could have picked it,+/// by that triangle's entry of the light list: its section's first and its index on (under software traversal's+/// units its tree's leaf has the index). The same wall, lit alike by the emitters as one section and as a mesh each+/// (a mesh of one triangle: index 0).+#[test]+fn a_ray_that_meets_an_emitter_weighs_it_by_that_triangles_entry() {+ let g = match gpu::Gpu::new() {+ Ok(g) => g,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ let lit = |apart: bool| {+ let mut sc = scene::build(&emitters_world(apart), Path::new(".."), &crate::default_presets_dir(), None).unwrap();+ (sc.width, sc.height) = (96, 54);+ // (Under software traversal with units, as a live view has the scene.)+ let prep = crate::prepare_as(g.hwrt, true, &mut sc, &mut vec![]);+ let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 64, &mut vec![]).unwrap();+ BESIDE_EMITTERS.map(|[x0, y0, x1, y1]| (y0..y1).flat_map(|y| (x0..x1).map(move |x| y * 96 + x)).map(|k| frame.color[k].iter().sum::<f32>() as f64).sum::<f64>() / (3 * (x1 - x0) * (y1 - y0)) as f64)+ };+ let (one, each) = (lit(false), lit(true));+ for ((a, b), region) in one.into_iter().zip(each).zip(BESIDE_EMITTERS) {+ assert!(b > 0.01 && (a / b - 1.0).abs() < 0.003, "the wall beside an emitter ({region:?}): {a:.4} as one mesh's second section, {b:.4} as meshes of their own");+ }+}++/// The light a surface's own ray brings back from what it meets is that surface's from a view's first frames on,+/// while the cache is cold and such a pixel is left to the kernel's second pass: a wall lit by nothing but a patch+/// under a spot light is lit alike with the patch a mesh of its own, the second section of a mesh whose first is+/// black, and (hardware traversal, which draws particles) a particle that follows a black one. (The record a pixel+/// is left by says which section its ray met; a triangle no instance places is its own row.)+#[test]+fn a_first_frames_bounce_is_off_the_section_the_ray_met() {+ 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 quad = |x: f32, z: f32, h: f32| [[[x - h, -0.7, z + h], [x + h, -0.7, z + h], [x + h, -0.7, z - h]], [[x - h, -0.7, z + h], [x + h, -0.7, z - h], [x - h, -0.7, z - h]]];+ let (far, patch) = (quad(-3.0, 3.0, 0.05), quad(0.0, 0.75, 0.5));+ // (`how` 0: the patch a mesh of its own; 1: a mesh's second section; 2: a particle.)+ let scene = |how: u32| {+ let mut w = wall_world(3.0, serde_json::json!({ "name": "patch", "color": [0.8, 0.8, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true }));+ let spot = serde_json::from_value(serde_json::json!({ "type": "spot", "color": [1, 1, 1], "castShadow": true, "intensity": 60, "radius": 0, "range": 0, "angle": 0.25, "penumbra": 0.2 })).unwrap();+ w.set_object(21, "spot".into(), None, Kind::Light(spot), true, false).unwrap();+ w.set_transform(21, Vec3::new(0.0, 1.4, 0.75), glam::Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();+ match how {+ 0 => {+ for (k, (t, material)) in [(far, 2), (patch, 3)].into_iter().enumerate() {+ w.set_geometry(30 + k as u32, soup(&t, [0.0, 1.0, 0.0], vec![])).unwrap();+ w.set_object(30 + k as u32, format!("part{k}"), None, Kind::Mesh { geometry: 30 + k as u32, material, own_blas: false, materials: vec![] }, true, false).unwrap();+ }+ }+ 1 => {+ w.set_geometry(30, soup(&[far, patch].concat(), [0.0, 1.0, 0.0], vec![[0, 6, 0], [6, 6, 1]])).unwrap();+ w.set_object(30, "floor".into(), None, Kind::Mesh { geometry: 30, material: 2, own_blas: false, materials: vec![2, 3] }, true, false).unwrap();+ }+ _ => {+ for (id, name, material, at) in [(30, "far", 2, "vec3<f32>(-3.0, -0.7, 3.0), vec3<f32>(0.05, 0.0, 0.0), vec3<f32>(0.0, 0.0, -0.05)"), (31, "patch", 3, "vec3<f32>(0.0, -0.7, 0.75), vec3<f32>(0.5, 0.0, 0.0), vec3<f32>(0.0, 0.0, -0.5)")] {+ w.set_particle_fn(name, format!("fn pf_{name}(i: PIn, p: array<vec4<f32>, 8>) -> POut {{ return POut({at}, true, vec4<f32>(0.0)); }}"), String::new());+ w.set_object(id, name.into(), None, Kind::Particles { count: 1, emitter: name.into(), params: vec![], material, emitter_area: 0.0 }, true, false).unwrap();+ }+ }+ }+ w+ };+ // (The wall above the patch: lit by nothing but what the patch sends back.)+ let region = [39, 22, 57, 38];+ let mut lit = vec![];+ for how in 0..3 {+ let mut live = match open(&scene(how)) {+ Ok(c) if how == 2 && !c.g.hwrt => break,+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ lit.push(region_mean(&picture(&mut live, 2), region));+ }+ assert!(lit[0] > 20.0 && lit[1..].iter().all(|x| (x / lit[0] - 1.0).abs() < 0.1), "the wall above the patch after two frames, of 255: {lit:.1?} (the patch a mesh, a mesh's second section, a particle)");+}++/// A particle of a cutout's material is tested by its own material (its triangle's row has it): one whose opacity is+/// under its material's alpha test is not there, before a wall the sun lights, after a particle of another material.+#[test]+fn a_cutout_particle_is_tested_by_its_own_material() {+ 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 scene = |cut: bool| {+ let mut w = wall_world(3.0, serde_json::json!({ "name": "cut", "color": [0, 0, 0], "opacity": 0.3, "alphaTest": 0.5, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true }));+ let sun = serde_json::from_value(serde_json::json!({ "type": "directional", "color": [1.0, 1.0, 1.0], "castShadow": true, "intensity": 1.0, "angularDiameter": 0.5 })).unwrap();+ w.set_object(20, "sun".into(), None, Kind::Light(sun), true, false).unwrap();+ for (id, name, material, at) in [(30, "solid", 1, "vec3<f32>(-0.8, -0.8, 0.3), vec3<f32>(0.05, 0.0, 0.0), vec3<f32>(0.0, 0.05, 0.0)"), (31, "cut", 3, "vec3<f32>(0.0, 0.0, 0.5), vec3<f32>(0.5, 0.0, 0.0), vec3<f32>(0.0, 0.5, 0.0)")] {+ if cut || id == 30 {+ w.set_particle_fn(name, format!("fn pf_{name}(i: PIn, p: array<vec4<f32>, 8>) -> POut {{ return POut({at}, true, vec4<f32>(0.0)); }}"), String::new());+ w.set_object(id, name.into(), None, Kind::Particles { count: 1, emitter: name.into(), params: vec![], material, emitter_area: 0.0 }, true, false).unwrap();+ }+ }+ w+ };+ let (mut with, mut without) = match (open(&scene(true)), open(&scene(false))) {+ (Ok(a), Ok(b)) if a.g.hwrt => (a, b),+ (Ok(_), Ok(_)) => return eprintln!("skipped: no hardware RT"),+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),+ };+ // (The wall's middle, behind the particle.)+ let region = [40, 19, 56, 35];+ let (a, b) = (region_mean(&picture(&mut with, 16), region), region_mean(&picture(&mut without, 16), region));+ assert!(b > 30.0 && (a / b - 1.0).abs() < 0.05, "the wall behind the particle: {a:.1} of 255 with it, {b:.1} without");+}++/// An emitting particle lights both its sides (a rect light's card alone lights one, and whether an emitter is one+/// its own row's material says): a wall behind it is lit alike with the particle's face or its back to it, in a+/// scene whose first triangles are a light's card.+#[test]+fn an_emitting_particle_lights_both_its_sides_beside_a_lights_card() {+ 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 scene = |turned: bool| {+ let mut w = wall_world(3.0, serde_json::json!({ "name": "glow", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 3, "doubleSided": true }));+ // (A card far behind the camera, turned away.)+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 0.05, "width": 0.2, "height": 0.2, "range": 0 })).unwrap();+ w.set_object(21, "card".into(), None, Kind::Light(card), true, false).unwrap();+ w.set_transform(21, Vec3::new(0.0, 0.0, 9.0), glam::Quat::from_rotation_y(std::f32::consts::PI), Vec3::ONE).unwrap();+ let v = if turned { -0.15 } else { 0.15 };+ w.set_particle_fn("glow", format!("fn pf_glow(i: PIn, p: array<vec4<f32>, 8>) -> POut {{ return POut(vec3<f32>(0.0, 0.0, 0.3), vec3<f32>(0.15, 0.0, 0.0), vec3<f32>(0.0, {v}, 0.0), true, vec4<f32>(0.0)); }}"), String::new());+ w.set_object(31, "glow".into(), None, Kind::Particles { count: 1, emitter: "glow".into(), params: vec![], material: 3, emitter_area: 0.09 }, true, false).unwrap();+ w+ };+ let (mut face, mut back) = match (open(&scene(false)), open(&scene(true))) {+ (Ok(a), Ok(b)) if a.g.hwrt => (a, b),+ (Ok(_), Ok(_)) => return eprintln!("skipped: no hardware RT"),+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),+ };+ let e = &face.sc.tables.emitter_tris;+ assert!(e.first().is_some_and(|e| !e.nominal) && e.iter().any(|e| e.nominal), "the light list: a card's triangles first, then the particle's");+ // (The wall beside the particle, as the camera sees it.)+ let region = [35, 20, 43, 34];+ let (a, b) = (region_mean(&picture(&mut face, 64), region), region_mean(&picture(&mut back, 64), region));+ assert!(b > 20.0 && (a / b - 1.0).abs() < 0.05, "the wall beside the particle: {a:.1} of 255 with its back to the wall, {b:.1} with its face");+}++/// Primary visibility by rasterization (`Raster`): a path starts at the triangle the pass drew at its pixel, which is+/// the one its camera ray hits: the picture is the traced one's. The pass draws world-space triangles and is off in a+/// scene with instances, which every mesh of a world is: a scene of rect lights' cards alone.+#[test]+fn a_rasterized_first_hit_is_the_traced_one() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let mut w = World::default();+ // (Turned to face the camera: a card lights the side of its node's -z.)+ for (id, at, turn) in [(21, Vec3::new(-0.9, 0.2, 0.0), 3.6), (22, Vec3::new(0.8, -0.3, 1.0), 2.5)] {+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 0.6, 0.3], "castShadow": true, "intensity": 3, "width": 1.2, "height": 0.8, "range": 0 })).unwrap();+ w.set_object(id, format!("card{id}"), None, Kind::Light(card), true, false).unwrap();+ w.set_transform(id, at, glam::Quat::from_rotation_y(turn), Vec3::ONE).unwrap();+ }+ w.set_object(4, "camera".into(), None, Kind::Camera(camera(50.0, None, manual(0.0))), true, false).unwrap();+ w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ w.set_settings(Settings { camera: Some(4), ..Default::default() });+ let (mut traced, mut drawn) = match (open(&w), open(&w)) {+ (Ok(a), Ok(b)) => (a, b),+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),+ };+ assert!(!drawn.sc.instanced && drawn.sc.tris.len() == 4 && traced.raster.is_none(), "a scene of four world-space triangles, traced unless asked");+ drawn.raster = Some(super::frame::Raster::new(&drawn.g, drawn.w, drawn.h));+ (drawn.kernel_bg, drawn.tl_kernel_bg) = super::kernel_bind_groups(&drawn.g, drawn.raster.as_ref(), &drawn.targets);+ let (a, b) = (picture(&mut traced, 64), picture(&mut drawn, 64));+ let lit = a.chunks_exact(4).filter(|p| p[0] > 100).count();+ assert!(lit > a.len() / 4 / 50, "the cards are in the picture ({lit} pixels)");+ // (0 steps as measured; 4.9 with each index read one word on.)+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from the traced one", apart(&a, &b));+}++/// A mesh changed in place to triangles of more vertices (a crease: its two triangles share no corner any more) takes+/// another run of vertices, and the mesh that lies after it keeps its own; changed back, it stays where it is. Each+/// is read back through its indices, and the picture is a build's.+#[test]+fn a_mesh_changed_in_place_to_more_vertices_takes_another_run() {+ 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 quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 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![] };+ let creased = |s: f32| Geometry {+ positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, -s, 0.0, s, s, 0.0, -s, s, 0.0],+ normals: [[0.0, 0.0, 1.0].repeat(3), [0.6, 0.0, 0.8].repeat(3)].concat(),+ uvs: vec![0.0; 12],+ indices: vec![0, 1, 2, 3, 4, 5],+ groups: vec![],+ colors: vec![],+ };+ let mut w = world();+ w.set_geometry(31, quad(0.3)).unwrap();+ w.set_geometry(32, quad(0.2)).unwrap();+ for (id, geometry, x) in [(40, 31, -0.5), (41, 32, 0.5)] {+ w.set_object(id, format!("o{id}"), None, Kind::Mesh { geometry, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();+ w.set_transform(id, Vec3::new(x, 0.6, 0.8), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ }+ let mut live = match open(&w) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let run = |c: &LiveCore, id: u32| {+ let m = c.sc.meshes[c.sc.instances[c.sc.tables.retained.instance(id).unwrap().instance as usize].mesh as usize];+ (m.vfirst, m.vcount)+ };+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {+ let mut fresh = open(w).unwrap();+ forget(live);+ let (a, b) = (picture(live, 32), picture(&mut fresh, 32));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ };+ let (a, b) = (run(&live, 40), run(&live, 41));+ assert_eq!((a.1, b), (4, (a.0 + 4, 4)), "two meshes of four vertices, one after the other");+ w.set_geometry(31, creased(0.3)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "creased: in place ({:?})", live.fallback);+ let creased_run = run(&live, 40);+ assert!(creased_run.1 == 6 && creased_run.0 >= b.0 + b.1 && run(&live, 41) == b, "another run of six vertices, past the other mesh's ({creased_run:?})");+ mesh_is_the_cpus("the creased mesh", &live, 40);+ mesh_is_the_cpus("the mesh after it", &live, 41);+ against_a_build("creased", &mut live, &w);+ w.set_geometry(31, quad(0.25)).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "flat again: in place ({:?})", live.fallback);+ assert_eq!(run(&live, 40), creased_run, "four vertices fit where six were");+ mesh_is_the_cpus("the mesh, flat again", &live, 40);+ mesh_is_the_cpus("the mesh after it, still", &live, 41);+ against_a_build("flat again", &mut live, &w);+}++/// Two movable rect lights' cards (world-space triangles that move, one card after the other; a still card's+/// vertices lie before theirs): each moved alone is written where it lies, the other's vertices as they were; the+/// motion vectors at its pixels are its step back (its previous positions are its own); the picture is a build's.+/// (Hardware traversal: under software traversal a world-space triangle that moves is a rebuild's.)+#[test]+fn a_moved_card_beside_another_is_written_where_it_lies() {+ 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 turn = glam::Quat::from_rotation_y(3.3);+ let mut w = world();+ let mut at = [Vec3::new(0.0, -0.8, 1.2), Vec3::new(-0.8, 0.8, 1.2), Vec3::new(0.8, 0.8, 1.2)];+ for (k, id) in [20, 21, 22].into_iter().enumerate() {+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 0.7, 0.4], "castShadow": true, "intensity": 2, "width": 0.4, "height": 0.3, "range": 0 })).unwrap();+ w.set_object(id + 100, format!("card{id}"), None, Kind::Light(card), true, k > 0).unwrap();+ w.set_transform(id + 100, at[k], turn, Vec3::ONE).unwrap();+ }+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ assert!(live.sc.dynamic.1.len() == 12 && live.sc.dynamic_verts.0 > 0, "two cards that move, four triangles, after vertices that do not");+ moving_triangles_are_the_cpus("as loaded", &live);+ picture(&mut live, 2);+ for (k, to) in [(2, Vec3::new(0.5, 0.5, 1.4)), (1, Vec3::new(-0.4, 0.3, 1.0)), (2, Vec3::new(0.9, 0.9, 1.1))] {+ let (what, before, step) = (format!("card {k} moved"), live.sc.dynamic.3.clone(), at[k] - to);+ at[k] = to;+ w.set_transform(120 + k as u32, to, turn, Vec3::ONE).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);+ let moved = (0..4).filter(|&t| live.sc.dynamic.3[t * 3..t * 3 + 3] != before[t * 3..t * 3 + 3]).collect::<Vec<_>>();+ assert!(moved == [0, 1] || moved == [2, 3], "{what}: its two triangles alone ({moved:?})");+ moving_triangles_are_the_cpus(&what, &live);+ // The frame after: where the card is seen, the way back to where it was.+ live.render(1, |_, _| {});+ let m = &live.targets.kernel.motion;+ let vectors: Vec<Vec3> = read_back::<f32>(&live, &m.buffer, m.offset, m.size).chunks_exact(4).filter(|p| p[3] > 0.5).map(|p| Vec3::new(p[0], p[1], p[2])).filter(|v| v.length() > 1e-4).collect();+ assert!(vectors.len() > 10 && vectors.iter().all(|v| (*v - step).length() < 2e-4), "{what}: {} pixels moved, each by the card's step back {step} (the first: {:?})", vectors.len(), vectors.first());+ let mut fresh = open(&w).unwrap();+ forget(&mut live);+ let (a, b) = (picture(&mut live, 32), picture(&mut fresh, 32));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ }+}++/// A particle that drifts: its vertices' previous positions are the pass's last (the motion vectors at its pixels+/// are its step back), and the pass leaves its vertices' UVs as the build made them.+#[test]+fn a_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let mut w = world();+ w.set_particle_fn("drift", "fn pf_drift(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(-0.6 + 0.6 * i.time, 0.5, 1.0), vec3<f32>(0.3, 0.0, 0.0), vec3<f32>(0.0, 0.3, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ w.set_object(18, "drift".into(), None, Kind::Particles { count: 1, emitter: "drift".into(), params: vec![], material: 1, emitter_area: 0.01 }, true, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ // (The vertices that move: the particle's six.)+ let vertices = |c: &LiveCore| -> (Vec<[f32; 3]>, Vec<[f32; 2]>) {+ let (first, n) = (c.sc.dynamic_verts.0 as u64, c.sc.dynamic_verts.1 as u64);+ let size = crate::indexed::VERTEX_BYTES as u64;+ let v: Vec<crate::indexed::Vertex> = read_back(c, &c.sc.up.vertices, first * size, n * size);+ (v.iter().map(|v| [v[0][0], v[0][1], v[0][2]]).collect(), v.iter().map(|v| [v[0][3], v[1][3]]).collect())+ };+ let built = vertices(&live);+ assert!(built.1.len() == 6 && built.1.iter().any(|uv| uv[0] != 0.0) && built.1.iter().any(|uv| uv[1] != 0.0), "the particle's six vertices, with the build's UVs ({:?})", built.1);+ live.fixed_dt = Some(1.0 / 60.0);+ for _ in 0..4 {+ live.advance_time(1.0 / 60.0);+ live.render(1, |_, _| {});+ }+ let now = vertices(&live);+ assert!(now.0 != built.0 && now.1 == built.1, "the pass moved the vertices and left their UVs ({:?} -> {:?})", built.1, now.1);+ let (m, step) = (&live.targets.kernel.motion, Vec3::new(-0.6 / 60.0, 0.0, 0.0));+ let vectors: Vec<Vec3> = read_back::<f32>(&live, &m.buffer, m.offset, m.size).chunks_exact(4).filter(|p| p[3] > 0.5).map(|p| Vec3::new(p[0], p[1], p[2])).filter(|v| v.length() > 1e-4).collect();+ assert!(vectors.len() > 20 && vectors.iter().all(|v| (*v - step).length() < 2e-4), "{} pixels moved, each by the particle's step back {step} (the first: {:?})", vectors.len(), vectors.first());+}++/// A stateful GPU particle that drifts, as the one above: its pass keeps its vertices' last positions too, a vertex+/// each, and leaves their UVs.+#[test]+fn a_gpu_particle_that_moves_has_its_last_positions_and_keeps_its_uvs() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let mut w = world();+ let emit = "fn pe_drift(i: EIn, p: array<vec4<f32>, 8>) -> PState { var s: PState; s.pos = i.at; s.life = 1000.0; s.color = i.color; s.size = 0.3; s.vel = vec3<f32>(0.6, 0.0, 0.0); return s; }";+ w.set_particle_program("drift", emit.into(), "fn pu_drift(s: PState, i: UIn, p: array<vec4<f32>, 8>) -> PState { return s; }".into(), String::new());+ w.set_object(18, "drift".into(), None, Kind::GpuParticles { capacity: 1, program: "drift".into(), params: vec![], material: 1, emitter_area: 0.01, rate: 0.0, collide: Default::default() }, true, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ // (The game spawns one: the next commit takes it.)+ w.spawn_particles(18, &[-0.6, 0.5, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0]).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a spawn: in place ({:?})", live.fallback);+ let vertices = |c: &LiveCore| -> (Vec<[f32; 3]>, Vec<[f32; 2]>) {+ let (first, n) = (c.sc.dynamic_verts.0 as u64, c.sc.dynamic_verts.1 as u64);+ let size = crate::indexed::VERTEX_BYTES as u64;+ let v: Vec<crate::indexed::Vertex> = read_back(c, &c.sc.up.vertices, first * size, n * size);+ (v.iter().map(|v| [v[0][0], v[0][1], v[0][2]]).collect(), v.iter().map(|v| [v[0][3], v[1][3]]).collect())+ };+ let built = vertices(&live);+ assert!(built.1.len() == 6 && built.1.iter().any(|uv| uv[0] != 0.0) && built.1.iter().any(|uv| uv[1] != 0.0), "the particle's six vertices, with the build's UVs ({:?})", built.1);+ live.fixed_dt = Some(1.0 / 60.0);+ for _ in 0..6 {+ live.advance_time(1.0 / 60.0);+ live.render(1, |_, _| {});+ }+ let now = vertices(&live);+ assert!(now.0 != built.0 && now.1 == built.1, "the pass moved the vertices and left their UVs ({:?} -> {:?})", built.1, now.1);+ let (m, step) = (&live.targets.kernel.motion, Vec3::new(-0.6 / 60.0, 0.0, 0.0));+ let vectors: Vec<Vec3> = read_back::<f32>(&live, &m.buffer, m.offset, m.size).chunks_exact(4).filter(|p| p[3] > 0.5).map(|p| Vec3::new(p[0], p[1], p[2])).filter(|v| v.length() > 1e-4).collect();+ assert!(vectors.len() > 20 && vectors.iter().all(|v| (*v - step).length() < 2e-4), "{} pixels moved, each by the particle's step back {step} (the first: {:?})", vectors.len(), vectors.first());+}++/// A skinned model's primitive whose file has no normals is shaded by its triangles' own, which the kernel makes where+/// a triangle is hit: offline, a camera before the largest such triangle of a posed model sees that triangle's normal.+/// (Under either traversal: the model's mesh an instance's, or a unit's.)+#[test]+fn a_skinned_primitive_without_normals_is_shaded_by_its_triangles() {+ let g = match gpu::Gpu::new() {+ Ok(g) => g,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ let mut w = world();+ let pose = crate::desc::Animation { clip: "bend".into(), time: 0.4, r#loop: true, nodes: Default::default() };+ w.set_object(31, "m31".into(), None, Kind::Model { uri: "tests/render/data/skin-blend.glb".into(), nodes: None, animation: Some(pose), functions: vec![] }, true, false).unwrap();+ w.set_transform(31, Vec3::new(0.0, 6.0, 2.0), glam::Quat::from_rotation_y(0.3), Vec3::splat(2.5)).unwrap();+ let built = |w: &World| {+ let mut sc = scene::build(w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();+ (sc.width, sc.height) = (96, 54);+ // (Under software traversal with units, as a live view has the scene: without them the model is flattened+ // into world-space triangles with the CPU's normals.)+ let prep = crate::prepare_as(g.hwrt, true, &mut sc, &mut vec![]);+ (sc, prep)+ };+ // The mesh's triangles whose three vertices have no normal, as the instance places them: the largest.+ let (centre, normal, edge) = {+ let (sc, prep) = built(&w);+ let m = sc.meshes.iter().position(|m| m.deforms).expect("a deforming mesh");+ let (im, world, x) = (sc.meshes[m], sc.instances.iter().find(|i| i.mesh as usize == m).unwrap().world, &sc.indexed);+ let first = prep.groups.iter().sum::<usize>() + im.first as usize;+ let bare = x.indices[first..first + im.count as usize].iter().filter(|t| t.iter().all(|&v| x.vertices[(im.vfirst + v) as usize][1][..3] == [0.0; 3]));+ let placed = bare.map(|t| t.map(|v| world.transform_point3(Vec3::from_slice(&x.vertices[(im.vfirst + v) as usize][0][..3]))));+ let p = placed.max_by(|a, b| (a[1] - a[0]).cross(a[2] - a[0]).length().total_cmp(&(b[1] - b[0]).cross(b[2] - b[0]).length())).expect("triangles without normals");+ ((p[0] + p[1] + p[2]) / 3.0, (p[1] - p[0]).cross(p[2] - p[0]).normalize(), (p[1] - p[0]).length().max((p[2] - p[0]).length()))+ };+ w.set_transform(4, centre + normal * edge, glam::Quat::from_rotation_arc(Vec3::NEG_Z, -normal), Vec3::ONE).unwrap();+ let (sc, prep) = built(&w);+ let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 1, &mut vec![]).unwrap();+ let seen = Vec3::from(frame.normal[27 * 96 + 48]);+ assert!(seen.dot(normal).abs() > 0.999 && (seen.length() - 1.0).abs() < 1e-3, "the picture's middle has the normal {seen}; the triangle's is {normal}");+}+/// Each edit, on one view that takes them one after another, against a view built from the world as it is then.#[test]fn edits_in_place_leave_what_a_build_does() {@@ -235,7 +832,7 @@ fn a_resized_view_is_a_view_built_at_that_size() {};w.take_changes();picture(&mut live, 8);- let (verts, cache, out) = (live.sc.up.verts.clone(), live.targets.kernel.cache.val.buffer.clone(), live.targets.out.clone());+ let (verts, cache, out) = (live.sc.up.vertices.clone(), live.targets.kernel.cache.val.buffer.clone(), live.targets.out.clone());live.resize(96, 54).unwrap();assert!(live.targets.out == out && !live.reset, "the same size: the view as it was");let against = |what: &str, live: &mut LiveCore, w: &World| {@@ -252,7 +849,7 @@ fn a_resized_view_is_a_view_built_at_that_size() {for size in [(160, 90), (54, 96), (97, 55), (5, 3), (1, 1), (96, 54)] {live.resize(size.0, size.1).unwrap();assert!(live.reset && (live.w, live.h) == size, "{size:?}: the histories start again");- assert!(live.sc.up.verts == verts, "{size:?}: the scene's data is as it was");+ assert!(live.sc.up.vertices == verts, "{size:?}: the scene's data is as it was");assert!(live.g.merged || live.targets.kernel.cache.val.buffer == cache, "{size:?}: the radiance cache is as it was");against(&format!("{size:?}"), &mut live, &w);}@@ -416,20 +1013,17 @@ fn an_instanced_object_added_in_place_keeps_its_copies_data() {/// triangle placed by the instance, to rounding), its instance and moving flag, and a ray that hits its triangle/// finds it (the attributes' number, from the instance's first).fn list_is_its_triangles(what: &str, c: &LiveCore) {- let read = |b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {- 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 bytes = to.slice(..).get_mapped_range().unwrap().to_vec();- bytes- };+ use crate::heap::Stream;+ let read = |b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> { read_back(c, b, at, bytes) };let (tables, up) = (&c.sc.tables, &c.sc.up);let size = std::mem::size_of::<crate::GpuEmitterTri>();let list = read(&up.heap.buffer, up.heap.at(Table::EmitterTris), (tables.emitter_tris.len() * size) as u64);- let (verts, attrs) = (read(&up.verts, 0, up.verts.size()), read(&up.attrs, 0, up.attrs.size()));+ // (The triangles as the kernel reads them: three indices each; the vertices; the rows of those that have one.)+ let vertices: Vec<crate::indexed::Vertex> = read_back(c, &up.vertices, 0, up.vertices.size());+ let index: Vec<u32> = read_back(c, &up.words.buffer, up.words.at(Stream::Indices), up.words.cap(Stream::Indices));+ let tri_rows: Vec<[u32; 4]> = read_back(c, &up.words.buffer, up.words.at(Stream::Triangles), up.words.cap(Stream::Triangles) / 16 * 16);+ // (Software traversal: the trees' leaves, whose ids say a mesh's triangle's section and its index there.)+ let leaves: Vec<crate::indexed::Leaf> = if c.g.hwrt { vec![] } else { read_back(c, &up.bg_parts.leaves, 0, up.bg_parts.leaves.size() / crate::indexed::LEAF_BYTES as u64 * crate::indexed::LEAF_BYTES as u64) };let codes = crate::emitter_codes(&tables.emitter_tris, &crate::emitter_order(&tables.emitter_tris, tables.light_tree.as_ref()), tables.light_tree.as_ref());// (The CDF as the kernel reads it: an emitter that is not the tree's is found by the entry its code names.)let cdf = read(&up.heap.buffer, up.heap.at(Table::Emitters), (tables.emitter_tris.len() * 16) as u64);@@ -448,28 +1042,39 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {if e.area <= 0.0 {continue;}- let rows: Vec<[f32; 4]> = (0..3).map(|k| bytemuck::pod_read_unaligned(&verts[(e.tri as usize * 3 + k) * 16..][..16])).collect();- let a: scene::GpuTriAttr = bytemuck::pod_read_unaligned(&attrs[e.tri as usize * 96..][..96]);+ // (A mesh's indices count from its instance's first vertex; a world-space triangle's from the first of all.)+ let base = if e.inst == crate::NO_INST { 0 } else { c.sc.instances[e.inst as usize].verts };+ let p: [glam::Vec3A; 3] = std::array::from_fn(|k| glam::Vec3A::from_slice(&vertices[(base + index[e.tri as usize * 3 + k]) as usize][0][..3]));if e.inst == crate::NO_INST {- assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code & !crate::EMITTER_MOVES), "{what}: emitter {i} of the list against its triangle {}", e.tri);- assert_eq!(a.x[3].to_bits(), i as u32 + 1, "{what}: triangle {} names its emitter", e.tri);+ // (A triangle no instance places has a row: its material, its object, its flags, its emitter + 1. The+ // list's record names the row: the triangle's own.)+ assert_eq!(r, crate::GpuEmitterTri::of(e, p, code & !crate::EMITTER_MOVES), "{what}: emitter {i} of the list against its triangle {}", e.tri);+ assert_eq!((r.part, tri_rows[e.tri as usize][3]), (e.tri, i as u32 + 1), "{what}: emitter {i}'s record names its triangle's row, and the row the emitter");} else {// (The record as the GPU has it.)let (inst, record) = (&c.sc.instances[e.inst as usize], bytemuck::pod_read_unaligned::<scene::GpuInstance>(&records[e.inst as usize * record_size..][..record_size]));- let at = |k: usize| glam::Vec3::new(rows[k][0], rows[k][1], rows[k][2]);- let placed = [inst.world.transform_point3(at(0)), inst.world.transform_vector3(at(1)), inst.world.transform_vector3(at(2))];- assert_eq!((r.tri, r.inst, r.code), (e.tri, e.inst, code), "{what}: emitter {i}'s words");+ let placed = [inst.world.transform_point3(p[0].into()), inst.world.transform_vector3((p[1] - p[0]).into()), inst.world.transform_vector3((p[2] - p[0]).into())];+ assert_eq!(record.info[2], inst.verts, "{what}: instance {}'s record has its mesh's first vertex", e.inst);+ assert_eq!((r.tri, r.inst, r.code, r.part), (e.tri, e.inst, code, e.part), "{what}: emitter {i}'s words (its triangle, its instance, its code, its section)");for (got, want) in [r.v0, r.e1, r.e2].into_iter().zip(placed) {assert!((glam::Vec3::from(got) - want).length() <= 1e-4 * (1.0 + want.length()), "{what}: emitter {i}'s triangle {got:?}, its instance places it at {want:?}");}// Its section's row as the GPU has it says the material and where the section's emitters start, the- // triangle its index among them.- let at = (record.info[3] + a.uv[3].to_bits()) as usize;+ // triangle its index among them: its place after the section's first triangle (hardware traversal), or+ // what its tree's leaf says (software traversal: a tree has a mesh's triangles in its own order).+ let at = (record.info[3] + e.part) as usize;let row: scene::Row = bytemuck::pod_read_unaligned(&gpu_rows[at * 16..][..16]);assert_eq!(row, c.sc.rows[at], "{what}: row {at} on the GPU is the scene's");assert_eq!(record.info[3], inst.rows, "{what}: instance {}'s record has its rows", e.inst);assert!(inst.first_emitter <= i as u32, "{what}: emitter {i} is of instance {}'s run, from {}", e.inst, inst.first_emitter);- assert_eq!((row[2].wrapping_add(a.x[3].to_bits()), scene::row_material(&row)), (i as u32, e.mat), "{what}: triangle {} of instance {} finds its emitter, of its row's material", e.tri, e.inst);+ let rank = if c.g.hwrt {+ e.tri.wrapping_sub(row[1])+ } else {+ let l = &leaves[e.tri as usize];+ assert_eq!(l[0][3].to_bits(), e.part, "{what}: triangle {}'s leaf has its section", e.tri);+ l[1][3].to_bits()+ };+ assert_eq!((row[2].wrapping_add(rank), scene::row_material(&row)), (i as u32, e.mat), "{what}: triangle {} of instance {} finds its emitter, of its row's material", e.tri, e.inst);}alive += 1;}@@ -909,9 +1514,10 @@ fn the_light_list_holds_its_triangles() {let spark = live.sc.tables.emitter_tris.iter().position(|e| e.nominal).expect("the particles are emitters");let side = |c: &LiveCore| {let at = c.sc.up.heap.at(Table::EmitterTris) + (spark * std::mem::size_of::<crate::GpuEmitterTri>()) as u64;- let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 48, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let size = std::mem::size_of::<crate::GpuEmitterTri>() as u64;+ let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size, 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(&c.sc.up.heap.buffer, at, &to, 0, 48);+ e.copy_buffer_to_buffer(&c.sc.up.heap.buffer, at, &to, 0, size);c.g.queue.submit([e.finish()]);to.slice(..).map_async(wgpu::MapMode::Read, |_| {});c.g.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();@@ -2686,58 +3292,18 @@ fn a_posed_skinned_model_is_added_in_place() {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 read = |c: &LiveCore, b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<f32> { read_back(c, b, at, bytes) };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 cpu = |c: &LiveCore, id: u32, a: &crate::desc::Animation| skinned_on_cpu(c, &c.sc.tables.retained.skinned[of(c, id)], a).p;+ // A model's mesh on the GPU against the CPU skin of `now`; its previous positions 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);+ skinned_is_the_cpus(what, c, &c.sc.tables.retained.skinned[of(c, id)], &format!("m{id}"), now, before);};let built = live.sc.tables.retained.skinned.len();- let prev_size = live.sc.up.prev_verts.size();+ let prev_size = live.sc.up.prev_vertices.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'");+ assert!(live.sc.dynamic.1.len() == 6 && i.prev == i.verts - live.sc.dynamic_verts.0 && i.prev >= 6, "a mesh's previous positions lie after the card's six vertices'");}// One of a model the scene has, in a pose of its own.@@ -2747,7 +3313,7 @@ fn a_posed_skinned_model_is_added_in_place() {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");+ assert!(live.sc.up.prev_vertices.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);@@ -2766,7 +3332,8 @@ fn a_posed_skinned_model_is_added_in_place() {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 card = 6 * crate::indexed::VERTEX_BYTES as u64;+ assert_eq!(read(&live, &live.sc.up.prev_vertices, 0, card), read(&live, &live.sc.up.vertices, live.sc.dynamic_verts.0 as u64 * crate::indexed::VERTEX_BYTES as u64, card), "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, |_, _| {});@@ -2782,10 +3349,8 @@ fn a_posed_skinned_model_is_added_in_place() {// 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 corners = |v: &[f32]| -> Vec<Vec3> { v.chunks_exact(3).map(Vec3::from_slice).collect() };+ corners(&cpu(c, id, &bend(0.8))).iter().zip(corners(&cpu(c, id, before))).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);@@ -2810,12 +3375,13 @@ fn a_posed_skinned_model_is_added_in_place() {// 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>>());+ let rooms_size = |c: &LiveCore| (c.sc.up.vertices.size(), c.sc.up.words.cap(crate::heap::Stream::Indices));+ let (size, ids) = (rooms_size(&live), (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");+ assert!(rooms_size(&live).0 > size.0 && rooms_size(&live).1 > size.1, "the vertices' buffer and the triangles' indices were made again, larger ({size:?} -> {:?})", rooms_size(&live));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);@@ -2850,16 +3416,18 @@ fn a_posed_skinned_model_is_added_in_place() {// 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]);+ let (mesh, prev, tri, vertices) = (sk.mesh, live.sc.instances[sk.instance as usize].prev, live.sc.gpu_instances[sk.instance as usize].info[0], live.sc.meshes[sk.mesh as usize].vcount);+ let first_vertex = live.sc.instances[sk.instance as usize].verts;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");+ assert!(live.sc.edit.prev.free.iter().any(|(&at, &n)| at <= prev as usize && prev as usize + vertices as usize <= 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");+ assert_eq!(live.sc.instances[next.instance as usize].verts, first_vertex, "and its vertices");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);@@ -2900,11 +3468,14 @@ fn a_posed_skinned_model_is_added_in_place() {let i = c.sc.tables.retained.instance(id).unwrap().instance as usize;(c.sc.gpu_instances[i].info[0], c.sc.instances[i].prev)};+ // (A model's vertices: fewer than three a triangle.)+ let nv = live.sc.meshes[live.sc.tables.retained.skinned[of(&live, 35)].mesh as usize].vcount;+ assert!(nv > 0 && nv < 12, "the model's four triangles share vertices ({nv})");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");+ assert_eq!((tb, pb), (ta + 4, pa + nv), "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);@@ -3080,47 +3651,9 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {// (A mesh, its instance and its object, for each deforming mesh of the scene.)let deforming = |c: &LiveCore| c.sc.tables.retained.skinned.iter().map(|g| (g.uri.clone(), g.order.clone(), g.instance, g.object)).collect::<Vec<_>>();assert_eq!(deforming(&live).len(), 4, "four models, each a mesh of its own");- 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- };- // What the CPU skin gives a mesh for a pose: vertices (48 B a triangle), attributes (96 B), BLAS input (36 B).- let cpu = |c: &LiveCore, g: usize, a: &crate::desc::Animation| {- 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.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)- };- // (Numbers within a rounding of each other; the words that are no numbers, a flag, a section, a rank, the same.)- 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());- }- };- let gpu = |c: &LiveCore, g: usize| {- 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;- // (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), up.accel.as_ref().map(|a| read(c, &a.verts, k * 36, n * 36)), read(c, &up.prev_verts, prev as u64 * 48, n * 48))- };+ let read = |c: &LiveCore, b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<f32> { read_back(c, b, at, bytes) };+ // What the CPU skin gives a mesh for a pose: its triangles' corners, nine numbers a triangle.+ let cpu = |c: &LiveCore, g: usize, a: &crate::desc::Animation| skinned_on_cpu(c, &c.sc.tables.retained.skinned[g], a).p;// Software traversal: a mesh's tree on the GPU has its model's tree's shape (the links, word for word) and the// pose's boxes: a leaf's its triangles' (`corners`: the CPU skin's, nine numbers a triangle), an interior node's// its two children's. The mesh's bounds are the root's, and the top tree's leaf of its unit is those, placed.@@ -3154,22 +3687,10 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {assert_eq!((leaf.bmin, leaf.bmax), (unit.lo.into(), unit.hi.into()), "{what}: the top tree has the unit by its mesh's bounds, placed");};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);- let ((v, at, b, prev), (cv, cat, cb)) = (gpu(c, g), cpu(c, g, now));- same(&format!("{what}: the vertices"), &v, &cv, &[3], 12);- // (An attribute's words: the section in `uv.w` (15), the rank in `x.w` (23), the object and a spare beside.)- same(&format!("{what}: the attributes"), &at, &cat, &[15, 21, 22, 23], 24);- if let Some(b) = b {- same(&format!("{what}: the BLAS input"), &b, &cb, &[], 9);- }- tree(&what, c, g, &cb);- same(&format!("{what}: the previous frame's vertices"), &prev, &cpu(c, g, before).0, &[3], 12);- // The CPU's own: the build's pose in the pool, the pose as it is now when asked.- let (instance, id) = (deforming(c)[g].2, deforming(c)[g].3);- let inst = &c.sc.instances[instance as usize];- 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 sk = &c.sc.tables.retained.skinned[g];+ let what = format!("{what}, {} (object {})", sk.uri, sk.object);+ let corners = skinned_is_the_cpus(&what, c, sk, &format!("m{}", sk.object), now, before);+ tree(&what, c, g, &corners);};let check = |what: &str, c: &LiveCore, now: &crate::desc::Animation, before: &crate::desc::Animation| {for g in 0..deforming(c).len() {@@ -3182,13 +3703,13 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {}};let (first, second, third) = (bend(0.0), bend(0.75), bend(0.4));- let loaded: Vec<Vec<f32>> = (0..4).map(|g| cpu(&live, g, &first).0).collect();+ let loaded: Vec<Vec<f32>> = (0..4).map(|g| cpu(&live, g, &first)).collect();for (what, now, before) in [("a new pose", &second, &first), ("the next", &third, &second)] {all(&mut w, now);assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);check(what, &live, now, before);}- assert!((0..4).all(|g| cpu(&live, g, &third).0.iter().zip(&loaded[g]).any(|(a, b)| (a - b).abs() > 0.05)), "the pose moves every mesh");+ assert!((0..4).all(|g| cpu(&live, g, &third).iter().zip(&loaded[g]).any(|(a, b)| (a - b).abs() > 0.05)), "the pose moves every mesh");// One posed alone: its mesh, and the others' as they were (their previous frame's vertices their own pose now).let alone = bend(0.15);w.set_animation(31, Some(alone.clone())).unwrap();@@ -3223,10 +3744,11 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {check("posed and moved at once", &live, &bend(0.9), &third);assert_eq!(stands(&live, 30), w.world_matrix(30), "its instance stands where the model was moved to");pictured("posed and moved at once", &mut live, &w);- // The scene's buffers made again, larger (a mesh of more triangles than the room for edits has, added in place,- // far below the view): the pass writes the new ones.- let size = live.sc.up.verts.size();- let n = 200u32;+ // The scene's buffers made again, larger (a mesh of more triangles and more vertices than the room for edits has,+ // added in place, far below the view): the pass writes the new ones.+ let rooms_size = |c: &LiveCore| (c.sc.up.vertices.size(), c.sc.up.words.cap(crate::heap::Stream::Indices));+ let size = rooms_size(&live);+ let n = (((live.sc.edit.verts.cap - live.sc.edit.verts.end) as f64).sqrt() as u32 + 1).max(200);let positions: Vec<f32> = (0..=n).flat_map(|y| (0..=n).flat_map(move |x| [x as f32, y as f32, 0.0])).collect();let indices: Vec<u32> = (0..n).flat_map(|y| (0..n).flat_map(move |x| { let k = y * (n + 1) + x; [k, k + 1, k + n + 2, k, k + n + 2, k + n + 1] })).collect();let corners = ((n + 1) * (n + 1)) as usize;@@ -3235,7 +3757,7 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {w.set_transform(40, Vec3::new(0.0, -80.0, 0.0), glam::Quat::IDENTITY, Vec3::splat(0.001)).unwrap();// (Software traversal's room does not grow: a rebuild's there.)assert_eq!(live.commit(&mut w).unwrap(), !hw, "a large mesh added: in place under hardware traversal ({:?})", live.fallback);- assert!(live.sc.up.verts.size() > size, "the triangles' buffer was made again, larger ({} -> {})", size, live.sc.up.verts.size());+ assert!(!hw || (rooms_size(&live).0 > size.0 && rooms_size(&live).1 > size.1), "the vertices' buffer and the triangles' indices were made again, larger ({size:?} -> {:?})", rooms_size(&live));if !hw {picture(&mut live, 2);}@@ -3251,12 +3773,10 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {live.render(1, |_, _| {});let m = &live.targets.kernel.motion;let moved = read(&live, &m.buffer, m.offset, m.size);- 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()- };+ let corners = |v: &[f32]| -> Vec<Vec3> { v.chunks_exact(3).map(Vec3::from_slice).collect() };let far = (0..4).map(|g| {let world = live.sc.instances[deforming(&live)[g].2 as usize].world;- corners(&cpu(&live, g, &bend(0.25)).0).iter().zip(corners(&cpu(&live, g, &bend(0.9)).0)).map(|(x, y)| world.transform_vector3(*x - y).length()).fold(0.0f32, f32::max)+ corners(&cpu(&live, g, &bend(0.25))).iter().zip(corners(&cpu(&live, g, &bend(0.9)))).map(|(x, y)| world.transform_vector3(*x - y).length()).fold(0.0f32, f32::max)}).fold(0.0f32, f32::max);let vectors: Vec<f32> = moved.chunks_exact(4).filter(|p| p[3] > 0.5).map(|p| Vec3::new(p[0], p[1], p[2]).length()).collect();let longest = vectors.iter().copied().fold(0.0f32, f32::max);diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex dbd343c..caefb2a 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -14,10 +14,12 @@ pub(super) struct LoadedScene {pub(super) tri_instances: Vec<(u32, u32, u32)>,/// (A mesh the GPU skins has its build's pose here: `LiveCore::mesh_tris` has it as it is now.)pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,- /// Software traversal with units: what the skinning pass skins each model from (`scene::Scene::skin_sources`) and- /// the shape of its meshes' trees (`skin_trees`), kept on the CPU: a new pose takes a tree's boxes again from- /// them (live/edits.rs `repose_skinned`). Empty under hardware traversal, whose BLASes the GPU builds.- pub(super) skin_sources: Vec<Vec<[crate::skin::SkinCorner; 3]>>,+ /// The vertices that move, the first and how many (`indexed::Indexed::dynamic`); by skin source, the model's+ /// vertices its meshes are skinned from and their triangles' indices (`Indexed::skins`).+ pub(super) dynamic_verts: (u32, u32),+ pub(super) skins: Vec<(Vec<crate::skin::SkinCorner>, Vec<[u32; 3]>)>,+ /// Software traversal with units: the shape of each skin source's meshes' trees (`scene::Scene::skin_trees`): a+ /// new pose takes a tree's boxes again from its vertices as posed (live/edits.rs `repose_skinned`).pub(super) skin_trees: Vec<Vec<crate::bvh::GpuNode>>,/// Software traversal: each pool triangle's section and its index in it (a unit's tree orders its mesh's/// triangles; live/edits.rs `mesh_places`). Empty under hardware traversal, where they lie by section.@@ -49,8 +51,9 @@ pub(super) struct LoadedScene {pub(super) base: gpu::Params,/// GPU table copies that parameter edits rewrite in place (`commit`).pub(super) tables: tables::Tables,- /// CPU copy of the dynamic triangles (posed models: the tail of the GPU triangle order from `dynamic_first`):- /// vertices (kernel layout), shading attributes, BLAS vertices.+ /// CPU copy of the dynamic triangles (posed models: the tail of the GPU triangle order, from its first): rows+ /// (v0, e1, e2), shading attributes, corners (a triangle that is not finite: at the origin). Their vertices on+ /// the GPU are made from these (`upload_dynamic`).pub(super) dynamic: (usize, Vec<[f32; 4]>, Vec<scene::GpuTriAttr>, Vec<[f32; 3]>),/// Kernel feature inputs edits cannot change: textures, material functions, traversal groups.pub(super) fixed_features: (bool, bool, [usize; crate::GROUPS]),@@ -239,7 +242,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);// (The light tree is the tables' by now: its nodes from there.)- let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;+ let up = g.upload(&sc, &targets.accum, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frameif !g.merged {let _ = g.kernel_pass(&up.kernel, "finish");@@ -267,7 +270,10 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet instance_features = gpu::instance_features(&sc);let pool_place: Vec<[u32; 2]> = if up.units.is_some() { sc.pool_attrs.iter().map(|a| [a.uv[3].to_bits(), a.x[3].to_bits()]).collect() } else { vec![] };let (pool_tris, meshes, instances) = (std::mem::take(&mut sc.pool_tris), std::mem::take(&mut sc.meshes), std::mem::take(&mut sc.instances));- let (skin_sources, skin_trees) = if up.units.is_some() { (std::mem::take(&mut sc.skin_sources), std::mem::take(&mut sc.skin_trees)) } else { (vec![], vec![]) };+ let skin_trees = if up.units.is_some() { std::mem::take(&mut sc.skin_trees) } else { vec![] };+ // (The vertices and the indices themselves are the GPU's now.)+ let ix = std::mem::take(&mut sc.indexed);+ let (vertices, dynamic_verts, skins) = (ix.vertices.len(), ix.dynamic, ix.skins);let (sections, rows) = (std::mem::take(&mut sc.sections), std::mem::take(&mut sc.rows));let mut gpu_instances = std::mem::take(&mut sc.gpu_instances);let proc_first = gpu_instances.len();@@ -311,13 +317,12 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Prow_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)- },+ // (The previous positions at the build: the vertices that move. No room: it grows with the first deforming+ // mesh an edit places.)+ prev: Holes::new(dynamic_verts.1 as usize, dynamic_verts.1 as usize),+ // (Three vertices a triangle of the room: `Gpu::upload`.)+ verts: Holes::new(vertices, vertices + room.tris * 3),free_skinned: vec![],};- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, skin_sources, skin_trees, 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))+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, 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.rsindex 88ce81c..5cb5b2e 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -656,7 +656,7 @@ impl LiveCore {});}let Some(a) = up.accel.as_ref() else { return serde_json::Value::Null };- let buffers = [&up.verts, &up.attrs, &up.prev_verts, &up.heap.buffer, &up.words.buffer, &a.verts].iter().map(|b| b.size()).sum::<u64>();+ let buffers = [&up.vertices, &up.prev_vertices, &up.heap.buffer, &up.words.buffer].iter().map(|b| b.size()).sum::<u64>();let live: u64 = self.sc.meshes.iter().enumerate().filter(|(k, _)| e.users.get(&(*k as u32)).copied().unwrap_or(0) > 0).map(|(_, m)| m.count as u64).sum::<u64>() + e.pool_first as u64;let mb = |b: f64| (b / (1 << 20) as f64 * 10.0).round() / 10.0;serde_json::json!({@@ -1384,7 +1384,7 @@ mod instanced_tests {let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();(sc.width, sc.height) = (64, 36);let prep = crate::prepare(g, &mut sc, &mut vec![]);- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();+ let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()};let (a, b) = (offline(&views), offline(&whole));@@ -1433,7 +1433,7 @@ mod instanced_tests {let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();(sc.width, sc.height) = (64, 36);let prep = crate::prepare(g, &mut sc, &mut vec![]);- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();+ let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()};let (a, b) = (offline(&plain), offline(&uniform));diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rsindex 3e8f5ea..5e00d58 100644--- a/renderer/src/ltree.rs+++ b/renderer/src/ltree.rs@@ -433,7 +433,7 @@ mod tests {use super::*;fn tri(i: u32, x: f32) -> (EmitterTri, [[f32; 4]; 3]) {- (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: crate::NO_INST }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])+ (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0 }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])}/// Garbage in: emitters whose triangles are not finite, that coincide, or carry weights near f32's limit make adiff --git a/renderer/src/main.rs b/renderer/src/main.rsindex d8d125c..e1c0744 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -497,7 +497,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hosif job.signals.is_some() {params.motion[1] = 1.0;}- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;+ let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;if let Some(prefix) = &job.signals {// The raw (undenoised) means: diffuse = color less specular and emission.let diffuse: Vec<f32> = frame.color.iter().zip(&frame.specular).zip(&frame.emission).flat_map(|((c, s), e)| [0, 1, 2].map(|k| (c[k] - s[k] - e[k]).max(0.0))).collect();diff --git a/renderer/src/merged.rs b/renderer/src/merged.rsindex f4fac6e..e2a8e36 100644--- a/renderer/src/merged.rs+++ b/renderer/src/merged.rs@@ -1,5 +1,5 @@//! The merged binding layout: the kernel with at most eight storage buffers a stage, WebGPU's default limit-//! (`maxStorageBuffersPerShaderStage`). The kernel binds 21 as it is written: more than a browser gives a page.+//! (`maxStorageBuffersPerShaderStage`). The kernel binds 20 as it is written: more than a browser gives a page.//! (The live passes need none of this: each binds at most eight, live/layout.rs, and a page binds them as they are.)//!//! The kernel's source has both layouts: pathtrace.wgsl declares its tables' views and its group-1 buffers in an@@ -110,7 +110,7 @@ mod tests {/// Kernel variants in the merged layout: valid WGSL, no entry point with more than eight storage buffers, none/// declared beyond them (a pipeline layout counts what is declared), no length of a view's buffer in the source,/// and `MergedLive`'s members where the renderer puts their sections.- /// The layout as written has 22 (21 under hardware traversal, which has no trees' buffer). Because the merged+ /// The layout as written has 22 (20 under hardware traversal, which has neither of the trees' buffers). Because the merged/// blocks declare none of the views or of group 1's buffers by their own names, a read or write of one past its/// accessor does not compile here (and naga says where), whatever the other layouts take.#[test]@@ -121,7 +121,7 @@ mod tests {// (`main` no longer adds to the cache's sums: `finish` trains it.)assert_eq!(used.iter().map(|u| u.1).max(), Some(21), "{used:?}");let hw = kernel_wgsl(&kernel_template(), &KernelVariant::new(true, Default::default(), 0));- assert_eq!(hw.matches("var<storage").count(), 21 + 4, "hardware traversal: no trees' buffer (and the translucency pass's four)");+ assert_eq!(hw.matches("var<storage").count(), 20 + 4, "hardware traversal: neither of the trees' buffers (and the translucency pass's four)");for features in [0, crate::gpu::F_VCOLOR, crate::gpu::F_GRID, crate::gpu::F_TINT | crate::gpu::F_UNLIT | crate::gpu::F_BACKGROUND, crate::gpu::F_SOURCE] {let src = variant(features, true);assert!(!src.contains("arrayLength"), "the lengths are the parameters'");@@ -129,7 +129,8 @@ mod tests {let (used, declared) = storage_buffers(&m, &info);assert!(declared as u32 <= STORAGE_BUFFERS, "features {features:#x}: {declared} declared");assert!(used.iter().all(|u| u.1 as u32 <= STORAGE_BUFFERS), "features {features:#x}: {used:?}");- assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(8), "the trace reads all eight");+ assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(8), "the trace reads all eight a page has (the trees' leaves the eighth)");+ assert_eq!(declared, 8, "features {features:#x}");// The struct's members are the first sections; its last, the vec4s, begins where the cache's values do.let (at, _) = crate::heap::Heap::<crate::heap::Live>::starts_for(&crate::gpu::live_sizes(1, 64, 64, 64, 64));assert_eq!(layout(&m, "MergedLive").0, at[..4]);@@ -245,8 +246,8 @@ mod tests {assert_eq!(g.matches("if (loop_guard()) {").count(), loops(&plain) - counted(&plain));let (m, info) = parse(&g);let (used, declared) = storage_buffers(&m, &info);- // (As written: the guard's count and `finish`'s records too. Merged: still eight.)- assert_eq!(declared as u32, if merged { STORAGE_BUFFERS } else { 23 }, "{used:?}");+ // (As written: the guard's count and `finish`'s records too. Merged: the eight a page has.)+ assert_eq!(declared as u32, if merged { 8 } else { 23 }, "{used:?}");}// The pass on its own: nested loops, a `continuing` block, comments and braces in them, a loop in an `if`; a// counted loop left alone, one bounded by a variable or assigning its counter guarded.diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex c938a8e..a8c8ba6 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -71,6 +71,10 @@ pub struct InstMesh {pub sect_count: u32,/// Its triangles carry its geometry's vertex colours (a material says whether it reads them).pub colored: bool,+ /// Its vertices (indexed.rs): the first and how many the run holds. Its triangles' indices count from the first;+ /// `prepare` sets them, or the edit that places the mesh.+ pub vfirst: u32,+ pub vcount: u32,}/// A run of a mesh's triangles that an object draws with one of its materials: a geometry group, or the whole of a@@ -84,6 +88,10 @@ pub struct Section {pub slot: u32,}+/// The most sections a mesh may have: a hit's section is 16 bits of the record a pixel is left to the kernel's second+/// pass by (pathtrace.wgsl `finish`).+pub const MESH_SECTIONS: usize = 1 << 16;+/// An instance's row for a section of its mesh, as the kernel reads it (the words' heap, heap.rs `Stream::Rows`):/// the material with the class bits `ROW_*`, the section's first triangle in the triangles' table, its first emitter in/// the light list (`NO_EMITTER`: it does not emit), and a word to spare.@@ -124,12 +132,12 @@ pub fn rows_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMateriasections.iter().zip(rows).filter(|(_, r)| materials.get(row_material(r) as usize).is_some_and(emissive)).map(|(s, _)| s.count).sum()}-/// A triangle's place among its instance's emitters and its material, from its attributes (its section and its-/// index in it), the instance's rows and where each section's emitters start (`section_emitters`). None: its-/// section's material does not emit.-pub fn section_slot(a: &GpuTriAttr, rows: &[Row], starts: &[Option<u32>]) -> Option<(usize, u32)> {+/// A triangle's place among its instance's emitters, its material and its section, from its attributes (its+/// section and its index in it), the instance's rows and where each section's emitters start (`section_emitters`).+/// None: its section's material does not emit.+pub fn section_slot(a: &GpuTriAttr, rows: &[Row], starts: &[Option<u32>]) -> Option<(usize, u32, u32)> {let s = a.uv[3].to_bits() as usize;- Some(((starts.get(s).copied()?? + a.x[3].to_bits()) as usize, row_material(rows.get(s)?)))+ Some(((starts.get(s).copied()?? + a.x[3].to_bits()) as usize, row_material(rows.get(s)?), s as u32))}/// Where each section's emitters start among its instance's (None: its material does not emit).@@ -203,13 +211,15 @@ 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+ /// An instance of a mesh that deforms: where its vertices' positions of the previous frame begin (the kernel's/// `prev_verts`: its motion is its pose's and its transform's). 0 otherwise.pub prev: u32,+ /// Its mesh's first vertex (`indexed::Indexed::meshes`): its triangles' indices count from it.+ pub verts: u32,}/// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose),-/// (first triangle in the GPU order, object index, a spare word, its rows' first), and the+/// (first triangle in the GPU order, object index, its mesh's first vertex, its rows' first), and the/// world matrix rows of the previous frame (a movable instance's motion vectors; the same rows when it did not move).#[repr(C)]#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]@@ -229,7 +239,7 @@ impl Instance {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, f32::from_bits(self.prev))], info: [first, self.object, 0, 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, self.verts, 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).@@ -273,8 +283,10 @@ pub const INST_MIRRORED: u32 = 4;/// triangle's row).pub const INST_CUTOUT: u32 = 16;pub const INST_GLASS: u32 = 32;+/// Its mesh deforms (a posed skinned model's): its motion is its vertices' too (`Instance::prev`).+pub const INST_DEFORMS: u32 = 64;/// Every bit of n1.w that is the instance's own, not a unit's.-pub const INST_BITS: u32 = INST_MIRRORED | INST_CUTOUT | INST_GLASS;+pub const INST_BITS: u32 = INST_MIRRORED | INST_CUTOUT | INST_GLASS | INST_DEFORMS;/// Whether a placement mirrors what it places (a negative determinant).pub fn mirrors(w: Mat4) -> bool {@@ -519,7 +531,7 @@ pub struct GpuTriAttr {pub n2: [f32; 4], // normal2, w = uv1.xpub uv: [f32; 4], // uv1.y, uv2.x, uv2.y, material (bits)pub t: [f32; 4], // tangent (dP/du), w = bitangent sign- pub x: [f32; 4], // a spare word, object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)+ pub x: [f32; 4], // `indexed::OWN_TANGENT` (bits), object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)}#[repr(C)]@@ -677,6 +689,8 @@ pub struct Scene {/// source, whose boxes are taken again at each pose (`units::refit`). The source's triangles are in its order.pub skin_rest: Vec<Vec<skin::PaletteRows>>,pub skin_trees: Vec<Vec<crate::bvh::GpuNode>>,+ /// The triangles as shared vertices and indices (indexed.rs), in the GPU's order: `prepare` makes them.+ pub indexed: crate::indexed::Indexed,/// The meshes' sections (`InstMesh::sect_first`) and the instances' rows (`Instance::rows`): as the kernel reads/// the rows once `prepare` has set where each section's triangles and emitters are.pub sections: Vec<Section>,@@ -1597,7 +1611,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seretained.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(§ions), 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), prev: 0 });+ 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, verts: 0 });rows.extend(mine);}}@@ -1655,7 +1669,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sefor (i, &(wm, hidden)) in placed.iter().enumerate() {let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);objects.extend_from_slice(©_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), prev: 0 });+ 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, verts: 0 });rows.extend(mine.iter().copied());}}@@ -1830,7 +1844,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), prev: 0 });+ 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, verts: 0 });rows.extend(mine);}for (p, nn, uv, tg, mat) in &part.rest {@@ -1910,7 +1924,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet 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), prev: 0 });+ 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, verts: 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 }) };@@ -1985,7 +1999,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seobjects.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), prev: 0 };+ 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, verts: 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 {@@ -2283,6 +2297,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seskin_sources,skin_rest,skin_trees: vec![],+ indexed: Default::default(),sections,rows,gpu_instances: vec![],@@ -2636,7 +2651,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32) -> InstMesh {}}let count = tris.len() as u32;- InstMesh { first, count, rest_first: 0, rest_count: 0, lo, hi, deforms: false, sect_first: 0, sect_count: 0, colored: false }+ InstMesh { first, count, rest_first: 0, rest_count: 0, lo, hi, deforms: false, sect_first: 0, sect_count: 0, colored: false, vfirst: 0, vcount: 0 }}/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its@@ -2707,6 +2722,8 @@ fn push_tri(/// Shading attributes of a triangle (normals, UVs, tangent frame, texel density, material).pub fn tri_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3, f32)>, mat: u32) -> GpuTriAttr {+ // (Whether the tangent is the first corner's own: `indexed::OWN_TANGENT`.)+ let own = if tangent.is_some() { crate::indexed::OWN_TANGENT } else { 0 };// Per-triangle tangent frame from UVs (glTF convention: v grows downward in the image).let (t, sign) = tangent.unwrap_or_else(|| {let (e1, e2) = (p[1] - p[0], p[2] - p[0]);@@ -2730,7 +2747,7 @@ pub fn tri_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3n2: [n[2].x, n[2].y, n[2].z, uv[1].x],uv: [uv[1].y, uv[2].x, uv[2].y, f32::from_bits(mat)],t: [t.x, t.y, t.z, sign],- x: [0.0, 0.0, 0.0, 0.0],+ x: [f32::from_bits(own), 0.0, 0.0, 0.0],}}@@ -2819,7 +2836,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, prev: 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, verts: 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.@@ -2851,7 +2868,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, prev: 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, verts: 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);@@ -2996,7 +3013,7 @@ mod instance_tests {assert_eq!((rows_cast(&rows, true), rows_cast(&rows, false), rows_bits(&rows)), (true, false, INST_CUTOUT | INST_GLASS));let starts = section_emitters(&d.sections, &rows, &materials);assert_eq!((rows_emitters(&d.sections, &rows, &materials), &starts[..]), (2, &[None, None, Some(0), None, None][..]));- assert_eq!((section_slot(&d.attrs[4], &rows, &starts), section_slot(&d.attrs[5], &rows, &starts)), (Some((1, 2)), None), "an emitter's place: its section's start and its index");+ assert_eq!((section_slot(&d.attrs[4], &rows, &starts), section_slot(&d.attrs[5], &rows, &starts)), (Some((1, 2, 2)), None), "an emitter's place (its section's start and its index), its material and its section");// Two materials for four slots: a slot past the last is the last. Emitters in two sections, one after another.let two = section_rows(&d.sections, &[2, 0], &materials);assert_eq!(two.iter().map(row_material).collect::<Vec<_>>(), [2, 0, 0, 0, 0]);diff --git a/renderer/src/units.rs b/renderer/src/units.rsindex 7d8ab24..e76e253 100644--- a/renderer/src/units.rs+++ b/renderer/src/units.rs@@ -904,11 +904,11 @@ pub(crate) mod cpu {/// their buffer; every loop iteration counted against `budget` (the loop guard's role: the walk must end).pub(crate) struct Kernel<'a> {pub(crate) nodes: &'a [GpuNode],- pub(crate) tri_verts: &'a [[f32; 4]],+ /// The trees' leaf triangles (`indexed::Leaf`), as the kernel has them.+ pub(crate) leaves: &'a [crate::indexed::Leaf],pub(crate) instances: &'a [GpuInstance],- /// Each triangle's section (its attributes' uv.w) and the instances' rows: what a unit with rows has its- /// glass by (`row_flags`). Empty where no unit has rows.- pub(crate) sections: &'a [u32],+ /// The instances' rows: what a unit with rows has its glass by, through its triangles' sections+ /// (`row_flags`). Empty where no unit has rows.pub(crate) rows: &'a [crate::scene::Row],/// `P.motion.z`, `P.motion.w`.pub(crate) top: u32,@@ -953,9 +953,14 @@ pub(crate) mod cpu {self.count(|r| *(if !r.in_units { &mut r.still_nodes } else if i >= self.top { &mut r.top_nodes } else { &mut r.mesh_nodes }) += 1);self.nodes.get(i as usize).copied().ok_or(format!("reads node {i} of {}", self.nodes.len()))}- pub(crate) fn vert(&self, i: u32) -> Walk<Vec3A> {- self.count(|r| *(if r.in_units { &mut r.mesh_verts } else { &mut r.still_verts }) += 1);- self.tri_verts.get(i as usize).map(|v| Vec3A::new(v[0], v[1], v[2])).ok_or(format!("reads vertex {i} of {}", self.tri_verts.len()))+ /// A leaf's triangle: v0, e1, e2. (Counted as a triangle's three vertices.)+ pub(crate) fn leaf(&self, i: u32) -> Walk<[Vec3A; 3]> {+ self.count(|r| *(if r.in_units { &mut r.mesh_verts } else { &mut r.still_verts }) += 3);+ self.leaves.get(i as usize).map(|l| l.map(|v| Vec3A::new(v[0], v[1], v[2]))).ok_or(format!("reads leaf triangle {i} of {}", self.leaves.len()))+ }+ /// pathtrace.wgsl `leaf_id`.+ pub(crate) fn leaf_id(&self, ti: u32, k: usize) -> Walk<u32> {+ Ok(self.leaves.get(ti as usize).ok_or(format!("reads leaf triangle {ti} of {}", self.leaves.len()))?[k][3].to_bits())}pub(crate) fn record(&self, i: u32) -> Walk<GpuInstance> {self.count(|r| r.records += 1);@@ -986,7 +991,7 @@ pub(crate) mod cpu {/// pathtrace.wgsl `intersect_tri`: (t, u, v), t = INF for a miss.pub(crate) fn intersect_tri(&self, o: Vec3A, d: Vec3A, i: u32, tmax: f32) -> Walk<f32> {- let (v0, e1, e2) = (self.vert(i * 3)?, self.vert(i * 3 + 1)?, self.vert(i * 3 + 2)?);+ let [v0, e1, e2] = self.leaf(i)?;let pv = d.cross(e2);let det = e1.dot(pv);if det.abs() < 1e-12 {@@ -1038,12 +1043,12 @@ pub(crate) mod cpu {for k in 0..n.count {self.step()?;let ti = n.left_or_first + k;- let flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();- if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {- continue;- }let t = self.intersect_tri(o, d, ti, hit.t)?;if t < hit.t {+ let flags = self.leaf_id(ti, 0)?;+ if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {+ continue;+ }hit = Hit { t, tri: ti, inst: NO_INST };if mode != TRACE_CLOSEST {return Ok(hit);@@ -1086,8 +1091,7 @@ pub(crate) mod cpu {}/// shaders/trace_units.wgsl `row_flags`.- fn row_flags(&self, first: u32, ti: u32) -> Walk<u32> {- let section = *self.sections.get(ti as usize).ok_or(format!("reads the section of triangle {ti}"))?;+ fn row_flags(&self, first: u32, section: u32) -> Walk<u32> {let x = self.rows.get((first + section) as usize).ok_or(format!("reads row {first} + {section}"))?[0];Ok(if x & crate::scene::ROW_CUTOUT != 0 { crate::scene::TRI_MASKED } else { 0 } | if x & crate::scene::ROW_GLASS != 0 { crate::scene::TRI_NO_SHADOW } else { 0 })}@@ -1155,9 +1159,10 @@ pub(crate) mod cpu {let x = self.intersect_tri(ro, rd, ti, hit.t)?;if x < hit.t {// (A unit's glass: shadow rays pass it.)- let mut flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();+ let part = self.leaf_id(ti, 0)?;+ let mut flags = 0;if ubits & (crate::scene::INST_CUTOUT | crate::scene::INST_GLASS) != 0 {- flags |= self.row_flags(urows, ti)?;+ flags = self.row_flags(urows, part)?;}if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {continue;@@ -1188,7 +1193,7 @@ pub(crate) mod cpu {}#[cfg(test)]-mod tests {+pub(crate) mod tests {use super::cpu::*;use super::*;use glam::{Quat, Vec3};@@ -1254,7 +1259,10 @@ mod tests {"let ti = first + n.left_or_first + k;","let x = intersect_tri(ro, rd, ti, hit.t);","if (x.x < hit.t) {",- "hit = Hit(x.x, ti, x.y, x.z, rec);",+ "let part = leaf_id(ti, 0u);",+ "var flags = 0u;",+ "if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags = row_flags(urows, part); }",+ "hit = Hit(x.x, ti, x.y, x.z, rec, part);","if (mode != TRACE_CLOSEST) { return hit; }","if (rec != NO_INST && sp == base) {","rec = NO_INST;",@@ -1273,12 +1281,14 @@ mod tests {kernel,"pathtrace.wgsl",&[+ "fn leaf_id(ti: u32, k: u32) -> u32 { return bitcast<u32>(leaves[ti * 3u + k].w); }","fn proc_dir(r: Instance, d: vec3<f32>) -> vec3<f32> { return r.n0.xyz * d.x + r.n1.xyz * d.y + r.n2.xyz * d.z; }","fn proc_point(r: Instance, p: vec3<f32>) -> vec3<f32> { return proc_dir(r, p - vec3<f32>(r.m0.w, r.m1.w, r.m2.w)); }","fn intersect_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> vec3<f32> {",- "let v0 = tri_verts[i * 3u].xyz;",- "let e1 = tri_verts[i * 3u + 1u].xyz;",- "let e2 = tri_verts[i * 3u + 2u].xyz;",+ "let k = i * 3u;",+ "let v0 = leaves[k].xyz;",+ "let e1 = leaves[k + 1u].xyz;",+ "let e2 = leaves[k + 2u].xyz;","let pv = cross(d, e2);","let det = dot(e1, pv);","if (abs(det) < 1e-12) { return vec3<f32>(INF, 0.0, 0.0); }",@@ -1291,9 +1301,10 @@ mod tests {"if (t <= 0.0 || t >= tmax) { return vec3<f32>(INF, 0.0, 0.0); }","fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {","var stack: array<u32, 48>;",- "if (mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }","let r = intersect_tri(o, d, ti, hit.t);",- "hit = Hit(r.x, ti, r.y, r.z, NO_INST);",+ "let flags = leaf_id(ti, 0u);",+ "if (mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }",+ "hit = Hit(r.x, ti, r.y, r.z, NO_INST, ti);","if (mode != TRACE_CLOSEST) { return hit; }","if (tr != INF && sp < 48u) {","if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }",@@ -1332,7 +1343,7 @@ mod tests {/// into room, a record, the top tree again.struct Scene {nodes: Vec<GpuNode>,- tri_verts: Vec<[f32; 4]>,+ soup: Soup,instances: Vec<GpuInstance>,layout: Layout,still_tris: usize,@@ -1346,27 +1357,35 @@ mod tests {kept: Kept,}- fn put_tris(out: &mut Vec<[f32; 4]>, tris: &[[Vec3A; 3]]) {- for [a, b, c] in tris {- let (e1, e2) = (*b - *a, *c - *a);- out.extend([[a.x, a.y, a.z, 0.0], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);+ /// Triangles as the trees' leaves have them (`indexed::Leaf`), without flags or sections.+ #[derive(Default)]+ pub(crate) struct Soup {+ pub(crate) leaves: Vec<crate::indexed::Leaf>,+ }++ impl Soup {+ /// The triangles after those there are; the first's index.+ pub(crate) fn push(&mut self, tris: &[[Vec3A; 3]]) -> u32 {+ let first = self.leaves.len() as u32;+ self.leaves.extend(tris.iter().map(|t| crate::indexed::leaf(*t, [0, 0])));+ first}}impl Scene {fn new(still: &[[Vec3A; 3]], mesh_room: usize, units: usize) -> Scene {let b = bvh::build(still);- let mut tri_verts = vec![];- put_tris(&mut tri_verts, &b.order.iter().map(|&i| still[i as usize]).collect::<Vec<_>>());+ let mut soup = Soup::default();+ soup.push(&b.order.iter().map(|&i| still[i as usize]).collect::<Vec<_>>());// (An empty still scene: the tree over nothing is a leaf of triangle 0, here three zero triangles; the meshes'// triangles follow whole triangles.)if still.is_empty() {- tri_verts.resize(9, [0.0; 4]);+ soup.push(&[[Vec3A::ZERO; 3]; 3]);}let layout = Layout::new(b.nodes.len(), mesh_room, units);let mut nodes = b.nodes;nodes.resize(nodes.len() + layout.nodes(), FILL);- Scene { nodes, tri_verts, instances: vec![GpuInstance::default()], top: layout.top_first, layout, still_tris: still.len(), meshes: vec![], units: vec![], count: 0, kept: Kept::default() }+ Scene { nodes, soup, instances: vec![GpuInstance::default()], top: layout.top_first, layout, still_tris: still.len(), meshes: vec![], units: vec![], count: 0, kept: Kept::default() }}/// A new mesh: its tree placed and written, its triangles appended in the tree's order.@@ -1374,8 +1393,7 @@ mod tests {let t = mesh_tree(tris)?;let root = self.layout.place(t.nodes.len()).ok_or("no room for the tree")?;self.nodes[root as usize..root as usize + t.nodes.len()].copy_from_slice(&t.nodes);- let first = (self.tri_verts.len() / 3) as u32;- put_tris(&mut self.tri_verts, &t.order.iter().map(|&i| tris[i as usize]).collect::<Vec<_>>());+ let first = self.soup.push(&t.order.iter().map(|&i| tris[i as usize]).collect::<Vec<_>>());let (lo, hi) = tri_boxes(tris).into_iter().fold((Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY)), |a, b| (a.0.min(b.0), a.1.max(b.1)));self.meshes.push(Some((first, tris.len() as u32, root, t.nodes.len(), lo, hi)));Ok(self.meshes.len() - 1)@@ -1390,7 +1408,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, prev: 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, verts: 0 };unit_record(inst.gpu(first), root, cast)}@@ -1427,8 +1445,8 @@ mod tests {}fn kernel(&self) -> Kernel<'_> {- let budget = 64 * (self.nodes.len() as u64 + self.tri_verts.len() as u64) + 1024;- Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, sections: &[], rows: &[], top: self.top, units: self.count, steps: Default::default(), budget, deepest: Default::default(), reads: Default::default() }+ let budget = 64 * (self.nodes.len() as u64 + self.soup.leaves.len() as u64 * 3) + 1024;+ Kernel { nodes: &self.nodes, leaves: &self.soup.leaves, instances: &self.instances, rows: &[], top: self.top, units: self.count, steps: Default::default(), budget, deepest: Default::default(), reads: Default::default() }}/// Every triangle a ray could meet, tested one by one with the kernel's own triangle test (the still scene's in@@ -2060,7 +2078,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, prev: 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, verts: 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.rsindex 3598bf1..f05021f 100644--- a/renderer/src/units_cost.rs+++ b/renderer/src/units_cost.rs@@ -17,7 +17,7 @@ use std::time::Instant;/// A scene as the kernel is given it.struct Laid {nodes: Vec<bvh::GpuNode>,- tri_verts: Vec<[f32; 4]>,+ soup: units::tests::Soup,instances: Vec<scene::GpuInstance>,top: u32,units: u32,@@ -49,10 +49,12 @@ fn lay(world: &crate::world::World, assets: &std::path::Path, with_units: bool)let s = t.elapsed().as_secs_f64();let (top, count) = (p.params.motion[2].to_bits(), p.params.motion[3].to_bits());let stored = p.tri_verts.len() / 3;+ // (The triangles as the kernel has them: `prepare`'s vertices, indices and rows.)+ let soup = units::tests::Soup { leaves: sc.indexed.leaves.clone() };let what = format!("{} triangles stored ({:.1} MiB of vertices + attributes), {} nodes ({:.1} MiB), {} units; flattened {} triangles; prepare {s:.2} s", stored, (stored * 144) as f64 / 1048576.0, p.nodes.len(), (p.nodes.len() * 32) as f64 / 1048576.0, sc.units.as_ref().map_or(0, |u| u.count), flat + placed);let instances = if sc.gpu_instances.is_empty() { vec![scene::GpuInstance::default()] } else { sc.gpu_instances.clone() };let unit_tris = sc.units.as_ref().map_or(vec![], |u| sc.instances.iter().enumerate().filter(|(r, i)| !i.hidden && u.slots.get(*r).is_some_and(|s| s.is_some())).map(|(r, i)| (r as u32, sc.gpu_instances[r].info[0], sc.meshes[i.mesh as usize].count)).collect());- (Laid { nodes: p.nodes, tri_verts: p.tri_verts, instances, top, units: if sc.units.is_some() { count } else { 0 }, what, still: sc.tris.len() as u32, unit_tris }, sc)+ (Laid { nodes: p.nodes, soup, instances, top, units: if sc.units.is_some() { count } else { 0 }, what, still: sc.tris.len() as u32, unit_tris }, sc)}impl Laid {@@ -75,7 +77,7 @@ impl Laid {}fn kernel(&self) -> Kernel<'_> {- Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, sections: &[], rows: &[], top: self.top, units: self.units, steps: Default::default(), budget: 1 << 26, deepest: Default::default(), reads: Default::default() }+ Kernel { nodes: &self.nodes, leaves: &self.soup.leaves, instances: &self.instances, rows: &[], top: self.top, units: self.units, steps: Default::default(), budget: 1 << 26, deepest: Default::default(), reads: Default::default() }}}@@ -101,8 +103,8 @@ fn rays(l: &Laid, cam: &scene::CameraData, w: usize, h: usize) -> Vec<Ray> {out.push(Ray { o: o.into(), tmax, d: d.into(), mode, t, kind });(t < INF).then(|| {// The hit's point, a little off the triangle on the ray's side.- let v = |k: u32| { let v = l.tri_verts[(hit.tri * 3 + k) as usize]; Vec3A::new(v[0], v[1], v[2]) };- let n = v(1).cross(v(2)).normalize_or_zero();+ let e = |k: usize| { let v = l.soup.leaves[hit.tri as usize][k]; Vec3A::new(v[0], v[1], v[2]) };+ let n = e(1).cross(e(2)).normalize_or_zero();// (A unit's triangle is in the unit's space: its normal by the record's normal rows.)let n = if hit.inst == NO_INST { n } else { let r = &l.instances[hit.inst as usize]; Vec3A::new(Vec3A::from_slice(&r.n[0]).dot(n), Vec3A::from_slice(&r.n[1]).dot(n), Vec3A::from_slice(&r.n[2]).dot(n)).normalize_or_zero() };let n = if n.dot(d) > 0.0 { -n } else { n };@@ -342,11 +344,8 @@ fn units_pile() {// The piece's mesh: its triangles after the scene's, its tree in the mesh range.let tris = lump();let tree = units::mesh_tree(&tris).unwrap();- let first_tri = (l.tri_verts.len() / 3) as u32;- for &i in &tree.order {- let [a, b, c] = tris[i as usize];- l.tri_verts.extend([[a.x, a.y, a.z, 0.0], [(b - a).x, (b - a).y, (b - a).z, 0.0], [(c - a).x, (c - a).y, (c - a).z, 0.0]]);- }+ // (Its vertices three a triangle and counted from 0: the records placing it have no first vertex.)+ let first_tri = l.soup.push(&tree.order.iter().map(|&i| tris[i as usize]).collect::<Vec<_>>());let mesh = u.trees.len() as u32;let root = u.add_tree(mesh, &tree).expect("room for one small tree") as usize;l.nodes[root..root + tree.nodes.len()].copy_from_slice(&tree.nodes);@@ -409,7 +408,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, prev: 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, verts: 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/tests/render/data/tangent-quads.glb b/tests/render/data/tangent-quads.glbnew file mode 100644index 0000000..7abf60bBinary files /dev/null and b/tests/render/data/tangent-quads.glb differdiff --git a/tests/render/material-function-file-tangent.ts b/tests/render/material-function-file-tangent.tsnew file mode 100644index 0000000..cac47d3--- /dev/null+++ b/tests/render/material-function-file-tangent.ts@@ -0,0 +1,27 @@+// A tangent a file gives is the one a material's function sees. tests/render/data/tangent-quads.glb: two quads of one+// material, their UVs' u along +x; the right one has TANGENT +y at every vertex, the left one none (its frame is+// made from its UVs: +x). The function emits 5 nits where the tangent it is given points along y and 2 where it+// does not.+import { MaterialFunction, GLTFModel } from "@threert/scene";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";++const URI = "tests/render/data/tangent-quads.glb";++export const test: TestMeta = {+ id: "material/function-file-tangent", features: ["material-function", "gltf", "instancing"], reference: "analytic", temporal: false,+ metric: { kind: "ratio", a: [0.6, 0.4, 0.75, 0.6], b: [0.25, 0.4, 0.4, 0.6], expected: 2.5, tolerance: 0.02 },+ requires: [URI],+ note: "right quad (the file's tangent, +y) over left quad (no tangent in the file: +x from its UVs): 5 / 2",+};++const ALONG_Y = new MaterialFunction("tangent_along_y", {+ params: {},+ code: `+ o.base = vec3<f32>(0.0);+ o.emissive = vec3<f32>(select(2.0, 5.0, abs(i.t.y) > 0.7));`,+});++export default () => {+ const scene = sceneWithSky(0);+ return result(scene, camera(scene, [0, 0, 8], [0, 0, 0]), [new GLTFModel(URI, { functions: { side: ALONG_Y.with({}) } })]);+};