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
Nothing reads a world-space triangle: the groups, the still tree and the per-triangle rows go (#278)
Yujiab6cd61392de1
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex b862ba6..8b04511 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2920,6 +2920,20 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too lowFound by review: a translucent particle's material given another function kept the kernel's old dispatch for thetranslucency pass, which has its particles' functions alone; the kernel is made again where those are others.+**Nothing reads a world-space triangle (2026-11-25, after it).** Nothing made one any more; what read them is+deleted. Hardware traversal: the traversal groups and their BLASes, with the feature for a group past 2^24+triangles and the bit that told a model's TLAS instance from a group's (an instance's custom data is its record).+Software traversal: the tree over the scene's own triangles and its walk (the kernel's `trace` is the units' walk,+then the procedural objects'; the node buffer starts with the mesh trees). The kernel: a row a triangle, and what+a hit without an instance read (the test of a hit's instance stays where its record is read: every hit passes it,+and without it a frame is 1 to 3 % longer in some scenes, a crowd under the sky 6.36 -> 6.57 ms). The CPU:+`Scene::tris` and what went with it, posed models as triangles the CPU moved, their emitters, picking over them.+A deletion: the pictures are the same, with one exception that is not this step's doing. A TLAS's empty slots are+instances without extent at the world's origin (the patched wgpu's, since 2026-11-23), and on Metal a ray that+starts there loses its hit, as do a few that pass it: the groups' eight slots were empty in every scene, and with+them gone a scene whose TLAS has no empty slot renders such rays right (eleven render tests under hardware+traversal, failing since then, pass). A TLAS with an empty slot (an edit room, an instance removed) still has it.+**Software traversal has units alone (2026-11-25, after it).** An offline render under software traversalflattened every instance into world-space triangles (kept so on 2026-11-11, for its bytes to stay main's whileunits were new), and so did a scene with a mesh no tree could be made of or with more instances than a top treediff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 9169184..b4a516a 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1195,7 +1195,9 @@ them (the trace 37 % / 71 % / 16 % longer on the three scenes below), and step 7**Where units are used.** Wherever software traversal is (since 2026-11-25): a session, a browser and an offlinerender alike. Until then an offline render flattened every instance into world-space triangles (the line drawnon 2026-11-11, to keep its bytes main's while units were new), and `THREERT_UNITS` chose; what follows that names-the flattened scene or the variable is of that time. An instance of a mesh without a tree is no unit and is not+the flattened scene or the variable is of that time. Since the same day no triangle is in world space: the tree+over the scene's own triangles and its walk (the still scene's, in what follows) are gone, and the units are all+software traversal walks. An instance of a mesh without a tree is no unit and is notdrawn: a particle system's (its pass is hardware traversal's), a mesh with a vertex that is not a number (said).A scene with more instances than the top tree holds (262,144) draws none of them, and says so.@@ -1222,12 +1224,9 @@ names a record with the instance's rows; hardware traversal fills it), and alreaprocedural objects (`trace_procs`: the ray into the object's space, a tree of its own).**What there is now.** Under software traversal an instance stays an instance: a **unit**.-- **The still scene is the flat tree it was**, walked first, exactly as before. (A scene whose triangles are all- units' has for it a leaf of one triangle without area, put after the meshes' triangles: the tree over nothing's- leaf names triangle 0, which with units is a mesh's first, in model space.)- **A mesh's tree** is built once over its triangles in model space, where they already are (the pool hardwaretraversal builds its BLASes from; under software traversal the mesh's triangles are put in its tree's order, a- cutout triangle carrying its flag). Its nodes sit in the node buffer after the still tree's; a tree is relocatable+ cutout triangle carrying its flag). Its nodes sit in the mesh trees' range of the node buffer; a tree is relocatable(child indices count from its root, leaf triangles from its mesh's first).- **A unit** is the instance's kernel record (160 B), as under hardware traversal, with three of its unused wordsfilled: its mesh tree's root; whether it casts shadows; whether it is placed by a translation alone (the ray then@@ -1249,7 +1248,7 @@ procedural objects (`trace_procs`: the ray into the object's space, a tree of itloose at rest are an eighth of the units, or when the scene is small (64 units: a build is microseconds). Triedand left out: putting a new unit into the one tree leaf by leaf; after a few thousand pieces had flown, raysthrough the piles read several times what a built tree costs them.-- **The kernel** walks the top tree after the still one, with the ray already cut to the still scene's hit; at a+- **The kernel** walks the top tree; at aunit it takes the ray into the unit's space (as `trace_procs` does) and walks the mesh's tree. **The top tree andthe units' trees are walked by one loop**, each turn a node of whichever tree the ray is in: a GPU runs a group ofrays through a loop together, and with a unit's walk as a loop inside the top walk's, a ray that had left a unit@@ -1257,9 +1256,8 @@ procedural objects (`trace_procs`: the ray into the object's space, a tree of ittested first: a ray that meets no unit reads one node, and a scene of one unit has no tree to walk. The hit itreturns is the hit hardware traversal returns (the triangle, the record), so nothing after the traversal differs.- **The unit walk is `shaders/trace_units.wgsl`**, in the kernel under `@if(units)` (`F_UNITS`, a source feature,- as vertex colours are; gpu.rs `KernelVariant::flags`): the file's walk, a call at the end of the still walk, and the still- walk's stack declaration taken out ("The stack"). A scene without units has none of it; hardware traversal's- kernel never does.+ as vertex colours are; gpu.rs `KernelVariant::flags`): the file's walk and the call in `trace`. A scene without+ units has none of it; hardware traversal's kernel never does.- **A mesh that deforms** (a posed skinned model's) is a unit too. Its tree has the shape of a tree built once overits model's bind pose, one shape for every placement of the model (the skinning pass's corners and each suchmesh's triangles are in that tree's order), and the boxes of its pose. A new pose places the model's corners on@@ -1267,9 +1265,6 @@ procedural objects (`trace_procs`: the ray into the object's space, a tree of itchildren), and writes the nodes where they lie; the pass writes the triangles. Made again for a pose, a treecosts sixty times as much (a character of 13,744 triangles, one core: 3.0 ms against 0.05) and walks 4 to 11 %shorter by its nodes' areas.-- Still flattened, as before: every instance of a scene with more of them than a top tree holds (2^18), and every- instance of an offline render (`prepare`; a live session's scene goes through `prepare_live`), unless- `THREERT_UNITS=1`. `THREERT_UNITS=0` flattens everything, as before this step (the A/B).**Edits in place.** The edits that hardware traversal makes in place go through one type (`gpu::Top`: the TLAS andits BLASes, or the units), so the engine's path is the same under both traversals (`live/edits.rs` `move_instances`,@@ -1303,18 +1298,17 @@ that is not its mesh's tree now (freed, or placed again elsewhere), or a unit sinot yet used, and a tree given back, hold leaves that end (`units::FILL`), not zeros (zeros are an interior nodewhose children are nodes 0 and 1). With no unit shown the count is 0 and the kernel does not enter the top range.-**The stack.** One stack of 64 entries for an invocation of a kernel with units: a private variable of the module,-which the still walk uses too (its own declaration is under `@if(!units)`). Why not a walk's own: an array a function declares is set to zero each time the function is+**The stack.** One stack of 64 entries for an invocation of a kernel with units: a private variable of the module.+Why not a walk's own: an array a function declares is set to zero each time the function isentered, whatever the ray then meets, and a ray's walk is entered many times a pixel. The unit walk's own 64 words-cost hello world 0.3 ms a frame, Kabukichō 0.75 and the voxel level 0.55; the still walk's own 48 cost them 0.36,-1.1 and 1.5 more, **and cost every flattened scene the same** (a kernel without units is the file as it is, so it-still pays: "Open" in ROADMAP § 6 step 7c). A walk reads only what it pushed, so what an earlier ray left is never-read. The still walk uses 48 entries, as before, and leaves the stack empty; a unit's walk pushes above what the+cost hello world 0.3 ms a frame, Kabukichō 0.75 and the voxel level 0.55 (and the 48 of the still scene's walk,+while there was one, 0.36, 1.1 and 1.5 more). A walk reads only what it pushed, so what an earlier ray left is never+read. A unit's walk pushes above what thetop walk has pending. The top tree is at most 19 deep (a built tree 18, which holds 2^18 units, the most a scene isgiven units for; a root over two of them). That leaves 45 for a mesh tree. Binned SAH is not balanced: measured onthe CPU, its trees over the catalog's models are 17 deep for 37 k triangles, 20 for 502 k, 22 for a 31 k-trianglebuilding of Kabukichō, and 42 for the 5.86 M triangles of `zero-day` (a balanced tree there is 21), which as part of-a flattened scene fitted the still walk's 48. A mesh tree deeper than 45 is built again by median splits, whose+a flattened scene fitted a stack of 48. A mesh tree deeper than 45 is built again by median splits, whosedepth is log2(triangles / 4): a worse tree to walk, never a wrong one. A push past the stack is dropped (geometrymissed, never a hang), and the builders' bounds mean it is not reached; `the_builders_keep_their_depths` holds themto it.@@ -1577,8 +1571,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, 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.+ colours, the instances' rows, and the triangles' indices ("The scene's triangles" below) (`env_cdf_at`,+ `pword`, `vcolor_word`, `tri_indices`). 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.@@ -1618,25 +1612,20 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/a hand of 0: 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`):+ (`info.z`).+- **A triangle is a mesh's, and 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 forthe section has the material and where the section's triangles and emitters start; its instance's record hasits object and whether its mesh deforms (`INST_DEFORMS`). A light sample is told its emitter's section by thelight 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 (software traversal's, where an- instance is no unit: the build places every triangle by an instance)- has one: its material, its object, its flags, its emitter + 1. They are all the GPU holds: the world-space- triangles'.- **Software traversal's leaves** (`leaves`, binding 2; `indexed::Leaf`). A tree keeps its triangles itself, as anacceleration 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+ candidate's test reads nothing else. The ids: its section of its mesh, and its index inthe section (a tree has a mesh's triangles in its own order). Written at the build and where an edit places amesh; 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, UV and tangent 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 writes whole (those that move in world space) keep three vertices each.+- **What shares.** Corners equal bit for bit in position, normal, UV and tangent are one vertex: each mesh within+ itself, a skinned mesh by its model's corners.- **Particle systems.** A system is a mesh of the pool, four vertices and two triangles a particle, and oneinstance that places nothing (`scene::particle_mesh`, `INST_PARTICLES`): its pass writes the vertices in theworld and their previous positions, and its BLAS is built again after the passes, with the TLAS@@ -1653,8 +1642,8 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/has no tangents (a scene's own geometries, a light's card) has its frame made where it is hit, from itstriangle's edges, its UVs and its first normal.- **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`).+ copy on the GPU has no stride; the kernel reads their positions): 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@@ -2205,7 +2194,7 @@ in a browser") is the last line, not the guarantee: a count above zero is a bug| what the kernel walks | built by | what holds it ||---|---|---|-| the still scene's tree (software traversal), a procedural object's boxes' tree | bvh.rs `build_tris`, `build_boxes` | children after their parent and inside the tree (so a walk that goes down and pops what it pushed reaches each node at most once and ends, whatever the boxes say); every node reached once; leaves of 1 to 16 items inside the items; boxes finite (an item whose box is not is in no leaf, after every leaf's range, its index kept); no deeper than the kernel's stack (48: where the levels left could not finish the split the surface-area heuristic wants, the median); `check_tree` in tests and debug builds |+| a mesh's tree (software traversal), a procedural object's boxes' tree | bvh.rs `build_tris`, `build_boxes` | children after their parent and inside the tree (so a walk that goes down and pops what it pushed reaches each node at most once and ends, whatever the boxes say); every node reached once; leaves of 1 to 16 items inside the items; boxes finite (an item whose box is not is in no leaf, after every leaf's range, its index kept); no deeper than the kernel's stack (48: where the levels left could not finish the split the surface-area heuristic wants, the median); `check_tree` in tests and debug builds || the units' trees, the top tree | units.rs | the same, checked at every build and edit (an incremental path, cheap per unit) || the light tree | ltree.rs | children after their parent; median splits, so the depth is log2 of the entries, within the path codes' 26 bits; leaves of 1 to 4 entries (the child word's two bits); every entry's code leads to its leaf; `LightTree::check` after every build, growth and refit in tests and debug builds. Its walks end by their bounds whatever the data (`LT_PATH_BITS`, the code's depth, four entries) || the emitter CDF's searches | lib.rs | binary searches end on any data (the interval shrinks); the guide table's entries are the CDF's |@@ -2223,8 +2212,8 @@ Where what is built from enters, it is finite:the way) is given to them as three vertices at the origin (`scene::blas_tri`): DXR and Vulkan leave such a vertexundefined behaviour and define a degenerate triangle as never hit; its index stays.-Measured (2026-11-14, software traversal's still tree, `bvh_depth` in a session's load line): Bistro 18 levels,-Kabukichō 26, the Kabukichō district 33: the stack's 48 changes none of them. A tree of boxes spaced in powers of two+Measured (2026-11-14, the one tree software traversal then had over a whole scene): Bistro 18 levels,+Kabukichō 26, the Kabukichō district 33: a stack of 48 changes none of them. A tree of boxes spaced in powers of twois as deep as SAH makes it unheld, and no deeper than asked held (bvh.rs `a_tree_is_no_deeper_than_its_stack`).Garbage in (NaN and infinite vertices, values near f32's limit, a thousand copies of one triangle, a needle;emitters likewise) makes trees the checks pass and the kernel's walk ends on (`garbage_in_makes_a_tree_the_kernel_walks`,diff --git a/renderer/examples/walkable.rs b/renderer/examples/walkable.rsindex ddc3b7e..0681449 100644--- a/renderer/examples/walkable.rs+++ b/renderer/examples/walkable.rs@@ -15,8 +15,8 @@ fn main() -> anyhow::Result<()> {host.setup("r", None)?;let world = host.world.borrow();let sc = scene::build(&world, assets, &threert_render::default_presets_dir(), None)?;- // World-space triangles: the flattened ones and every instance's pool, transformed.- let mut tris: Vec<[Vec3A; 3]> = sc.tris.clone();+ // World-space triangles: every instance's, placed.+ let mut tris: Vec<[Vec3A; 3]> = vec![];for inst in &sc.instances {let m = sc.meshes[inst.mesh as usize];for t in &sc.pool_tris[m.first as usize..(m.first + m.count) as usize] {diff --git a/renderer/shaders/emitter_fill.wgsl b/renderer/shaders/emitter_fill.wgslindex 412e5d2..c49f922 100644--- a/renderer/shaders/emitter_fill.wgsl+++ b/renderer/shaders/emitter_fill.wgsl@@ -1,11 +1,10 @@// The light list's triangles (lib.rs `GpuEmitterTri`) taken again from where their triangles are now: what real-time// engines' "prepare lights" pass does. One run of the list an invocation row (gpu.rs `EmitterFill`): the emitters-// something has moved since the list was written (the triangles the CPU reposed, the particles their passes place,-// the instances that moved).+// something has moved since the list was written (the particles their passes place, the instances that moved).struct Run { first: u32, count: u32 };@group(0) @binding(0) var<storage, read> runs: array<Run>;// 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).+// counted from the first vertex of the mesh an instance places).@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@@ -15,7 +14,6 @@ struct Run { first: u32, count: u32 };// 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.@group(0) @binding(3) var<storage, read_write> instances: array<vec4<f32>>;const INSTANCE_VEC4: u32 = 10u;-const NO_INST: u32 = 0xffffffffu;@compute @workgroup_size(64)fn fill(@builtin(global_invocation_id) id: vec3<u32>) {@@ -26,19 +24,16 @@ fn fill(@builtin(global_invocation_id) id: vec3<u32>) {// 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 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];- let m2 = instances[inst * INSTANCE_VEC4 + 2u];- for (var k = 0u; k < 3u; k++) {- rows[k] = vec3<f32>(dot(m0.xyz, rows[k]), dot(m1.xyz, rows[k]), dot(m2.xyz, rows[k]));- }- rows[0] += vec3<f32>(m0.w, m1.w, m2.w);+ let m0 = instances[inst * INSTANCE_VEC4];+ let m1 = instances[inst * INSTANCE_VEC4 + 1u];+ let m2 = instances[inst * INSTANCE_VEC4 + 2u];+ for (var k = 0u; k < 3u; k++) {+ rows[k] = vec3<f32>(dot(m0.xyz, rows[k]), dot(m1.xyz, rows[k]), dot(m2.xyz, rows[k]));}+ rows[0] += vec3<f32>(m0.w, m1.w, m2.w);for (var k = 0u; k < 3u; k++) {list[r + k] = vec4<u32>(bitcast<vec3<u32>>(rows[k]), list[r + k].w);}diff --git a/renderer/shaders/gpu_particles.wgsl b/renderer/shaders/gpu_particles.wgslindex 2023329..24e5333 100644--- a/renderer/shaders/gpu_particles.wgsl+++ b/renderer/shaders/gpu_particles.wgsl@@ -1,9 +1,9 @@// Stateful GPU particles (gpu.rs `GpuParticlesGpu`; ROADMAP § 6 step 5a): each `GpuParticles` node's particles live in// a state buffer on the GPU (position and age, velocity and life, colour and size), emitted, updated, collided and// retired here every frame; the CPU keeps no particle. Like `Particles` (particles.wgsl), a particle is a quad of two-// dynamic triangles and its own object (pivot, bounds, per-particle data: its colour, the material function's-// `i.custom`); this pass writes the kernel's triangle data, last frame's positions (motion vectors), the BLAS input and-// the objects, and the dynamic BLASes are rebuilt after it.+// triangles of its system's mesh and its own object (pivot, bounds, per-particle data: its colour, the material+// function's `i.custom`); this pass writes the kernel's triangle data, last frame's positions (motion vectors), the+// BLAS input and the objects, and the systems' BLASes are rebuilt after it.//// A particle program is two WGSL bodies (`ParticleProgram` in @threert/scene), parameters `$Name` in `p`:// fn pe_<name>(i: EIn, p: array<vec4<f32>, 8>) -> PState { var s: PState; <emit code> return s; }@@ -64,7 +64,7 @@ struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, d: vec4<f32>, e: vec4<@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(5) var<storage, read_write> objects: array<vec4<f32>>;-// This pass's last positions of its vertices (the previous positions' indexing; a repose re-uploads the dynamic tail).+// This pass's last positions of its vertices (the previous positions' indexing).@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>>;diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgslindex 6f1609f..dcb4d1c 100644--- a/renderer/shaders/particles.wgsl+++ b/renderer/shaders/particles.wgsl@@ -2,8 +2,7 @@// its particles. A particle is a quad of its system's mesh (scene.rs `ParticleSystem`: four vertices) and its own// object (pivot, bounds, per-particle data for material functions). The pass writes the vertices (positions and// shading attributes; the systems' BLASes are built from them after it), last frame's positions as `prev_verts`-// (motion vectors; from its own copy `last`, since a repose re-uploads the dynamic tail from the CPU) and the-// objects.+// (motion vectors; from its own copy `last`) and the objects.//// A particle function is a WGSL body (`ParticleFunction` in @threert/scene) run per particle:// fn pf_<name>(i: PIn, p: array<vec4<f32>, 8>) -> POut { var o = POut(...); <code> return o; }diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 5c38a41..1e91511 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -33,7 +33,6 @@ const TRACE_ANY: u32 = 2u;// Any hit on any surface, alpha-cutout triangles taken as opaque (live emitter shadow rays: `emitter_tr`).const TRACE_ANY_OPAQUE: u32 = 3u;const TRI_MASKED: u32 = 2u;-const TRI_DYNAMIC: u32 = 4u;// Highest texture-page mip (texpack::MIPS - 1) and the ray-cone LOD bias (negative = sharper; accumulation antialiases).const TEX_MAX_LEVEL: f32 = 4.0;const LOD_BIAS: f32 = 0.5;@@ -76,7 +75,6 @@ const F_TEX: u32 = 256u;const F_FUNC: u32 = 512u;const F_GLASS: u32 = 2048u;const F_COAT: u32 = 4096u;-const F_HUGE: u32 = 8192u;const F_INST: u32 = 16384u;const F_MEDIA: u32 = 32768u;const F_PEMIT: u32 = 65536u; // opaque particles' emitters (one not shown has no area)@@ -112,8 +110,7 @@ struct Params {vol2: vec4<f32>, // volumetric albedo tint rgb, range (m, 0 = unlimited)jitter: vec4<f32>, // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -cache: vec4<f32>, // live radiance cache (1 = on), history cap in samples, history cap in frames, -- motion: vec4<f32>, // live motion vectors: 1 = on, -, -, - (first dynamic triangle: group_first[1].x)- group_first: array<vec4<u32>, 2>, // first global triangle of each traversal group ([1].x = the first dynamic one)+ motion: vec4<f32>, // live motion vectors: 1 = on; `render --signals`; software traversal's units: the top tree's root, their count (bits)light_lod: vec4<f32>, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off)emit_power: vec4<f32>, // the emitter CDF's power and cull as the CPU built it (lib.rs `EmitterCull`); not read herelod_view: vec4<f32>, // emitter cull's view cone (lib.rs EmitterCull): forward direction, cos of the half-angle@@ -147,8 +144,8 @@ struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: 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.+// (e1, id), (e2, -). A candidate's test reads nothing else. The ids: its section of its mesh, 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); }@@ -164,7 +161,7 @@ const VERTEX_VEC4: u32 = 3u;fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }@group(0) @binding(11) var<storage, read_write> accum: array<Pixel>;// 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.+// them 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> };@@ -199,9 +196,9 @@ fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }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; `part`: as a hit's (`Hit.part`): its section of its-// instance's mesh, or its own row; `flags`: EMITTER_CARD. Four vec4s, a cache line.+// (attributes: `emitter_attrs`), `inst`: the instance that places it, `code`: the light tree's path 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;+// `flags`: EMITTER_CARD. Four vec4s, a cache line.struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32, part: u32, flags: u32 };const EMITTER_TRI_VEC4: u32 = 4u;const EMITTER_MOVES: u32 = 0x80000000u;@@ -306,50 +303,37 @@ 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[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-// section, which its instance has; on the triangle itself where no instance places it.+// The material of a triangle, given its attributes and the instance that places it. 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 section,+// which its instance has.fn material_of(a: TriAttr, inst: u32) -> u32 {- let m = triangle_material(a);- if (has(F_INST) && inst != NO_INST) { return row_word(instance_at(inst).info.w, m, 0u) & ROW_MATERIAL; }- return m;+ if (!has(F_INST) || inst == NO_INST) { return 0u; }+ return row_word(instance_at(inst).info.w, bitcast<u32>(a.uv.w), 0u) & ROW_MATERIAL;}-// The material a triangle itself holds: one that no instance places.-fn triangle_material(a: TriAttr) -> u32 { return bitcast<u32>(a.uv.w); }-// 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.+// A triangle's three vertices (indexed.rs), counted from its mesh's first: 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 (software traversal's, of an instance that is no unit), 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: its entry says (lib.rs `EMITTER_CARD`).const EMITTER_CARD: u32 = 1u;fn emitter_is_card(em: EmitterTri) -> bool { return (em.flags & EMITTER_CARD) != 0u; }// 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; `x`: -, its object (an instance's: where its-// attributes are placed, `inst_x`), -, its emitter entry + 1. `vi`: where its three vertices are in `vertices`-// (their tangents are read where a frame is asked: `hit_tangent`). `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.+// corner; `uv.w`: its section (`part`); `x.y`: its object (where its attributes are placed, `inst_x`: of a particle+// system's mesh, which particle it is). `vi`: where its three vertices are in `vertices` (their tangents are read+// where a frame is asked: `hit_tangent`). `inst`, `part`: as a hit has them (`Hit`): its vertices count from its+// mesh's first.struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32>, vi: vec3<u32> }fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {var base = 0u;- var row = vec4<u32>(part, 0u, 0u, 0u);+ var particle = 0u;if (has(F_INST) && inst != NO_INST) {let r = instance_at(inst);base = r.info.z;// A particle system's mesh: which particle the triangle is (two each, from the mesh's first).- if (has(F_PART) && (bitcast<u32>(r.n1.w) & INST_PARTICLES) != 0u) { row.y = (ti - r.info.x) >> 1u; }- } else {- row = tri_row(part);+ if (has(F_PART) && (bitcast<u32>(r.n1.w) & INST_PARTICLES) != 0u) { particle = (ti - r.info.x) >> 1u; }}let i = (tri_indices(ti) + vec3<u32>(base)) * VERTEX_VEC4;let p0 = vertices[i.x];@@ -370,14 +354,14 @@ fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {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)),- vec4<f32>(0.0, bitcast<f32>(row.y), 0.0, bitcast<f32>(row.w))), p0.xyz, e1, e2, i);+ 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>(part)),+ vec4<f32>(0.0, bitcast<f32>(particle), 0.0, 0.0)), p0.xyz, e1, e2, i);}// The tangent frame at a point of a triangle (barycentrics u, v), in the world: (tangent, hand). Its three vertices'// tangents there (a file's, a particle's), the hand its first vertex's; a triangle without tangents (a hand of 0)// has its 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. Not of unit length where it is its vertices': who asks makes it so against the-// normal. Asked where a frame is read: a normal map, a function.+// instance (`inst`; NO_INST: left as it is). Not of unit length where it is its vertices': who asks makes it so+// against the normal. Asked where a frame is read: a normal map, a function.fn hit_tangent(td: TriData, inst: u32, u: f32, v: f32) -> vec4<f32> {let t0 = vertices[td.vi.x + 2u];var t = vec4<f32>(t0.xyz * (1.0 - u - v) + vertices[td.vi.y + 2u].xyz * u + vertices[td.vi.z + 2u].xyz * v, t0.w);@@ -416,7 +400,7 @@ fn unit_or_zero(v: vec3<f32>) -> vec3<f32> {return vec3<f32>(0.0);}-// A model-space triangle's shading attributes placed by instance r (scene::instance_attr). (Not its tangents, which+// A model-space triangle's shading attributes placed by instance r. (Not its tangents, which// are placed where they are read: `hit_tangent`.)fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {var b = a;@@ -622,10 +606,11 @@ 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.-// `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.+// `inst`: the instance whose triangle `tri` is, in its mesh's space (a procedural hit's: its object's record; no+// hit: NO_INST). `part`: 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.+// (What reads a hit's record tests `inst != NO_INST`, which every hit passes: without the test a frame is 1 to 3 %+// longer in some scenes, a crowd under the sky 6.36 -> 6.57 ms.)struct Hit { t: f32, tri: u32, u: f32, v: f32, inst: u32, part: u32 };const NO_INST: u32 = 0xffffffffu;@@ -728,7 +713,7 @@ fn proc_normal(h: Hit) -> vec3<f32> {return normalize(vec3<f32>(dot(r.n0.xyz, n), dot(r.n1.xyz, n), dot(r.n2.xyz, n)));}-// The software BVH walk (without `hwrt`: trace_hw.wgsl's traversal is the hardware's).+// Software traversal (without `hwrt`: trace_hw.wgsl's traversal is the hardware's).@if(!hwrt) fn ray_aabb(o: vec3<f32>, inv_d: vec3<f32>, bmin: vec3<f32>, bmax: vec3<f32>, tmax: f32) -> f32 {let t0 = (bmin - o) * inv_d;@@ -760,59 +745,12 @@ fn proc_normal(h: Hit) -> vec3<f32> {return vec3<f32>(t, u, v);}-// mode: TRACE_CLOSEST, TRACE_SHADOW (any hit among shadow casters), TRACE_ANY (any hit on any surface).+// mode: TRACE_CLOSEST, TRACE_SHADOW (any hit among shadow casters), TRACE_ANY (any hit on any surface). The scene's+// triangles are its units' (trace_units.wgsl), then the procedural objects.@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, 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>;- var sp = 0u;- var node = 0u;- loop {- let n = nodes[node];- if (n.count > 0u) {- for (var k = 0u; k < n.count; k++) {- let ti = n.left_or_first + k;- let r = intersect_tri(o, d, ti, hit.t);- if (r.x < hit.t) {- 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; }- }- }- if (sp == 0u) { break; }- sp--;- node = stack[sp];- continue;- }- let l = n.left_or_first;- let r = l + 1u;- let nl = nodes[l];- let nr = nodes[r];- var tl = ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);- var tr = ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);- if (tl == INF && tr == INF) {- if (sp == 0u) { break; }- sp--;- node = stack[sp];- continue;- }- var near = l;- var far = r;- if (tr < tl) {- near = r;- far = l;- let tmp = tl; tl = tr; tr = tmp;- }- node = near;- if (tr != INF && sp < 48u) {- stack[sp] = far;- sp++;- }- }- @if(units) hit = trace_units(o, d, inv_d, hit, mode);+ @if(units) hit = trace_units(o, d, 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20)), hit, mode);if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }return hit;}@@ -1266,8 +1204,8 @@ 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; `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.)+// `inst`: the instance the triangle is placed by (as `surface` places it); `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;@@ -1329,8 +1267,7 @@ 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;-// `part`: as a hit's.+// the instance the triangle belongs to (it places the triangle's edges: its texel density); `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;@@ -2036,7 +1973,7 @@ fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {}// What light sampling reads of an emitter's attributes (UVs, material, object), as shading has them at a hit of it:-// its triangle's, with its instance's object if it has one. (Not the normals and the tangent, which stay the mesh's:+// its triangle's, with its instance's object. (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 = tri_data(em.tri, em.inst, em.part).a;@@ -2055,24 +1992,18 @@ fn emitter_attrs(em: EmitterTri) -> TriAttr {// 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. 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 rows = instance_at(hit.inst).info.w;- let first = row_word(rows, hit.part, 2u);- if (first == NO_EMITTER) { return 1.0; }- 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);+ if (is_proc(hit) || !has(F_INST) || P.counts.y == 0u) { return 1.0; }+ // The hit triangle's emitter: its index in its section, counted from the section's first entry (its instance's+ // row's; none: it is not light-sampled).+ let rows = instance_at(hit.inst).info.w;+ let first = row_word(rows, hit.part, 2u);+ if (first == NO_EMITTER) { return 1.0; }+ let entry = first + hit_rank(hit, rows);+ let em = emitter_tri_at(entry);let cr = cross(em.e1, em.e2);let area = 0.5 * length(cr);let cos_l = abs(dot(normalize(cr), d));- let sel = emitter_pmf(entry - 1u, em, mis_x, mis_n);+ let sel = emitter_pmf(entry, em, mis_x, mis_n);if (!(sel > 0.0)) { return 1.0; }return power_heuristic(pdf, sel / max(area, 1e-12) * hit.t * hit.t / max(cos_l, 1e-6));}@@ -3652,8 +3583,7 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {lt_fb = LT_NONE;}// (The hit point as the ray's origin, at distance 0.)- // (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 s = surface(r2.xyz, r3.xyz, Hit(0.0, r0.w, bitcast<f32>(r1.y), bitcast<f32>(r1.z), r1.x, fl >> 16u), 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);@@ -4058,17 +3988,10 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {if (depth == 0u) {first_t = hit.t;let ti = hit.tri;- // The first dynamic triangle is the first of traversal group 4 (a u32: an index carried as f32 bits would be a- // denormal below 2^23, which a driver may flush to zero).- // Dynamic triangles 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.+ // A deforming mesh keeps its previous vertices in model space, where its instance's record says.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) && has(F_INST)) {+ deforms = has(F_DEFORM) && (bitcast<u32>(instance_at(hit.inst).n1.w) & INST_DEFORMS) != 0u;}if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {// Procedural geometry: its object-space hit point through the previous frame's rows.@@ -4077,7 +4000,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {let lp = vec4<f32>(proc_point(r, s.p), 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 (LIVE && P.motion.x > 0.5 && has(F_INST) && hit.inst != NO_INST) {+ } else if (LIVE && P.motion.x > 0.5 && has(F_INST)) {// A movable instance: its model-space hit point (the previous pose's for a deforming mesh) through the// previous frame's transform (p rows; the same as m when it did not move).let r = instance_at(hit.inst);@@ -4098,12 +4021,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {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) {- // (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); }albedo = select(s.base, s.emissive / max(max(s.emissive.r, max(s.emissive.g, s.emissive.b)), 1e-6), s.card);@@ -4161,7 +4078,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 = (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)+ let fl = (min(depth, 255u) << 8u) | (hit.part << 16u) | 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/trace_hw.wgsl b/renderer/shaders/trace_hw.wgslindex b565b2f..c004c7b 100644--- a/renderer/shaders/trace_hw.wgsl+++ b/renderer/shaders/trace_hw.wgsl@@ -1,8 +1,7 @@-// Hardware ray tracing (wgpu ray query). Up to four instances (see Prepared::groups): shadow casters mask 1, the rest-// mask 2 (glass among them; an instance's glass among its other sections is stepped through by its row). Every-// geometry is flagged opaque: none reports candidates, and a cutout's hit is confirmed by `alpha_pass`.-// instance_custom_data holds the instance's first global triangle index, or in scenes where a group starts beyond-// 2^24 triangles (F_HUGE: custom data has 24 bits) its traversal group, whose first triangle is in P.group_first.+// Hardware ray tracing (wgpu ray query). A TLAS instance a model instance or a procedural object: shadow casters+// mask 1, the rest mask 2 (glass among them; an instance's glass among its other sections is stepped through by its+// row). Every geometry is flagged opaque: none reports candidates, and a cutout's hit is confirmed by `alpha_pass`.+// instance_custom_data holds the instance's record.@if(hwrt) @group(0) @binding(19) var acc: acceleration_structure;@if(hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {@@ -97,48 +96,30 @@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); }+ // (A triangle is an instance's: a scene without instances has none.)+ if (!has(F_INST)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }+ // Its instance's record is the custom data; ti is its mesh's triangle, in model space, and the geometry it was+ // hit in its section.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, 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));+ return Hit(it.t, ti, it.barycentrics.x, it.barycentrics.y, it.instance_custom_data, it.geometry_index);}// The first word of the row of the hit `trace_opaque` last found (its material and class bits), NO_ROW where its// instance has no rows: the trace's tests of a hit read no attribute and no material then.@if(hwrt) var<private> hit_row: u32;@if(hwrt) const NO_ROW: u32 = 0xffffffffu;-// Whether that hit is an alpha-cutout's: its row says, or without a row (a triangle no instance places) its own-// 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(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.-@if(hwrt) fn hit_inst(custom: u32) -> u32 {- return select(NO_INST, custom & (INSTANCE_BIT - 1u), has(F_INST) && (custom & INSTANCE_BIT) != 0u);-}--@if(hwrt) const INSTANCE_BIT: u32 = 0x800000u;--// Global triangle of a hit: an instance's pool triangle, or a traversal group's. An instance's geometry is a section-// of its mesh, and its row has where the section's triangles start (the first section starts where the mesh does);-// the row's class is read where the trace tests a hit by it.-@if(hwrt) fn hit_tri(custom: u32, geometry: u32, prim: u32) -> u32 {- if (has(F_INST) && (custom & INSTANCE_BIT) != 0u) {- let rec = instance_at(custom & (INSTANCE_BIT - 1u));- if (has(F_MASKED) || has(F_IGLASS)) { hit_row = row_word(rec.info.w, geometry, 0u); }- var first = rec.info.x;- if (geometry != 0u) { first = row_word(rec.info.w, geometry, 1u); }- return first + prim;- }- return group_tri(custom, prim);-}+// Whether that hit is an alpha-cutout's: its row says.+@if(hwrt) fn cutout_hit(h: Hit) -> bool { return hit_row != NO_ROW && (hit_row & ROW_CUTOUT) != 0u; }-@if(hwrt) fn group_tri(custom: u32, prim: u32) -> u32 {- if (has(F_HUGE)) { return P.group_first[custom >> 2u][custom & 3u] + prim; }- return custom + prim;+// The triangle of a hit of the instance at record `inst`. The geometry is a section of its mesh, and its row has+// where the section's triangles start (the first section starts where the mesh does); the row's class is read where+// the trace tests a hit by it.+@if(hwrt) fn hit_tri(inst: u32, geometry: u32, prim: u32) -> u32 {+ let rec = instance_at(inst);+ if (has(F_MASKED) || has(F_IGLASS)) { hit_row = row_word(rec.info.w, geometry, 0u); }+ var first = rec.info.x;+ if (geometry != 0u) { first = row_word(rec.info.w, geometry, 1u); }+ return first + prim;}// gpu.rs `KernelSwitches::strict`: a ray a ray query must not be given (not finite, or a length that is negative or NaN).diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgslindex 6ef15a5..158be12 100644--- a/renderer/shaders/trace_units.wgsl+++ b/renderer/shaders/trace_units.wgsl@@ -11,25 +11,22 @@// is placed by a translation alone, its normal rows the identity's: the ray keeps its direction and only its origin// moves, which is what the rows would have made of it.//-// `trace` walks the still scene first and calls this with its hit: the ray is already cut to it.-//-// The stack is the module's, one for an invocation of the kernel, and in a kernel with units the still walk uses it-// too (`@if(!units)` takes its own away). An array a function declares is set to zero each time the-// function is entered, whatever the ray then meets, and a ray's walk is entered many times a pixel: the unit walk's-// own 64 words cost hello 0.3 ms a frame and the city 0.75, and the still walk's 48 cost every scene as much again,-// flattened ones too. This one is set to zero once. A walk reads only what it has pushed: what an earlier ray left-// is never read. The still walk has left it empty; a unit's walk pushes above what the top walk has pending and is-// done when it is back down to it. 64 entries: 19 for the top tree, 45 for a mesh's (units.rs `STACK`); the still-// walk uses 48 of them, as before. Every index read here was checked on the CPU when it was written (units.rs-// `check_mesh`, `check_top`), the depths with them.+// The stack is the module's, one for an invocation of the kernel. An array a function declares is set to zero each+// time the function is entered, whatever the ray then meets, and a ray's walk is entered many times a pixel: the+// unit walk's own 64 words cost hello 0.3 ms a frame and the city 0.75. This one is set to zero once. A walk reads+// only what it has pushed: what an earlier ray left is never read. A unit's walk pushes above what the top walk has+// pending and is done when it is back down to it. 64 entries: 19 for the top tree, 45 for a mesh's (units.rs+// `STACK`). Every index read here was checked on the CPU when it was written (units.rs `check_mesh`, `check_top`),+// the depths with them.//// One loop walks both levels: a GPU runs a group of rays through a loop together, and a ray that has left an inner// loop waits for the others of its group to leave it; with the unit's walk as a loop inside the top walk's, every// ray of a group waited at every unit for the group's slowest (the voxel level, 10,459 units: the trace pass 6.8 ms-// for as many iterations as the flattened scene's 4.5 ms). Here each turn of the loop is a node of whichever tree-// the ray is in: `rec` says which (NO_INST: the top tree), and with it the ray (`ro`, `rd`, `rinv`: the world's, or-// the unit's), what child indices count from (`off`) and the unit's first triangle. A top leaf sets these and goes-// to the unit's root; when the stack is back down to where the unit was entered (`base`), they are set back.+// for as many iterations as the same scene flattened to world space took 4.5 ms for). Here each turn of the loop is+// a node of whichever tree the ray is in: `rec` says which (NO_INST: the top tree), and with it the ray (`ro`, `rd`,+// `rinv`: the world's, or the unit's), what child indices count from (`off`) and the unit's first triangle. A top+// leaf sets these and goes to the unit's root; when the stack is back down to where the unit was entered (`base`),+// they are set back.//// The root's box is tested before the walk: a ray that meets no unit reads one node, and a scene of one unit is a// root that is a leaf, whose record only the rays that meet its box read.diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgslindex e496a94..a214237 100644--- a/renderer/shaders/translucent.wgsl+++ b/renderer/shaders/translucent.wgsl@@ -55,12 +55,11 @@return t;}-// Material of a translucent particle at a hit of `tacc` (its primitive, its instance's custom data, barycentrics b):+// Material of a translucent particle at a hit of `tacc` (its primitive, its instance's record, barycentrics b):// colour, opacity and emission after maps and its material function.-@if(hwrt) fn particle_material(prim: u32, custom: u32, b: vec2<f32>, view: vec3<f32>, lod: f32) -> MatOut {+@if(hwrt) fn particle_material(prim: u32, inst: u32, b: vec2<f32>, view: vec3<f32>, lod: f32) -> MatOut {// Its system's mesh: the triangles from the instance's record's first, one section; its particle's object from// the instance's first.- let inst = hit_inst(custom);let rec = instance_at(inst);let ti = rec.info.x + prim;let td = tri_data(ti, inst, 0u);diff --git a/renderer/src/bvh.rs b/renderer/src/bvh.rsindex b102aae..994f662 100644--- a/renderer/src/bvh.rs+++ b/renderer/src/bvh.rs@@ -50,21 +50,19 @@ const BINS: usize = 16;const MAX_LEAF: usize = 4;/// The most items a leaf the surface-area heuristic prefers to a split may hold.const SAH_LEAF: usize = 16;-/// The kernel's stack for this module's trees (pathtrace.wgsl `trace`, `trace_procs`: `array<u32, 48>`). A walk holds-/// at most one entry a level of its tree, so a tree no deeper than this is walked whole; a push past it would be-/// dropped (geometry missed, never a hang).+/// The kernel's stack for a tree of boxes (pathtrace.wgsl `trace_procs`: `array<u32, 48>`). A walk holds at most one+/// entry a level of its tree, so a tree no deeper than this is walked whole; a push past it would be dropped+/// (geometry missed, never a hang).pub const STACK: usize = 48;-/// The tree over no triangle, as the kernel can walk it. A node with `count: 0` is an interior node to the kernel-/// (pathtrace.wgsl `trace`): the one-node tree this module used to make for nothing had itself for a left child and,-/// for a right child, whatever lay after the node buffer's 32 bytes. Where that was zeros the walk ended; where it was-/// what an earlier scene left there, it might not (a dispatch that does not end: docs/RUNTIME.md "The engine in a-/// browser"). The encoding has no empty leaf, so this is a leaf of one triangle, triangle 0: with no triangles the-/// vertex buffer is zeros (gpu.rs `upload`), a triangle without area that no ray meets (`intersect_tri`: its-/// determinant is 0). One node read, no child, no box.+/// The tree over no triangle, and what unused room in a node buffer holds (units.rs `FILL`): a node that ends a+/// walk. A node with `count: 0` is an interior node to the kernel: one of zeros has itself for a left child and the+/// node after it for a right child, and a walk that lands on it may not end (docs/RUNTIME.md "The engine in a+/// browser"). The encoding has no empty leaf, so this is a leaf of one triangle, without a box. One node read, no+/// child.pub const EMPTY: GpuNode = GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [0.0; 3], count: 1 };-/// The tree over triangles the kernel's software traversal walks (the still scene's), no deeper than `STACK`.+/// The tree over triangles, no deeper than `STACK`.pub fn build(tris: &[[V; 3]]) -> Bvh {build_tris(tris, STACK)}@@ -303,11 +301,12 @@ mod tests {}}- /// The kernel's software traversal (pathtrace.wgsl `trace`, its loop statement for statement) on the CPU, with- /// what the kernel does not have: every read checked, and the steps counted. `tris`: the triangles the vertex- /// buffer holds. Returns the triangles the ray is tested against; an error where the kernel would read a node or- /// a triangle that is not there, or would not stop. No triangle is ever hit here (the ray keeps its full length),- /// so the walk visits at least every node the kernel visits for the same ray.+ /// The kernel's walk of one tree (pathtrace.wgsl `trace_procs`' loop, statement for statement; a unit's tree is+ /// walked the same way, units.rs) on the CPU, with what the kernel does not have: every read checked, and the+ /// steps counted. `tris`: how many items the leaves may name. Returns the items the ray is tested against; an+ /// error where the kernel would read a node or an item that is not there, or would not stop. Nothing is ever hit+ /// here (the ray keeps its full length), so the walk visits at least every node the kernel visits for the same+ /// ray.fn walk(nodes: &[GpuNode], tris: usize, o: V, d: V) -> Result<Vec<u32>, String> {let node_at = |i: u32| nodes.get(i as usize).copied().ok_or(format!("reads node {i} of {}", nodes.len()));let inv_d = V::ONE / V::select(d.abs().cmplt(V::splat(1e-20)), V::splat(1e-20), d);@@ -362,25 +361,25 @@ mod tests {#[test]fn the_walk_is_the_kernels_loop() {let src = include_str!("../shaders/pathtrace.wgsl");- let (_, rest) = src.split_once("fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {").expect("the kernel's trace");- let (body, _) = rest.split_once("if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }").expect("the end of the triangles' loop");+ let (_, rest) = src.split_once("fn trace_procs(o: vec3<f32>, d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {").expect("the kernel's walk of a tree of boxes");+ let (body, _) = rest.split_once("\n}\n").expect("its end");let lines = [- "let inv_d = 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20));",+ "let inv = 1.0 / select(ld, vec3<f32>(1e-20), abs(ld) < vec3<f32>(1e-20));","var stack: array<u32, 48>;","var node = 0u;",- "let n = nodes[node];",- "if (n.count > 0u) {",- "for (var k = 0u; k < n.count; k++) {",- "let ti = n.left_or_first + k;",+ "let w = nb + node * 8u;",+ "let first_or_left = pword(w + 3u);",+ "let count = pword(w + 7u);",+ "if (count > 0u) {",+ "for (var q = 0u; q < count; q++) {",+ "let p = pword(ob + first_or_left + q);","if (sp == 0u) { break; }","node = stack[sp];",- "let l = n.left_or_first;",- "let r = l + 1u;",- "let nl = nodes[l];",- "let nr = nodes[r];",- "var tl = ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);",- "var tr = ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);",+ "let wl = nb + first_or_left * 8u;",+ "var tl = ray_aabb(lo, inv, proc_vec(wl), proc_vec(wl + 4u), hit.t);",+ "var tr = ray_aabb(lo, inv, proc_vec(wl + 8u), proc_vec(wl + 12u), hit.t);","if (tl == INF && tr == INF) {",+ "var far = first_or_left + 1u;","if (tr < tl) {","node = near;","if (tr != INF && sp < 48u) {",@@ -388,7 +387,7 @@ mod tests {];let mut at = 0;for l in lines {- at += body[at..].find(l).unwrap_or_else(|| panic!("the kernel's trace no longer has `{l}` where the walk expects it"));+ at += body[at..].find(l).unwrap_or_else(|| panic!("the kernel's walk no longer has `{l}` where the walk expects it"));}assert!(src.contains("let tn = max(max(tmin_v.x, tmin_v.y), max(tmin_v.z, 0.0));\n let tf = min(min(tmax_v.x, tmax_v.y), min(tmax_v.z, tmax));\n return select(INF, tn, tn <= tf);"), "ray_aabb");assert!(src.contains("const INF: f32 = 3.0e38;"));@@ -403,10 +402,6 @@ mod tests {}}- /// The kernel walks every tree `build` makes without reading past its nodes or its triangles, and stops: trees- /// over no triangle (a scene with nothing in it, or with procedural geometry only), one, a leaf's worth, many.- /// The empty scene's vertex buffer holds zeros (gpu.rs `upload`: 512 bytes, so triangles 0..2 are there, without- /// area)./// Garbage in (as Embree's builders are tested): every tree `build_tris` makes of it is one `check_tree` passes/// (the builder checks itself in tests), that the kernel's walk ends on within its buffers, with the items whose/// box is not finite after every leaf's range. NaN and infinite vertices among good ones, all of them bad, values@@ -440,7 +435,7 @@ mod tests {assert_eq!(tail, bad, "{what}: the items left out come last");for k in 0..200 {let o = V::new(k as f32 - 100.0, 7.0, 3.0);- walk(&b.nodes, tris.len().max(3), o, (V::new(0.3, -1.0, 0.2) - o * 0.001).normalize()).unwrap_or_else(|e| panic!("{what}: {e}"));+ walk(&b.nodes, tris.len(), o, (V::new(0.3, -1.0, 0.2) - o * 0.001).normalize()).unwrap_or_else(|e| panic!("{what}: {e}"));}}}@@ -476,8 +471,8 @@ mod tests {for n in [0usize, 1, 2, 4, 5, 17, 1000] {let tris: Vec<[V; 3]> = (0..n).map(|_| { let c = p(20.0); [c + p(1.0), c + p(1.0), c + p(1.0)] }).collect();let b = build(&tris);- // (An empty scene's buffer: 512 zero bytes are 10 vec4s, three triangles' worth and a third.)- let held = if n == 0 { 3 } else { n };+ // (The tree over nothing is a leaf of one item: `EMPTY`.)+ let held = n.max(1);let mut rays: Vec<(V, V)> = (0..2000).map(|_| (p(60.0), p(2.0).normalize_or(V::X))).collect();// Rays through the origin and along the axes (an empty tree's boxes are at the origin).for a in [V::X, V::Y, V::Z, V::ONE.normalize(), V::new(1.0, -1.0, 0.0).normalize()] {diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex 9052c66..e54e913 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -1,8 +1,7 @@-//! Headless wgpu backend: uploads the flattened scene once, accumulates path-traced samples, reads back HDR.+//! Headless wgpu backend: uploads the scene once, accumulates path-traced samples, reads back HDR.use crate::heap::{Heap, Live, Section, Stream, Table};use crate::scene::Scene;-use crate::GROUPS;use anyhow::{anyhow, Result};use web_time::Instant;use wgpu::util::DeviceExt;@@ -143,10 +142,7 @@ pub struct Params {pub vol2: [f32; 4], // volumetric albedo tint rgb, range (m, 0 = unlimited)pub jitter: [f32; 4], // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -pub cache: [f32; 4], // live radiance cache (1 = on), history cap in samples, history cap in frames, -- pub motion: [f32; 4], // live motion vectors: 1 = on, -, -, - (first dynamic triangle: group_first[1][0])- /// First global triangle of each traversal group (`Prepared::groups`; group 4 = the first dynamic one). Hardware- /// BLAS instances carry their group index, not this offset: instance custom data has only 24 bits (16.7 M).- pub group_first: [[u32; 4]; 2],+ pub motion: [f32; 4], // live motion vectors: 1 = on; `render --signals`; software traversal's units: the top tree's root, their count (bits)/// Light LOD (live; `emitter_lod`): reference position, d0 (0 = off).pub light_lod: [f32; 4],/// x: the emitter CDF's total without light LOD (camera-hit MIS weighs by power alone; = misc[1] when it is off);@@ -253,8 +249,6 @@ pub struct PendingProc {pub struct TopBuild {/// Instances (hardware traversal's TLAS instances, software traversal's units) moved, came or went.pub instances: bool,- /// The dynamic groups' BLASes: their triangles were re-transformed.- pub dynamic: bool,/// Instanced meshes' BLASes: new meshes, a skinned model's new pose. (Software traversal: their trees are written/// by then; the top tree is made over their bounds.)pub meshes: Vec<u32>,@@ -264,7 +258,7 @@ pub struct TopBuild {impl TopBuild {pub fn any(&self) -> bool {- self.instances || self.dynamic || !self.meshes.is_empty() || !self.procs.is_empty()+ self.instances || !self.meshes.is_empty() || !self.procs.is_empty()}}@@ -286,7 +280,7 @@ fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec<wgpu::BlasBuildEntrfirst_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),+ first_index: Some(accel.index_first + first * 3),transform_buffer: None,transform_buffer_offset: None,})@@ -297,28 +291,6 @@ fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec<wgpu::BlasBuildEntr.collect()}-/// The build entries of the dynamic groups' BLASes (groups 4 and up) over their triangles as they are now.-fn dynamic_entries(accel: &Accel) -> Vec<wgpu::BlasBuildEntry<'_>> {- accel- .blases- .iter()- .filter(|b| b.1 >= 4)- .map(|(blas, _, first, size)| wgpu::BlasBuildEntry {- blas,- geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {- size,- vertex_buffer: &accel.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,- }]),- })- .collect()-}-/// The acceleration structure's binding in the scene's group (trace_hw.wgsl `acc`): the last, after every buffer.const ACC_BINDING: u32 = 19;@@ -503,11 +475,10 @@ pub struct EmitterFill {longest: u32,}-/// A scene's fills: of the emitters the CPU moves (after a commit that moved them), and of the particles' (after-/// their passes). None where the scene has no such emitters.+/// A scene's fill a frame: of the particles' emitters, after their passes. None where the scene has no such+/// emitters.#[derive(Default)]pub struct EmitterFills {- pub moved: Option<EmitterFill>,pub particles: Option<EmitterFill>,}@@ -848,7 +819,7 @@ fn skin_bind_group(d: &wgpu::Device, pipeline: &wgpu::ComputePipeline, own: [&wg/// what the CPU keeps between frames: where the next emission starts in its ring of slots, the rate's fraction carried.pub struct GpuParticlesGpu {pipeline: wgpu::ComputePipeline,- /// Timestamps around the dynamic BLAS rebuild (`STAMP_WGSL`, as `ParticleGpu`'s).+ /// Timestamps around the systems' BLAS rebuild (`STAMP_WGSL`, as `ParticleGpu`'s).stamp: (wgpu::ComputePipeline, wgpu::BindGroup),bg: wgpu::BindGroup,params: wgpu::Buffer,@@ -926,7 +897,7 @@ fn particle_source(scene: &Scene) -> String {format!("{RECORDS}{head}{functions}{tail}")}-/// Hardware acceleration structures: one BLAS per non-empty traversal group, one TLAS over them.+/// Hardware acceleration structures: a BLAS a mesh, one TLAS over their instances and the procedural objects'.pub struct Accel {pub tlas: wgpu::Tlas,/// What the BLASes are built from: the vertices (`Uploaded::vertices`: a record's first 12 bytes its position) and@@ -935,29 +906,18 @@ pub struct Accel {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.+ /// By mesh: its first vertex and how many (`indexed::Indexed::meshes`).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.meshes: Vec<wgpu::Blas>,/// Per mesh: its (first pool triangle, count) geometries and their sizes (`mesh_entries`).mesh_geo: Vec<(Vec<(u32, u32)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)>,- /// The first pool triangle in the GPU order.- pool_first: usize,- /// The TLAS index of model instance 0 (the traversal groups' instances come first).- pub inst_base: usize,/// The build's triangle BLAS bytes per triangle (Metal's sizes): edits' memory estimates (live/mod.rs `room_stats`).pub blas_per_tri: f64,- /// The TLAS index of the first procedural object's instance (after the model instances; each has its own AABB- /// BLAS, which its TLAS instance keeps).- pub proc_base: usize,}/// What is above the triangles for an edit in place: hardware traversal's TLAS and BLASes, or software traversal's-/// units (units.rs). An instance's slot is its TLAS index; its kernel record is the slot less `inst_base` (0 for-/// units: a unit's slot is its record).+/// units (units.rs). An instance's slot (its TLAS index, its unit's) is its kernel record.pub enum Top<'a> {Hw(&'a mut Accel),Sw(&'a mut crate::units::Units),@@ -973,13 +933,6 @@ impl<'a> Top<'a> {}}- pub fn inst_base(&self) -> usize {- match self {- Top::Hw(a) => a.inst_base,- Top::Sw(_) => 0,- }- }-pub fn sw(&self) -> bool {matches!(self, Top::Sw(_))}@@ -994,23 +947,23 @@ impl<'a> Top<'a> {/// An instance of instanced mesh `k` at `slot`, placed by `world`. (Its bounds are the mesh's BLAS's, or its/// tree's: units.rs `Unit`.)- pub fn place(&mut self, slot: usize, k: u32, world: glam::Mat4, custom: u32, cast_shadow: bool, hidden: bool) {+ pub fn place(&mut self, slot: usize, k: u32, world: glam::Mat4, cast_shadow: bool, hidden: bool) {match self {- Top::Hw(a) => a.tlas[slot] = Some(wgpu::TlasInstance::new(&a.meshes[k as usize], tlas_rows(world), custom, instance_mask(cast_shadow, hidden))),+ Top::Hw(a) => a.tlas[slot] = Some(wgpu::TlasInstance::new(&a.meshes[k as usize], tlas_rows(world), slot as u32, instance_mask(cast_shadow, hidden))),Top::Sw(u) => u.set(slot, u.unit(k, world, hidden)),}}/// A procedural object's instance at `slot` (its AABB BLAS). Hardware traversal only: software traversal finds/// procedural objects by their records (`trace_procs`), and its edits of them rebuild the scene.- pub fn place_blas(&mut self, slot: usize, blas: &wgpu::Blas, world: glam::Mat4, custom: u32, mask: u8) {+ pub fn place_blas(&mut self, slot: usize, blas: &wgpu::Blas, world: glam::Mat4, mask: u8) {if let Top::Hw(a) = self {- a.tlas[slot] = Some(wgpu::TlasInstance::new(blas, tlas_rows(world), custom, mask));+ a.tlas[slot] = Some(wgpu::TlasInstance::new(blas, tlas_rows(world), slot as u32, mask));}}/// Whether instanced mesh `k` can be placed: always under hardware traversal (its BLAS); under software traversal- /// if it has a tree (a mesh that deforms has none: its instances are flattened).+ /// if it has a tree (one without is no unit, and is not drawn).pub fn has_mesh(&self, k: u32) -> bool {match self {Top::Hw(_) => true,@@ -1838,7 +1791,7 @@ impl Kernel {Kernel { functions, hash: h.finish(), ..self.clone() }}- pub fn new(scene: &Scene, groups: [usize; GROUPS]) -> Kernel {+ pub fn new(scene: &Scene) -> Kernel {// (The translucency pass's functions: those of its particles' materials.)let used: std::collections::BTreeSet<i32> = scene.translucent_mats().iter().filter_map(|&m| scene.materials.get(m as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();let functions = Kernel::material_functions(&scene.shaders, &used);@@ -1869,7 +1822,7 @@ impl Kernel {functions.hash(&mut h);volume_functions.hash(&mut h);geometry_functions.hash(&mut h);- Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish(), approx: A_LIVE }+ Kernel { features: features(scene), functions, volume_functions, geometry_functions, hash: h.finish(), approx: A_LIVE }}}@@ -1894,11 +1847,8 @@ pub const F_FUNC: u32 = 512;// (1024: the emitter-reservoir experiment, removed 2026-11-13.)pub const F_GLASS: u32 = 2048;pub const F_COAT: u32 = 4096;-/// A traversal group starts beyond 2^24 triangles: hardware instances carry their group index instead of their first-/// triangle (24-bit custom data), and hits look the offset up in `Params::group_first` (~0.2 ms on Kabukicho, so only-/// when needed).-pub const F_HUGE: u32 = 8192;-/// Instanced glTF meshes (scene::Instance): TLAS instances with custom data INSTANCE_BIT | record index, shaded from+// (8192: free.)+/// The scene has instances (scene::Instance): TLAS instances with their record as custom data, shaded from/// model-space triangles through their `instances` record.pub const F_INST: u32 = 16384;/// Bounded participating media (`VolumeMesh`; pathtrace.wgsl `media_track`): compiled out where no scene has one.@@ -1956,30 +1906,15 @@ fn light_tiles_of(var: Option<&str>, android: bool) -> bool {pub const RIS_EXACT: usize = 8;/// The features that change the kernel's source (an `@if` flag) rather than switch code in it (`FEAT`).pub const F_SOURCE: u32 = F_UNITS;-/// Software traversal's units (units.rs; shaders/trace_units.wgsl): the second level's walk, spliced into the-/// software traversal after the still scene's (F_SOURCE). Never with hardware traversal.+/// Software traversal's units (units.rs; shaders/trace_units.wgsl): the walk of a scene's instances, spliced into+/// the software traversal (F_SOURCE). Never with hardware traversal.pub const F_UNITS: u32 = 1 << 26;/// The sky's aerial perspective (SkyAtmosphere `aerialPerspective`; pathtrace.wgsl `aerial_tr`) on every path segment-/// that ends on a surface: compiled out where no scene has it. (Bit 23 is left to INSTANCE_BIT below.)+/// that ends on a surface: compiled out where no scene has it.pub const F_AERIAL: u32 = 1 << 24;-/// Marks a model instance's custom data (bit 23); group instances then stay below it.-pub const INSTANCE_BIT: u32 = 1 << 23;--/// Whether some traversal group starts beyond what instance custom data holds (see F_HUGE): 24 bits, or 23 when-/// model instances take the top bit.-pub fn huge(groups: [usize; GROUPS], instanced: bool) -> bool {- let limit = if instanced { 1 << 23 } else { 1 << 24 };- let mut first = 0;- groups.iter().any(|&count| {- let past = count > 0 && first >= limit;- first += count;- past- })-}-/// Features a scene needs; `THREERT_FEATURES` (bit mask) restricts them for profiling.-pub fn features(scene: &Scene, groups: [usize; GROUPS]) -> u32 {- features_of(&scene.materials, scene.environment.features(), !scene.textures.is_empty(), !scene.shaders.is_empty(), groups, instance_features(scene))+pub fn features(scene: &Scene) -> u32 {+ features_of(&scene.materials, scene.environment.features(), !scene.textures.is_empty(), !scene.shaders.is_empty(), instance_features(scene))}impl Params {@@ -2031,13 +1966,8 @@ pub fn instance_features(scene: &Scene) -> u32 {/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the/// scene's structure (`instances`: `instance_features`).-pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures: bool, functions: bool, groups: [usize; GROUPS], instances: u32) -> u32 {- // `instances` carries the structural features (instance_features): instancing is its F_INST bit.- let instanced = instances & F_INST != 0;+pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures: bool, functions: bool, instances: u32) -> u32 {let mut f = instances | environment;- if groups[1] + groups[3] + groups[5] + groups[7] > 0 {- f |= F_MASKED;- }if textures {f |= F_TEX;}@@ -2053,12 +1983,8 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures:if ms.iter().any(|m| m.tex1[2] == crate::scene::MAT_UNLIT) {f |= F_UNLIT;}- if huge(groups, instanced) {- f |= F_HUGE;- }-if let Some(mask) = std::env::var("THREERT_FEATURES").ok().and_then(|v| v.parse::<u32>().ok()) {- f &= mask | F_HUGE | F_INST | F_PROC | F_TINT; // not optional: they say what the instances' custom data / the object table holds+ f &= mask | F_INST | F_PROC | F_TINT; // not optional: they say what the instances' records / the object table hold}// Features compiled in although the scene does not use them (the perf smoke's cost of a contract compiled in but off).if let Some(on) = std::env::var("THREERT_FEATURES_ON").ok().and_then(|v| v.parse::<u32>().ok()) {@@ -2591,11 +2517,10 @@ 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, 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, 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- // triangle without area; bvh.rs `EMPTY`.)+ // (A buffer is never empty: zeros where the scene has nothing for it.)let buf = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| {let data: &[u8] = if bytes.is_empty() { &[0u8; 512] } else { bytes };d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: data, usage })@@ -2615,7 +2540,7 @@ 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, scene.indexed.rows.len(), records.len(), self.hwrt, scene.units.is_some());+ let room = EditRoom::for_scene(scene, scene.indexed.indices.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;@@ -2637,7 +2562,7 @@ impl Gpu {// 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(), (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));+ timings.push(("tri_data_mb".into(), (ix.vertices.len() * crate::indexed::VERTEX_BYTES + ix.indices.len() * 12 + 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 };let grids = self.make_grids(&scene.grids, &scene.media, &scene.grid_programs);@@ -2677,57 +2602,16 @@ impl Gpu {mipmap_filter: wgpu::MipmapFilterMode::Linear,..Default::default()});- // Hardware acceleration structures, one BLAS per traversal group (see `Prepared::groups`): shadow casters have- // mask 1, the rest mask 2; alpha-cutout groups are non-opaque so the ray query reports candidates to test.+ // Hardware acceleration structures: a BLAS a mesh (model space, a geometry a section), a TLAS instance a+ // placement (its custom data its record; shadow casters mask 1, the rest mask 2), then the procedural objects'.+ // Every geometry is flagged opaque, a cutout's too: every query forces opacity (trace_hw.wgsl).let mut accel = None;if self.hwrt {let tb = Instant::now();- 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()- .enumerate()- .map(|(g, &count)| {- let r = (first, count, if g % 4 < 2 { 1u8 } else { 2u8 });- first += count;- r- })- .collect();- let pool_first = first;- let mut t = d.create_tlas(&wgpu::CreateTlasDescriptor { label: None, max_instances: (GROUPS + scene.instances.len() + scene.procs.len() + room.records) as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });- let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = groups- .iter()- .map(|&(_, count, _)| wgpu::BlasTriangleGeometrySizeDescriptor {- vertex_format: wgpu::VertexFormat::Float32x3,- // (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,- })- .collect();- let mut blases = vec![];- for (i, (first, count, mask)) in groups.iter().enumerate() {- if *count == 0 {- continue;- }- // Dynamic groups (4..8) are rebuilt whenever something in them moves: built fast rather than traced fast- // (the C slice's ~100 k moving triangles: rebuild 4.14 -> 3.1 ms a frame, trace unchanged).- let flags = if i >= 4 { wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD } else { wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE };- let blas = d.create_blas(- &wgpu::CreateBlasDescriptor { label: None, flags, update_mode: wgpu::AccelerationStructureUpdateMode::Build },- wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: vec![sizes[i].clone()] },- );- // Custom data = the first triangle, or past 2^24 (F_HUGE) the group: `Params::group_first` has its first.- let custom = if huge_scene { i as u32 } else { *first as u32 };- t[blases.len()] = 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], custom, *mask));- blases.push((blas, i, *first, sizes[i].clone()));- }- // Instanced meshes: one opaque model-space BLAS each, a TLAS instance per placement (custom data- // INSTANCE_BIT | record; shadow casters mask 1).+ // (Room for one at least: a scene of the sky alone.)+ let mut t = d.create_tlas(&wgpu::CreateTlasDescriptor { label: None, max_instances: (scene.instances.len() + scene.procs.len() + room.records).max(1) as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });// Per mesh: its geometries, one a section (`InstMesh::parts`): first triangle, count.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();// (A translucent particle system's is not flagged opaque: the translucency pass asks for every hit.)@@ -2749,8 +2633,7 @@ impl Gpu {.collect()}).collect();- // Deforming meshes (posed skinned models') are rebuilt every new pose: built fast rather than traced fast, as the dynamic- // groups are.+ // Deforming meshes (posed skinned models') are rebuilt every new pose: built fast rather than traced fast.let meshes: Vec<wgpu::Blas> = mesh_sizes.iter().zip(&scene.meshes)@@ -2761,27 +2644,25 @@ impl Gpu {.collect();// 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, u32, u32)>> = group_parts.chain(mesh_vertex_parts).collect();+ let parts: Vec<Vec<(u32, u32, u32, u32)>> = mesh_parts.iter().zip(&ix.meshes).map(|(ps, &(vfirst, vcount))| ps.iter().map(|&(first, count)| (vfirst, vcount.max(1), first, count)).collect()).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();+ anyhow::ensure!(scene.instances.len() + scene.procs.len() <= 1 << 24, "too many instances for 24-bit custom data");for (k, inst) in scene.instances.iter().enumerate() {let w = inst.world;let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];let [r0, r1, r2] = [row(0), row(1), row(2)];let xf = [r0[0], r0[1], r0[2], r0[3], r1[0], r1[1], r1[2], r1[3], r2[0], r2[1], r2[2], r2[3]];- t[base + k] = Some(wgpu::TlasInstance::new(&meshes[inst.mesh as usize], xf, INSTANCE_BIT | k as u32, instance_mask(inst.cast_shadow, inst.hidden)));+ t[k] = Some(wgpu::TlasInstance::new(&meshes[inst.mesh as usize], xf, k as u32, instance_mask(inst.cast_shadow, inst.hidden)));}// Procedural geometry: one AABB BLAS per distinct geometry (object space; kept across uploads by the// geometry's hash, so a rebuild builds only new ones), and per mesh a TLAS instance of it after the model// instances, whose custom data is the mesh's record; its hits are told apart by their kind.- let proc_base = base + scene.instances.len();+ let proc_base = scene.instances.len();let mut built = self.proc_blases.lock().unwrap();let mut kept: std::collections::HashMap<[u8; 32], (wgpu::Blas, u64)> = Default::default();let mut proc_new: Vec<(usize, wgpu::Buffer, wgpu::BlasAABBGeometrySizeDescriptor)> = vec![];@@ -2809,26 +2690,15 @@ impl Gpu {drop(built);for (j, p) in scene.procs.iter().enumerate() {let record = (scene.gpu_instances.len() + j) as u32;- anyhow::ensure!(record < INSTANCE_BIT, "too many instances for 23-bit custom data");let k = scene.proc_layout.as_ref().map_or(j, |l| l.blob_of[j]);t[proc_base + j] = Some(wgpu::TlasInstance::new(&geo_blas[k], tlas_rows(p.world), record, instance_mask(p.cast_shadow, p.hidden)));}- let entries: Vec<wgpu::BlasBuildEntry> = blases+ let entries: Vec<wgpu::BlasBuildEntry> = meshes.iter()- .map(|(blas, _, first, size)| wgpu::BlasBuildEntry {- blas,- geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {- size,- 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).zip(&ix.meshes).map(|(((blas, sizes), parts), &(first_vertex, _))| wgpu::BlasBuildEntry {+ .zip(&mesh_sizes)+ .zip(&mesh_parts)+ .zip(&ix.meshes)+ .map(|(((blas, sizes), parts), &(first_vertex, _))| wgpu::BlasBuildEntry {blas,geometry: wgpu::BlasGeometries::TriangleGeometries(sizes@@ -2840,13 +2710,13 @@ impl Gpu {first_vertex,vertex_stride: VERTEX_STRIDE,index_buffer: Some(&words.buffer),- first_index: Some(index_first + ((pool_first + first as usize) * 3) as u32),+ first_index: Some(index_first + first * 3),transform_buffer: None,transform_buffer_offset: None,}).collect(),),- }))+ }).chain(proc_new.iter().map(|(k, boxes, size)| wgpu::BlasBuildEntry {blas: &geo_blas[*k],geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size, stride: 24, aabb_buffer: boxes, primitive_offset: 0 }]),@@ -2884,7 +2754,7 @@ impl Gpu {}drop(entries);let mesh_geo = mesh_parts.into_iter().zip(mesh_sizes).collect();- 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 });+ accel = Some(Accel { tlas: t, vertices: b_vertices.clone(), indices: words.buffer.clone(), index_first, mesh_verts: ix.meshes.clone(), meshes, mesh_geo, 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<'_> {@@ -2892,7 +2762,7 @@ impl Gpu {}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() });- let kernel = Kernel { approx: self.approx, ..Kernel::new(scene, groups) };+ let kernel = Kernel { approx: self.approx, ..Kernel::new(scene) };// Translucent particles (hardware RT): the translucency pass's own TLAS, built again after the particle pass:// an instance of it a system's mesh, the instance's record in its custom data as in the scene's TLAS.let layered: Vec<(u32, u32)> = scene.particles.iter().filter(|p| p.translucent).filter_map(|p| scene.instances.iter().position(|i| i.mesh == p.mesh).map(|r| (p.mesh, r as u32))).collect();@@ -2900,7 +2770,7 @@ impl Gpu {Some(a) if !layered.is_empty() => {let mut tlas = d.create_tlas(&wgpu::CreateTlasDescriptor { label: Some("translucent"), max_instances: layered.len() as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });for (k, &(mesh, record)) in layered.iter().enumerate() {- tlas[k] = Some(wgpu::TlasInstance::new(&a.meshes[mesh as usize], [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], INSTANCE_BIT | record, 0xff));+ tlas[k] = Some(wgpu::TlasInstance::new(&a.meshes[mesh as usize], [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], record, 0xff));}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 });@@ -2917,7 +2787,7 @@ impl Gpu {};// (The particle passes' pipeline constant: vec4s an object entry, 4 with instance colours.)let object_stride = [("OBJECT_STRIDE", scene.object_stride() as f64)];- // Particle systems (hardware RT: the pass writes the dynamic BLASes' input).+ // Particle systems (hardware RT: the pass writes their BLASes' input).let particles = match &accel {Some(a) if !scene.particles.is_empty() => {let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("particles"), source: wgpu::ShaderSource::Wgsl(particle_source(scene).into()) });@@ -3004,7 +2874,7 @@ 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_vertices, &heap, &words), particles: self.emitter_fill(&emitter_runs.particles, &b_vertices, &heap, &words) },+ Some(_) => EmitterFills { particles: self.emitter_fill(&emitter_runs.particles, &b_vertices, &heap, &words) },None => EmitterFills::default(),};Ok(Uploaded { bg, bg_parts, heap, 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 })@@ -3076,12 +2946,10 @@ 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 };- // 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).+ // The triangles' indices.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 index_bytes = (ix.indices.len() + room_tris) * 12;+ 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];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));@@ -3106,7 +2974,6 @@ impl Gpu {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()]);@@ -3117,7 +2984,6 @@ impl Gpu {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 {@@ -3143,7 +3009,7 @@ impl Gpu {Ok((heap, head + blob_words, room))}- /// The particle pass (scene time, camera, frame time, rain, wetness), then the dynamic BLASes and the TLAS rebuilt.+ /// The particle pass (scene time, camera, frame time, rain, wetness), then the systems' BLASes and the TLAS rebuilt./// `pass_ts`: timestamps (q, q + 1) around the particle pass; `blas_ts`: (q, q + 1) around the BLAS build (the end of/// an empty pass before it, the beginning of one after it).#[allow(clippy::too_many_arguments)]@@ -3241,7 +3107,7 @@ impl Gpu {/// One frame of the stateful GPU particles (gpu_particles.wgsl): each system's emissions (its rate over `dt`, and the/// game's spawns, `spawns` per node, 8 floats each), the update, collision and retirement of the rest, their quads;- /// with `rebuild`, the dynamic BLASes after (else the stateless pass that follows rebuilds them).+ /// with `rebuild`, the systems' BLASes after (else the stateless pass that follows rebuilds them).#[allow(clippy::too_many_arguments)]pub fn run_gpu_particles(&self, up: &Uploaded, cam: [f32; 3], fwd: [f32; 3], time: f32, dt: f32, spawns: &std::collections::BTreeMap<u32, Vec<f32>>, rebuild: bool, e: &mut wgpu::CommandEncoder, ts: Option<(&wgpu::QuerySet, u32)>, blas_ts: Option<(&wgpu::QuerySet, u32)>) {let (Some(p), Some(accel)) = (&up.gpu_particles, &up.accel) else { return };@@ -3721,8 +3587,6 @@ impl Gpu {}}- /// Rebuilds the BLASes of the dynamic groups (posed models, after their vertices changed) and the TLAS.- /// Rebuilds the TLAS alone (instance transforms changed, no triangles)./// `old`'s contents in a new buffer of `size` bytes (its usage and label), copied on the GPU and submitted now, so/// writes queued after this land on the copy (live/edits.rs `edit_geometry` growing past its room).pub fn grown(&self, old: &wgpu::Buffer, size: u64, label: &str) -> wgpu::Buffer {@@ -3744,18 +3608,16 @@ impl Gpu {accel.tlas = t;}- /// The BLAS vertex buffer grown to `bytes` (`grown`)./// 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);+ let (blas, geo) = self.mesh_blas_for(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>)) {- let rel = (first - accel.pool_first) as u32;- let parts: Vec<(u32, u32)> = mesh.parts(sections).into_iter().map(|(at, count)| (rel + at, count)).collect();+ fn mesh_blas_for(&self, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> (wgpu::Blas, (Vec<(u32, u32)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {+ let parts: Vec<(u32, u32)> = mesh.parts(sections).into_iter().map(|(at, count)| (first as u32 + at, count)).collect();let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = parts.iter().map(|&(_, c)| wgpu::BlasTriangleGeometrySizeDescriptor {@@ -3775,7 +3637,7 @@ impl Gpu {pub fn add_mesh(&self, accel: &mut Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> u32 {// Built fast rather than traced fast (edits come every frame under destruction; the batches of pieces are rebuilt// every frame): `mesh_blas_for`.- let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);+ let (blas, geo) = self.mesh_blas_for(first, mesh, sections);accel.meshes.push(blas);accel.mesh_geo.push(geo);accel.mesh_verts.push((mesh.vfirst, mesh.vcount));@@ -3839,7 +3701,7 @@ impl Gpu {/// The bind groups that hold the scene's buffers again, from `up`'s as they are now (one that grew: the tables,/// 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() {+ if let Some(f) = &mut up.fills.particles {f.bg = self.emitter_fill_bind_group(&f.runs, &up.vertices, &up.heap, &up.words);}if let Some(k) = &mut up.skin {@@ -3898,8 +3760,7 @@ impl Gpu {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 jobs: Vec<LeafJob> = scene.retained.skinned.iter().map(|g| { let m = &scene.meshes[g.mesh as usize]; LeafJob { 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 };@@ -4009,9 +3870,6 @@ impl Gpu {meshes.dedup();let mut entries = mesh_entries(accel, &meshes);entries.extend(b.procs.iter().map(|p| wgpu::BlasBuildEntry { blas: &p.blas, geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size: &p.size, stride: 24, aabb_buffer: &p.boxes, primitive_offset: 0 }]) }));- if b.dynamic {- entries.extend(dynamic_entries(accel));- }let mut e = self.device.create_command_encoder(&Default::default());e.build_acceleration_structures(entries.iter(), [&accel.tlas]);self.queue.submit([e.finish()]);@@ -4076,10 +3934,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, 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, 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), groups, nodes, emitters, emitter_tris, emitter_runs, light_tree, env, env_cdf, energy, timings)?;+ let up = self.upload(scene, &self.accum_buffer(w, h), 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() {@@ -4244,7 +4102,7 @@ mod tests {fn feature_bits_are_distinct() {let all = [("F_MASKED", F_MASKED), ("F_FOG", F_FOG), ("F_VOLUME", F_VOLUME), ("F_TEX", F_TEX), ("F_FUNC", F_FUNC),- ("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),+ ("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),("F_DEFORM", F_DEFORM), ("F_PART", F_PART),@@ -4515,9 +4373,9 @@ mod tests {assert!(guard_room(false) && !guard_room(true));}- /// Software traversal's units are in a kernel only when the scene has them (F_UNITS, `units`): without, the still- /// walk keeps its stack and there is no unit walk; with, the still walk hands its hit to `trace_units` and its stack- /// is the module's (the procedural objects' walk keeps its own). Hardware traversal has neither software walk.+ /// Software traversal's units are in a kernel only when the scene has them (F_UNITS, `units`): without, there is+ /// no unit walk; with, `trace` calls `trace_units`, whose stack is the module's (the procedural objects' walk+ /// keeps its own). Hardware traversal has neither software walk.#[test]fn units_are_software_traversals_only() {let t = kernel_template();@@ -4525,9 +4383,9 @@ mod tests {let u = kernel_wgsl(&t, &KernelVariant::new(false, KernelSwitches::default(), F_UNITS));let hw = kernel_wgsl(&t, &KernelVariant::new(true, KernelSwitches::default(), 0));assert!(!sw.contains("trace_units") && !hw.contains("trace_units") && !hw.contains("fn trace_procs("));- assert_eq!((u.matches("fn trace_units(").count(), u.matches("trace_units(o, d, inv_d, hit, mode)").count()), (1, 1));+ assert_eq!((u.matches("fn trace_units(").count(), u.matches("hit = trace_units(").count()), (1, 1));let stacks = |s: &str| (s.matches("var<private> stack: array<u32, 64>").count(), s.matches("var stack: array<u32, 48>").count());- assert_eq!((stacks(&sw), stacks(&u)), ((0, 2), (1, 1)));+ assert_eq!((stacks(&sw), stacks(&u)), ((0, 1), (1, 1)));}/// With nothing set, every platform but Android opens the device as it was before the options existed: no@@ -4702,34 +4560,4 @@ mod tests {assert_eq!(m.global_expressions[k.init], naga::Expression::Literal(naga::Literal::U32(stride as u32)));}}-- /// Structural features other than F_INST (opaque particles, media) do not make a scene count as instanced: a group- /// starting between 2^23 and 2^24 stays within the non-instanced custom-data limit (no F_HUGE).- #[test]- fn structural_features_are_not_instancing() {- const M: usize = 1 << 23;- let groups = [M + 5, 3, 0, 0, 0, 0, 0, 0];- assert_eq!(features_of(&[], 0, false, false, groups, F_PEMIT) & F_HUGE, 0);- assert_eq!(features_of(&[], 0, false, false, groups, F_MEDIA) & F_HUGE, 0);- assert_ne!(features_of(&[], 0, false, false, groups, F_INST) & F_HUGE, 0);- }-- #[test]- fn huge_when_a_group_starts_past_24_bits() {- const M: usize = 1 << 24;- // One group of any size: its first triangle is 0.- assert!(!huge([M * 3, 0, 0, 0, 0, 0, 0, 0], false));- // The second group starts at 2^24 - 1: still fits.- assert!(!huge([M - 1, 5, 0, 0, 0, 0, 0, 0], false));- // ... at 2^24: does not.- assert!(huge([M, 5, 0, 0, 0, 0, 0, 0], false));- // Empty groups past 2^24 have no instance.- assert!(!huge([M + 7, 0, 0, 0, 0, 0, 0, 0], false));- // A 3 x 3 street district of 37.75 M triangles (opaque shadow casters first).- assert!(huge([36_000_000, 900_000, 500_000, 352_799, 0, 0, 0, 0], false));- // With model instances, group custom data must stay below the instance bit (2^23).- assert!(!huge([M - 1, 5, 0, 0, 0, 0, 0, 0], false));- assert!(huge([M / 2, 5, 0, 0, 0, 0, 0, 0], true));- assert!(!huge([M / 2 - 1, 5, 0, 0, 0, 0, 0, 0], true));- }}diff --git a/renderer/src/heap.rs b/renderer/src/heap.rsindex 242202c..ab3a0cd 100644--- a/renderer/src/heap.rs+++ b/renderer/src/heap.rs@@ -77,12 +77,10 @@ pub enum Stream {/// 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 = 6;+ const COUNT: usize = 5;const UNIT: u64 = 4;const LABEL: &'static str = "words";fn index(self) -> usize {diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rsindex af2e72f..75c8c9d 100644--- a/renderer/src/indexed.rs+++ b/renderer/src/indexed.rs@@ -1,8 +1,6 @@-//! 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, what the CPU writes-//! whole each frame (the dynamic world-space triangles) has three vertices a triangle, and a particle system's-//! mesh four a quad.+//! The scene's geometry as the GPU holds it: vertices kept once, a triangle three indices. The build makes triangles+//! with corners of their own (`Scene::pool_tris`, `attrs`); what they share is found here, mesh by mesh: a mesh's+//! triangles share within the mesh, and a particle system's mesh has four vertices a quad.use crate::scene::GpuTriAttr;use glam::Vec3A;@@ -14,16 +12,10 @@ use std::hash::Hash;pub type Vertex = [[f32; 4]; 3];pub const VERTEX_BYTES: usize = std::mem::size_of::<Vertex>();-/// The row of a triangle no instance places (software traversal's, of an instance that is no unit): 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).+/// its section of its mesh, 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>();@@ -154,22 +146,6 @@ pub fn source_vertices(source: &[[crate::skin::SkinCorner; 3]], scope: &Scope) -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() {- // (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, tangent) = 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-}-/// A particle system's quads (two triangles each, the second the first's first and third corners and its own/// third) as four vertices a quad, in the order the particle pass writes them.pub fn quads(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {@@ -185,50 +161,25 @@ pub fn quads(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {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 finite = t.iter().flatten().all(|x| x.is_finite());- for (c, p) in t.iter().enumerate() {- let (n, uv, tangent) = 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.+ /// A triangle's three vertices, counted from its mesh's first vertex.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.- pub pool_first: 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,/// 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.+ /// The vertices that move (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' (a mesh's triangles have none).- pub fn gpu_rows(&self) -> &[TriRow] {- &self.rows[..(self.pool_first as usize).min(self.rows.len())]- }-/// 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 {@@ -293,8 +244,7 @@ mod tests {}/// Triangles that the build made from a sheet of (n + 1)^2 vertices come back as that many, with tangents or- /// without; and each triangle read through its indices is the build's. Written whole, they have three vertices- /// each.+ /// without; and each triangle read through its indices is the build's.#[test]fn a_scopes_triangles_share_their_vertices() {for own in [false, true] {@@ -302,9 +252,6 @@ mod tests {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);}}@@ -356,24 +303,21 @@ mod tests {}/// 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.+ /// built from these positions); 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 s = shared(&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()));}}diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 2e492ae..34cbce6 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -59,16 +59,10 @@ pub fn default_presets_dir() -> PathBuf {}-/// Traversal groups (see `group_of`).-pub const GROUPS: usize = 8;-/// Everything the GPU kernels need for a loaded scene: triangle layout for the active traversal backend, emitter CDF,/// baked sky + its sampling CDF, and the base kernel parameters (camera from the scene).pub struct Prepared {pub tri_verts: Vec<[f32; 4]>,- /// Triangle counts of the traversal groups, in order: shadow-casting opaque, shadow-casting cutout,- /// non-shadowing opaque, non-shadowing cutout; then the same four for dynamic triangles (posed models).- pub groups: [usize; GROUPS],pub nodes: Vec<bvh::GpuNode>,/// The emitter CDF (`emitter_cdf`): one entry per `emitter_tris`, then the guide table.pub emitters: Vec<[f32; 4]>,@@ -84,38 +78,13 @@ pub struct Prepared {pub emitter_tris: Vec<EmitterTri>,/// The light tree over the static emitters (`ltree`).pub light_tree: Option<ltree::LightTree>,- /// Material -> runs of its flattened static triangles (first, end in the traversal order, object): a material- /// that starts emitting gets emitter entries in place from its runs (live/edits.rs `add_material_emitters`).- /// `moving_mats`: the materials of dynamic world-space triangles and of particle systems (`Tables::moving_mats`).- pub mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,+ /// The particle systems' materials (`Tables::moving_mats`).pub moving_mats: std::collections::HashSet<u32>,- /// The flattened triangles' build indices in traversal order (`Scene::tris` order: positions for new entries).- pub tri_order: Vec<u32>,/// The brightest sky texel (luminance) from which the environment is light-sampled (`Params::counts2[1]`): 0 when/// there are no emitters. A dynamic sky re-decides with each bake (live/load.rs `DynamicSky`).pub env_nee_floor: f32,}-/// The emitter entry of triangle `k` (traversal order) with attributes `a`, or None if it does not emit. Particle-/// triangles are collapsed until the particle pass places them: their nominal area (attrs x.z).-pub fn emitter_tri(k: usize, tri_verts: &[[f32; 4]], a: &scene::GpuTriAttr, materials: &[scene::GpuMaterial]) -> Option<EmitterTri> {- let mat = a.uv[3].to_bits();- let m = materials.get(mat as usize)?;- let lum = 0.2126 * m.emissive[0] + 0.7152 * m.emissive[1] + 0.0722 * m.emissive[2];- if !(lum > 0.0) {- return None;- }- let v = |j: usize| Vec3::new(tri_verts[k * 3 + j][0], tri_verts[k * 3 + j][1], tri_verts[k * 3 + j][2]);- let (e1, e2) = (v(1), v(2));- let area = 0.5 * e1.cross(e2).length();- if !(area * lum > 0.0) {- return None;- }- 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: false, in_tree: false, inst: NO_INST, part: 0, card: is_card(m) })-}-/// An emissive triangle of the emitter CDF: triangle (traversal order), material, object, area.#[derive(Clone, Copy, Debug)]pub struct EmitterTri {@@ -125,7 +94,7 @@ pub struct EmitterTri {pub area: f32,/// Centroid (light LOD: distance to the reference camera position).pub c: [f32; 3],- /// On a moving object (TRI_DYNAMIC): no light LOD, its centroid would go stale (the kernel skips it too).+ /// On a moving object: no light LOD, its centroid would go stale (the kernel skips it too).pub moves: bool,/// A particle's: `area` is the nominal one (Particles emitterArea), what the CDF weighs it by; its pass places/// its triangle, of whatever size.@@ -227,12 +196,11 @@ pub fn placed_emitter(inst: &scene::Instance, t: &[glam::Vec3A; 3], mat: u32, ma(area, ((w[0] + w[1] + w[2]) / 3.0).to_array(), w)}-/// Runs of the light list (first emitter, count) whose triangles something moves after the load; the GPU takes them-/// again from where the triangles are (gpu.rs `EmitterFill`): the emitters of the triangles the CPU reposes, and the-/// particles', which their passes place. (An instance that moves has its run filled when it does: live/edits.rs.)+/// Runs of the light list (first emitter, count) whose triangles something moves every frame; the GPU takes them+/// again from where the triangles are (gpu.rs `EmitterFill`): the particles', which their passes place. (An instance+/// that moves has its run filled when it does: live/edits.rs.)#[derive(Default)]pub struct EmitterRuns {- pub moved: Vec<[u32; 2]>,pub particles: Vec<[u32; 2]>,}@@ -248,7 +216,7 @@ impl EmitterRuns {}out};- EmitterRuns { moved: runs(&|e| e.moves && !e.nominal && e.inst == NO_INST), particles: runs(&|e| e.nominal) }+ EmitterRuns { particles: runs(&|e| e.nominal) }}}@@ -552,77 +520,37 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,if !hwrt {sc.procs.retain(|p| !p.blob.boxes.is_empty());}- // Hardware RT only needs triangles grouped by shadow casting; software traversal needs our BVH.- let bvh = if hwrt {- let mut order: Vec<u32> = (0..sc.tris.len() as u32).collect();- order.sort_by_key(|&i| group_of(sc.tri_flags[i as usize]));- bvh::Bvh { nodes: vec![bvh::GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [0.0; 3], count: 0 }], order, depth: 0 }- } else {- let b = bvh::build(&sc.tris);- timings.push(("bvh_depth".into(), b.depth as f64));- b- };- let mut groups = [0usize; GROUPS];- for f in &sc.tri_flags {- groups[group_of(*f)] += 1;- }- let mut tri_verts: Vec<[f32; 4]> = Vec::with_capacity(sc.tris.len() * 3);- let mut attrs = Vec::with_capacity(sc.attrs.len());- for &i in &bvh.order {- let [a, b, c] = sc.tris[i as usize];- let (e1, e2): (Vec3A, Vec3A) = (b - a, c - a);- tri_verts.push([a.x, a.y, a.z, f32::from_bits(sc.tri_flags[i as usize])]);- tri_verts.push([e1.x, e1.y, e1.z, 0.0]);- tri_verts.push([e2.x, e2.y, e2.z, 0.0]);- attrs.push(sc.attrs[i as usize]);- }- // Instanced meshes (hardware RT): the model-space pool after every traversal group, one BLAS per mesh.- let pool_first = tri_verts.len() / 3;- // Deforming meshes come first (scene build): flagged dynamic, their previous vertices kept for motion vectors.- let deforming = scene::deforming_pool(&sc.meshes);- for (k, (t, a)) in sc.pool_tris.iter().zip(&sc.pool_attrs).enumerate() {+ // The meshes' triangles, in model space, one mesh after another (`Scene::pool_tris`), a BLAS or a tree a mesh.+ let mut tri_verts: Vec<[f32; 4]> = Vec::with_capacity(sc.pool_tris.len() * 3);+ let mut attrs = Vec::with_capacity(sc.pool_attrs.len());+ for (t, a) in sc.pool_tris.iter().zip(&sc.pool_attrs) {let [a0, b, c] = *t;let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);- // (No class on a mesh's triangle: its instances' rows say which sections are cutouts or glass.)- tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(if k < deforming { scene::TRI_DYNAMIC } else { 0 })]);+ tri_verts.push([a0.x, a0.y, a0.z, 0.0]);tri_verts.push([e1.x, e1.y, e1.z, 0.0]);tri_verts.push([e2.x, e2.y, e2.z, 0.0]);attrs.push(*a);}- // (A deforming mesh's previous vertices lie as its triangles do, counted from the first dynamic triangle: what- // gpu.rs `prev_verts` holds at the build. Its instance's record says where.)- sc.gpu_instances = sc.instances.iter().map(|i| i.gpu(pool_first as u32 + sc.meshes[i.mesh as usize].first)).collect();+ // (A deforming mesh's previous vertices lie as its vertices do, counted from the first that moves: what gpu.rs+ // `prev_verts` holds at the build. Its instance's record says where.)+ sc.gpu_instances = sc.instances.iter().map(|i| i.gpu(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).for i in &sc.instances {let m = sc.meshes[i.mesh as usize];for (s, row) in m.sections(&sc.sections).iter().zip(&mut sc.rows[i.rows as usize..]) {- row[1] = pool_first as u32 + m.first + s.first;+ row[1] = m.first + s.first;}}- // A scene whose triangles are all units': the still tree is then the leaf of one triangle, triangle 0 (bvh.rs- // `EMPTY`), which no ray meets while triangle 0 is the zeros of an empty buffer. Here triangle 0 is the pool's- // first, a mesh's in its model space, and the still walk would meet it standing in the world. The leaf gets a- // triangle of its own after the pool, without area.- let no_still = trees.is_some() && pool_first == 0;- let nothing = tri_verts.len() / 3;- if no_still {- tri_verts.extend([[0.0; 4]; 3]);- attrs.push(bytemuck::Zeroable::zeroed());- }- // The units: the mesh trees after the still tree's nodes, room for the trees and units edits add (the edit room's- // triangles and records, gpu.rs `EditRoom`), the top tree; each unit's record gets its tree's root.- let mut nodes = bvh.nodes;- if no_still {- nodes[0].left_or_first = nothing as u32;- }+ // The units: the mesh trees, room for the trees and units edits add (the edit room's triangles and records,+ // gpu.rs `EditRoom`), the top tree; each unit's record gets its tree's root.+ let mut nodes = vec![];sc.units = None;if let Some(trees) = trees {let room = gpu::EditRoom::for_scene(sc, tri_verts.len() / 3, sc.instances.len() + sc.procs.len(), false, true);let used: usize = trees.iter().flatten().map(|t| t.nodes.len()).sum();- let mut u = units::Units { layout: units::Layout::new(nodes.len(), used + room.tris, sc.instances.len() + room.records), trees: vec![None; trees.len()], slots: vec![None; sc.instances.len()], count: 0, records: sc.instances.len() + sc.procs.len() + room.records, kept: Default::default() };- let still = nodes.len();- nodes.resize(still + u.layout.nodes(), units::FILL);+ let mut u = units::Units { layout: units::Layout::new(used + room.tris, sc.instances.len() + room.records), trees: vec![None; trees.len()], slots: vec![None; sc.instances.len()], count: 0, records: sc.instances.len() + sc.procs.len() + room.records, kept: Default::default() };+ nodes.resize(u.layout.nodes(), units::FILL);for (k, t) in trees.iter().enumerate() {if let Some(t) = t {let root = u.add_tree(k as u32, t).expect("the mesh range holds the build's trees") as usize;@@ -647,39 +575,16 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,sc.proc_records = sc.procs.iter().zip(&layout.headers).map(|(p, &h)| p.gpu(h)).collect();sc.proc_layout = (!sc.procs.is_empty()).then_some(layout);sc.attrs = attrs;- // Vertex colours (scene.rs `tri_colors`), with the triangles: the flattened ones in traversal order, the pool.- sc.gpu_vcolors = if sc.vcolors.is_empty() && sc.pool_vcolors.is_empty() {- vec![]- } else {- let at = |v: &[[u32; 3]], k: usize| v.get(k).copied().unwrap_or(scene::WHITE);- let mut v: Vec<u32> = Vec::with_capacity(sc.attrs.len() * 3);- v.extend(bvh.order.iter().flat_map(|&i| at(&sc.vcolors, i as usize)));- v.extend((0..sc.pool_tris.len()).flat_map(|k| at(&sc.pool_vcolors, k)));- v.resize(sc.attrs.len() * 3, u32::MAX);- v- };- // Posed models: where each of their triangles landed (they are re-skinned in place, hardware RT only).- if hwrt && sc.retained.dynamics_mut().next().is_some() {- let first_dynamic: usize = groups[..4].iter().sum();- let finals: std::collections::HashMap<u32, u32> = bvh.order[first_dynamic..].iter().enumerate().map(|(k, &i)| (i, (first_dynamic + k) as u32)).collect();- for d in sc.retained.dynamics_mut() {- d.finals = (0..d.mats.len() as u32).map(|j| finals[&(d.first + j)]).collect();- }- }+ // Vertex colours (scene.rs `tri_colors`), with the triangles.+ sc.gpu_vcolors = if sc.pool_vcolors.is_empty() { vec![] } else { (0..sc.pool_tris.len()).flat_map(|k| sc.pool_vcolors.get(k).copied().unwrap_or(scene::WHITE)).collect() };timings.push(("bvh_ms".into(), t.elapsed().as_secs_f64() * 1000.0));- // The light list (an emitter's weight = area x luminance of the emissive factor x object power): the flattened- // triangles that emit, then, an instance at a time, those of its triangles that emit: a run of the list an- // instance, its first in its record, its triangles' numbers counted from it (a model's mesh), or from where its- // section's start, which the section's row has (a mesh with sections). Each with its triangle in world space.+ // The light list (an emitter's weight = area x luminance of the emissive factor x object power): an instance at a+ // time, those of its triangles that emit: a run of the list an instance, its first in its record, its triangles'+ // numbers counted from it (a model's mesh), or from where its section's start, which the section's row has (a+ // mesh with sections). Each with its triangle in world space.let mut emitter_tris: Vec<EmitterTri> = vec![];let mut gpu_emitter_tris: Vec<GpuEmitterTri> = vec![];- for k in 0..pool_first {- if let Some(e) = emitter_tri(k, &tri_verts, &sc.attrs[k], &sc.materials) {- gpu_emitter_tris.push(GpuEmitterTri::new(&e, &tri_verts[k * 3..][..3], 0));- emitter_tris.push(e);- }- }// (And the instances hidden at the build, `Instance::masked`: where they stand when they are shown is theirs to// bound then, in the light tree's moving subtree.)let moving = sc.retained.moving_records();@@ -703,38 +608,22 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,sc.rows[at + k][2] = start.map_or(scene::NO_EMITTER, |s| first + s);}let (a, b) = (m.first as usize, (m.first + m.count) as usize);- let attrs = &sc.attrs[pool_first + a..pool_first + b];+ let attrs = &sc.attrs[a..b];let numbered = |k: usize| scene::section_slot(&attrs[k], &rows, &starts);- for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, count as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked || area.is_some(), area) {+ for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], a as u32, &numbered, count as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked || area.is_some(), area) {gpu_emitter_tris.push(GpuEmitterTri::of(&e, w, 0));emitter_tris.push(e);}}- // Where each material's flattened static triangles are (runs of the traversal order, with their object), for a- // material that starts emitting in the live view (tables.rs `apply`): its emitter entries are made from them in- // place, as each instance with a row of it gets its own (live/edits.rs `add_material_emitters`). Not the- // materials of dynamic world-space triangles: `moving_mats`. (A mesh that deforms is a model's, whose materials- // are the file's: no edit names them.)- let mut mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>> = std::collections::HashMap::new();- let mut moving_mats: std::collections::HashSet<u32> = Default::default();- for (k, a) in sc.attrs[..pool_first].iter().enumerate() {- let (mat, obj) = (a.uv[3].to_bits(), a.x[1].to_bits());- if tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0 {- moving_mats.insert(mat);- continue;- }- let runs = mat_runs.entry(mat).or_default();- match runs.last_mut() {- Some(r) if r[1] == k as u32 && r[2] == obj => r[1] += 1,- _ => runs.push([k as u32, k as u32 + 1, obj]),- }- }- // (Nor a particle system's material: its triangles are its pass's.)+ // A material that starts emitting in the live view (tables.rs `apply`) gets emitter entries in place, each+ // instance with a row of it its own (live/edits.rs `add_material_emitters`). Not a particle system's material,+ // whose triangles are its pass's: `moving_mats`. (A mesh that deforms is a model's, whose materials are the+ // file's: no edit names them.)// (Not a translucent system's, which has no emitter and no class: its material's function changes in place.)+ let mut moving_mats: std::collections::HashSet<u32> = Default::default();for i in sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0 && !i.hidden) {moving_mats.insert(scene::row_material(&sc.rows[i.rows as usize]));}- let tri_order = bvh.order[..pool_first.min(bvh.order.len())].to_vec();// Many static emitters: a light tree samples them by importance at the shading point (`ltree`); each one's path// code with its triangle in the list (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).// (Switched-off objects at full power: `switchable_power`.)@@ -758,11 +647,6 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,for (g, code) in gpu_emitter_tris.iter_mut().zip(emitter_codes(&emitter_tris, &order, light_tree.as_ref())) {g.code = code;}- // A triangle in world space names its emitter in its attributes (x.w = the entry + 1), for the rays that hit it- // (emit_mis); a mesh's triangle is numbered among its mesh's, and its instance has the first.- for (i, e) in emitter_tris.iter().enumerate().filter(|(_, e)| e.inst == NO_INST) {- sc.attrs[e.tri as usize].x[3] = f32::from_bits(i as u32 + 1);- }let emitter_runs = EmitterRuns::of(&emitter_tris);let (emitters, total, _) = emitter_cdf(&emitter_tris, &order, &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());// The moving emitters (after the tree's in the CDF) are picked with the probability of their share of power.@@ -826,7 +710,6 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,// (z, w: software traversal's units: the top tree's root and their count, as bits; trace_units.wgsl. y is// `render --signals`'.)motion: sc.units.as_ref().map_or([0.0; 4], |u| [0.0, 0.0, f32::from_bits(u.layout.top_first), f32::from_bits(u.count)]),- group_first: [[0; 4]; 2],light_lod: [0.0; 4],emit_power: [total, 0.0, 0.0, 0.0],aerial: [0.0; 4],@@ -849,27 +732,13 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,baked.write(&mut params, env_nee_floor);sc.environment.write(&mut params);let env = baked.env;- let mut first = 0u32;- for (g, &count) in groups.iter().enumerate() {- params.group_first[g / 4][g % 4] = first;- first += 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.+ sc.indexed = index_geometry(sc, &tri_verts);+ // Software traversal: the trees' leaves, every triangle as it was laid out for its tree above (v0, e1, e2), with+ // its section and its index there.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();+ sc.indexed.leaves = tri_verts.chunks_exact(3).zip(&sc.attrs).map(|(t, a)| [[t[0][0], t[0][1], t[0][2], a.uv[3]], [t[1][0], t[1][1], t[1][2], a.x[3]], [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));@@ -889,25 +758,16 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,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;- 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 }+ Prepared { tri_verts, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, moving_mats }}-/// 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 {+/// The scene's triangles, in the GPU's order (`tri_verts`, `sc.attrs`), as vertices and indices (indexed.rs). Each+/// mesh of the pool shares its vertices within itself (the meshes in parallel; a skinned one by its model's corners),+/// a particle system's has four a quad. A mesh's triangles count their vertices from the mesh's first. The vertices+/// lie in the pool's order, so those that move are one run: the deforming meshes', which are the pool's first.+fn index_geometry(sc: &scene::Scene, tri_verts: &[[f32; 4]]) -> 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();@@ -920,7 +780,7 @@ fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], grou.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]);+ let (tris, attrs) = (&sc.pool_tris[r.clone()], &sc.attrs[r]);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 if quads.contains(&(m as u32)) => (indexed::quads(tris, attrs), None),@@ -934,26 +794,16 @@ fn index_geometry(sc: &scene::Scene, order: &[u32], tri_verts: &[[f32; 4]], grouout.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");+ assert_eq!(out.indices.len(), 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");+ assert_eq!(out.meshes[m].0, 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]);- }+ out.dynamic = (0, deforming);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}@@ -1039,11 +889,6 @@ fn unit_trees(sc: &mut scene::Scene) -> Vec<Option<units::MeshTree>> {trees}-/// Traversal group: shadow casting x alpha cutout, static (0..4) or dynamic (4..8: posed models, own BLASes).-fn group_of(flags: u32) -> usize {- ((((flags & scene::TRI_NO_SHADOW) << 1) | ((flags & scene::TRI_MASKED) >> 1)) + (flags & scene::TRI_DYNAMIC)) as usize-}-/// Marginal (rows) + conditional (per row) CDFs over luminance * sin(theta).fn build_env_cdf(env: &gpu::EnvMap) -> Vec<f32> {let (w, h) = (env.width as usize, env.height as usize);@@ -1713,10 +1558,10 @@ mod units_tests {use crate::world::{Geometry, Kind, World};use glam::{Mat4, Quat};- /// A world with a ground and a light's card (an instance each, as every mesh: units under software traversal, and- /// no still triangle), meshes turned and scaled, one that casts no shadow, one hidden, and an instanced mesh of+ /// A world with a ground and a light's card (an instance each, as every mesh: units under software traversal),+ /// meshes turned and scaled, one that casts no shadow, one hidden, and an instanced mesh of/// five instances of which four are drawn.- fn world(ground: bool) -> World {+ fn world() -> World {let mut w = World::default();w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());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![] };@@ -1739,13 +1584,11 @@ mod units_tests {w.set_geometry(3, quad(0.5)).unwrap();w.set_geometry(5, ring).unwrap();let mesh = |geometry, own_blas| Kind::Mesh { geometry, material: 1, own_blas, materials: vec![] };- if ground {- w.set_object(10, "ground".into(), None, mesh(2, false), true, false).unwrap();- w.set_transform(10, Vec3::new(0.0, -1.0, 0.0), Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();- let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 3, "height": 3, "range": 0 })).unwrap();- w.set_object(16, "card".into(), None, Kind::Light(card), true, false).unwrap();- w.set_transform(16, Vec3::new(1.0, 2.5, -1.0), Quat::from_rotation_x(std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();- }+ w.set_object(10, "ground".into(), None, mesh(2, false), true, false).unwrap();+ w.set_transform(10, Vec3::new(0.0, -1.0, 0.0), Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 3, "height": 3, "range": 0 })).unwrap();+ w.set_object(16, "card".into(), None, Kind::Light(card), true, false).unwrap();+ w.set_transform(16, Vec3::new(1.0, 2.5, -1.0), Quat::from_rotation_x(std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();let place = |w: &mut World, id: u32, geometry: u32, at: [f32; 3], turn: f32, scale: [f32; 3], shadow: bool| {w.set_object(id, format!("o{id}"), None, mesh(geometry, true), shadow, false).unwrap();w.set_transform(id, Vec3::from(at), Quat::from_euler(glam::EulerRot::XYZ, turn, turn * 0.7, 0.3), Vec3::from(scale)).unwrap();@@ -1766,7 +1609,7 @@ mod units_tests {w}- /// `prepare` under software traversal lays out what the kernel walks (the still tree, the meshes' trees and their+ /// `prepare` under software traversal lays out what the kernel walks (the meshes' trees and their/// triangles in tree order, the records with their roots, the top tree, the parameters): the kernel's walk over/// it, on the CPU with every read checked, meets what a ray meets of every instance's triangles tested one by/// one where the instances place them: the closest one's distance (to the rounding of testing a triangle in its@@ -1774,7 +1617,7 @@ mod units_tests {/// No GPU.#[test]fn a_scene_with_units_is_its_triangles_to_every_ray() {- agree(&world(true), (3000, 400, 2000));+ agree(&world(), (3000, 400, 2000));}/// `prepare`'s vertices and indices (indexed.rs) are its triangles: every triangle read through its indices (a@@ -1785,7 +1628,7 @@ mod units_tests {/// one run. No GPU.#[test]fn the_indexed_geometry_is_the_scenes_triangles() {- let mut w = world(true);+ let mut w = world();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();@@ -1795,20 +1638,14 @@ mod units_tests {let mut sc = scene::build(&w, std::path::Path::new(".."), &default_presets_dir(), None).unwrap();let p = prepare_as(hwrt, &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() - 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);+ assert_eq!(x.indices.len(), sc.attrs.len(), "{what}");+ // (A triangle's mesh: its vertices count from the mesh's first.)+ let base = |k: usize| sc.meshes.iter().zip(&x.meshes).find(|(m, _)| m.count > 0 && (m.first as usize..(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]];- // (The triangle of a still tree over nothing, after the pool: without area either way.)- if sc.units.is_some() && sc.tris.is_empty() && k + 1 == sc.attrs.len() {- assert_eq!((edge(1), edge(2), v(1), v(2)), ([0.0; 3], [0.0; 3], [0.0; 3], [0.0; 3]), "{what}: the still tree's own triangle has no area");- continue;- }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 {@@ -1816,17 +1653,10 @@ mod units_tests {}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");assert_eq!(tangent.map(|t| bits(&t)), [a.t, a.t1, a.t2].map(|t| bits(&t)), "{what}: triangle {k}'s tangents, a corner each, 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).+ // Software traversal: the triangle as its tree's leaf has it, with its section and its index there.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[k].map(|r| bits(&r)), indexed::leaf(corners, [a.uv[3].to_bits(), a.x[3].to_bits()]).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");@@ -1856,7 +1686,7 @@ mod units_tests {/// not run there) no kernel asks for a particle's object. No GPU.#[test]fn a_particle_system_is_a_mesh_of_quads_and_an_instance() {- let mut w = world(true);+ let mut w = world();w.set_material(7, serde_json::from_value(serde_json::json!({ "name": "spark", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 0.5, 0.2], "emissiveIntensity": 20, "doubleSided": true })).unwrap());w.set_particle_fn("rise", "fn pf_rise(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(i.pivot + vec3<f32>(f32(i.index), i.time, 0.0), vec3<f32>(0.1, 0.0, 0.0), vec3<f32>(0.0, 0.1, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());for (id, count, emitter_area) in [(40, 3, 0.0), (41, 2, 0.09)] {@@ -1877,7 +1707,7 @@ mod units_tests {let (own, sampled) = (&sc.particles[0], &sc.particles[1]);let (stateful, stateful_sampled) = (&sc.gpu_particles[0], &sc.gpu_particles[1]);assert_eq!((stateful.capacity, stateful_sampled.capacity), (5, 1), "{what}: the stateful systems, as the stateless");- assert!(sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0).count() == 5 && sc.tris.is_empty(), "{what}: five systems, an instance each, none a world-space triangle");+ assert!(sc.instances.iter().filter(|i| i.bits & scene::INST_PARTICLES != 0).count() == 5, "{what}: five systems, an instance each");// (Software traversal: a system's mesh has no tree, its pass being hardware traversal's: its instance is no// unit. Every other instance is one, a hidden one out of the top tree.)if let Some(u) = &sc.units {@@ -1894,8 +1724,7 @@ mod units_tests {assert_ne!(part, 0, "{what}: the kernel asks for a particle's object");let (m, v) = (sc.meshes[own.mesh as usize], sc.indexed.meshes[own.mesh as usize]);assert_eq!((m.count, m.deforms, m.sect_count, v.1), (6, true, 1, 12), "{what}: two triangles and four vertices a particle");- let pool_first = sc.attrs.len() - sc.pool_tris.len();- let tris = &sc.indexed.indices[pool_first + m.first as usize..][..6];+ let tris = &sc.indexed.indices[m.first as usize..][..6];assert_eq!(tris, [[0, 1, 2], [0, 2, 3], [4, 5, 6], [4, 6, 7], [8, 9, 10], [8, 10, 11]], "{what}: a quad's corners once each");let uv = |k: u32| [sc.indexed.vertices[(v.0 + k) as usize][0][3], sc.indexed.vertices[(v.0 + k) as usize][1][3]];assert_eq!([uv(4), uv(5), uv(6), uv(7)], [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]], "{what}: in the order the pass writes them");@@ -1922,7 +1751,7 @@ mod units_tests {assert_eq!((row[2], row[3], i.bits & scene::INST_PARTICLES), (i.first_emitter, 0, scene::INST_PARTICLES), "{what}: its row has its first emitter");let mine = &p.emitter_tris[row[2] as usize..][..(count * 2) as usize];for (k, e) in mine.iter().enumerate() {- assert_eq!((e.inst, e.part, e.tri, e.nominal, e.moves, e.area, e.obj), (r as u32, 0, (pool_first as u32 + m.first) + k as u32, true, true, area, i.object), "{what}: emitter {k} of the system");+ assert_eq!((e.inst, e.part, e.tri, e.nominal, e.moves, e.area, e.obj), (r as u32, 0, m.first + k as u32, true, true, area, i.object), "{what}: emitter {k} of the system");}assert_eq!(p.emitter_runs.particles.iter().filter(|run| run[0] <= row[2] && row[2] + count * 2 <= run[0] + run[1]).count(), 1, "{what}: its emitters are taken again from its vertices every frame");}@@ -1939,23 +1768,15 @@ mod units_tests {}}- /// 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.- #[test]- fn a_scene_of_units_alone_is_its_triangles_to_every_ray() {- agree(&world(false), (1000, 1000, 400));- }-/// Software traversal's instances are units wherever a scene is prepared, an offline render's as a session's: the- /// kernel has the unit walk, and nothing is a world-space triangle. A scene without an instance has none.+ /// kernel has the unit walk. A scene without an instance has none.#[test]fn software_traversals_instances_are_units() {- let mut sc = scene::build(&world(true), std::path::Path::new("."), &default_presets_dir(), None).unwrap();+ let mut sc = scene::build(&world(), std::path::Path::new("."), &default_presets_dir(), None).unwrap();assert!(units_wanted(false, &sc) && !units_wanted(true, &sc));prepare_as(false, &mut sc, &mut vec![]);- assert!(sc.units.is_some() && sc.tris.is_empty() && !sc.instances.is_empty() && gpu::instance_features(&sc) & gpu::F_UNITS != 0);- let mut hw = scene::build(&world(true), std::path::Path::new("."), &default_presets_dir(), None).unwrap();+ assert!(sc.units.is_some() && !sc.instances.is_empty() && gpu::instance_features(&sc) & gpu::F_UNITS != 0);+ let mut hw = scene::build(&world(), std::path::Path::new("."), &default_presets_dir(), None).unwrap();prepare_as(true, &mut hw, &mut vec![]);assert!(hw.units.is_none() && gpu::instance_features(&hw) & gpu::F_UNITS == 0, "hardware traversal: none");let mut w = World::default();@@ -1987,15 +1808,12 @@ mod units_tests {fn agree(w: &World, least: (usize, usize, usize)) {let mut su = scene::build(&w, std::path::Path::new("."), &default_presets_dir(), None).unwrap();let pu = prepare_as(false, &mut su, &mut vec![]);- // (The ground and the light's card come together: `world`.)- let ground = 2 * usize::from(w.objects.contains_key(&10));- assert_eq!(su.tris.len(), 0, "no still triangle: the card is an instance too");let u = su.units.as_ref().expect("the scene has units");// Ten instances, the ground and the card: four meshes shown, one hidden (an instance no ray sees), five of the// instanced mesh of which one is hidden: eight units in the top tree, the ground and the card.- assert_eq!((su.instances.len(), u.count as usize), (10 + ground, 8 + ground), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());+ assert_eq!((su.instances.len(), u.count as usize), (12, 10), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());assert!(gpu::instance_features(&su) & gpu::F_UNITS != 0);- assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits() as usize), (u.layout.top_first, 8 + ground));+ assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits() as usize), (u.layout.top_first, 10));assert_eq!(pu.nodes.len(), u.layout.top_first as usize + u.layout.top_cap as usize);let instances = if su.gpu_instances.is_empty() { vec![scene::GpuInstance::default()] } else { su.gpu_instances.clone() };let kernel = Kernel { nodes: &pu.nodes, leaves: &su.indexed.leaves, instances: &instances, rows: &su.rows, top: pu.params.motion[2].to_bits(), units: pu.params.motion[3].to_bits(), steps: Default::default(), budget: 1 << 20, deepest: Default::default(), reads: Default::default() };diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex abe27bd..1108ad4 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -88,7 +88,7 @@ impl EditSplit {/// procedural word (counted from the region's start) and TLAS instance, and where they started.#[derive(Default)]pub(super) struct EditState {- /// Triangles (GPU order), kernel records (a record's TLAS instance is `inst_base` + it) and object-table entries+ /// Triangles (GPU order), kernel records (a record's TLAS instance, or its unit, is at it) and object-table entries/// edits can place: holes left by what they no longer draw, then the room, which grows past its end (ROADMAP § 6/// step 5).pub(super) tris: Holes,@@ -106,14 +106,12 @@ pub(super) struct EditState {/// Times the room grew (frame log `grows`), and whether the scene bind group must be made again.pub(super) grows: u32,pub(super) rebind: bool,- /// (triangles, records, objects, words, TLAS instances) the scene itself has: the room starts there.- pub(super) base: (usize, usize, usize, usize, usize),+ /// (triangles, records, objects, words) the scene itself has: the room starts there.+ pub(super) base: (usize, usize, usize, usize),/// The instances' rows (`scene::Row`) edits can place, as the records are, and the run each record an edit placed/// has (its first row, how many): given back with the record, kept where an object is placed again with as many.pub(super) rows: Holes,pub(super) row_runs: std::collections::HashMap<usize, (usize, usize)>,- /// The first pool triangle (instanced meshes' triangles are counted from it).- 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 positions (a vertex each) of the deforming meshes edits place: the build's before them,@@ -300,7 +298,7 @@ pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool,cx.edit.verts.give(old.vfirst as usize, old.vcount as usize);(cx.meshes[k as usize].vfirst, cx.meshes[k as usize].vcount) = (vfirst as u32, nv as u32);if let gpu::Top::Hw(accel) = &mut *cx.top {- cx.g.set_mesh(accel, k, cx.edit.pool_first + old.first as usize, &cx.meshes[k as usize], cx.sections);+ cx.g.set_mesh(accel, k, old.first as usize, &cx.meshes[k as usize], cx.sections);}}let im = cx.meshes[k as usize];@@ -314,7 +312,7 @@ pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool,let root = units.add_tree(k, tree).ok_or("edit room: tree nodes")?;cx.g.write_tree(cx.nodes, root, tree);}- (k, cx.edit.pool_first + im.first as usize, im)+ (k, im.first as usize, im)}None => {// A hole that fits, else the room's end (grown if it lacks room).@@ -341,7 +339,7 @@ pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool,}};cx.sections[sect_first as usize..][..n].copy_from_slice(§s);- 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 - cx.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 as u32) };let k = match &mut *cx.top {gpu::Top::Hw(accel) => match dead {Some(k) => {@@ -390,18 +388,17 @@ pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool,cx.w_colors.put((first * 12) as u64, bytemuck::cast_slice(&c));}cx.split.upload += t2.elapsed().as_secs_f64() * 1e3;- let rel = first - cx.edit.pool_first;- if cx.pool_tris.len() < rel + t.len() {- cx.pool_tris.resize(rel + t.len(), [glam::Vec3A::ZERO; 3]);+ if cx.pool_tris.len() < first + t.len() {+ cx.pool_tris.resize(first + t.len(), [glam::Vec3A::ZERO; 3]);}- cx.pool_tris[rel..rel + t.len()].copy_from_slice(&t);+ cx.pool_tris[first..first + t.len()].copy_from_slice(&t);// (Software traversal: where its tree left each triangle of its sections, `mesh_places`.)if cx.top.sw() {- if cx.pool_place.len() < rel + t.len() {- cx.pool_place.resize(rel + t.len(), [0; 2]);+ if cx.pool_place.len() < first + t.len() {+ cx.pool_place.resize(first + t.len(), [0; 2]);}for (j, x) in a.iter().enumerate() {- cx.pool_place[rel + j] = [x.uv[3].to_bits(), x.x[3].to_bits()];+ cx.pool_place[first + j] = [x.uv[3].to_bits(), x.x[3].to_bits()];}}let _ = im;@@ -426,7 +423,6 @@ pub(super) struct Placing<'a, 'b> {new_emitters: &'a mut Vec<(u32, crate::GpuEmitterTri)>,emitters_changed: &'a mut bool,top: &'a mut gpu::Top<'b>,- inst_base: usize,}/// An instance placed at `record` by an edit: its rows in the room, each with where its section's triangles start;@@ -436,7 +432,7 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::let im = cx.meshes[inst.mesh as usize];let sects = im.sections(cx.sections);for (s, row) in sects.iter().zip(mine.iter_mut()) {- row[1] = cx.edit.pool_first as u32 + im.first + s.first;+ row[1] = im.first + s.first;}let row_at = rows_for(cx.edit, cx.grow, cx.words, cx.instances, cx.meshes, record, mine.len())?;inst.rows = row_at as u32;@@ -458,7 +454,7 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::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, None);+ let made = crate::instance_emitters(inst, record as u32, &cx.pool_tris[a..b], a as u32, &numbered, n, &cx.tables.materials, moves, None);for (j, (e, w)) in made.into_iter().enumerate() {cx.new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));match cx.tables.emitter_tris.get_mut(first + j) {@@ -479,13 +475,13 @@ pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::}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);+ let gpu = cx.top.record(inst.gpu(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() {cx.gpu_instances.resize(record + 1, scene::GpuInstance::default());}cx.gpu_instances[record] = gpu;- cx.top.place(cx.inst_base + record, inst.mesh, inst.world, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, inst.hidden);+ cx.top.place(record, inst.mesh, inst.world, inst.cast_shadow, inst.hidden);if cx.instances.len() <= record {cx.instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() });}@@ -531,7 +527,7 @@ pub(super) fn drop_mesh_user(k: u32, edit: &mut EditState, tables: &mut tables::*n = n.saturating_sub(1);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.tris.give(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);tables.retained.model_mesh.retain(|_, v| *v != k);@@ -636,7 +632,7 @@ impl Grow<'_> {true}- /// Kernel records and the TLAS (a record's instance is `inst_base` + it).+ /// Kernel records and the TLAS (a record's instance is at it).pub(super) fn records(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, accel: &mut gpu::Accel) -> bool {if !self.ok {return false;@@ -645,7 +641,7 @@ impl Grow<'_> {if !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {return false;}- self.g.grow_tlas(accel, accel.inst_base + cap);+ self.g.grow_tlas(accel, cap);h.cap = cap;true}@@ -890,8 +886,8 @@ impl LiveCore {if !changes.promoted.is_empty() {eprintln!("live: {} moved, now movable (this once rebuilds; set `movable = true` in the scene code to avoid it)", changes.promoted.join(", "));}- // Moved movable subtrees: their drawables are re-transformed with the posed models, their lights rewritten in- // the light table.+ // Posed models, and what of the moved movable subtrees no instance moves (a rebuild's, below); their lights+ // are rewritten in the light table.let mut dynamic = changes.poses.clone();// Still objects that moved for the first time: their meshes' instances move from now on, or the scene rebuilds.for id in std::mem::take(&mut changes.started) {@@ -913,7 +909,7 @@ impl LiveCore {let masked = inst.is_some_and(|i| self.sc.instances.get(i.instance as usize).is_some_and(|x| x.masked));if world.shown(k) || masked {// Movable models placed as instances move their transform (a posed skinned model too); the rest- // re-transform triangles.+ // rebuild.match inst.map(|i| i.instance) {Some(i) if !changes.poses.contains(&k) || inst.is_some_and(|i| matches!(i.mesh, scene::MeshKind::Skinned(_))) => placed.push((k, i)),_ => {@@ -985,7 +981,8 @@ impl LiveCore {}catch_up.flush_section(&self.g.queue, &self.sc.up.heap, Table::Instances);}- if rigid_ok && (dynamic.is_empty() || (!changes.structural && self.repose(world, &dynamic, &mut top)?)) {+ // (What moved and is no instance's to move: a rebuild's.)+ if rigid_ok && dynamic.is_empty() {// Moved emitters: their triangles in the list and the light tree's moving subtree around them, once (after// every in-place update).if std::mem::take(&mut self.emitters_moved) {@@ -994,7 +991,7 @@ impl LiveCore {changes.poses.clear();changes.moved.clear();// Moving objects move their shadows and reflections over static surfaces: let anti-lag look for it.- if !dynamic.is_empty() || !placed.is_empty() || !rigid.is_empty() || !shared.is_empty() || !procs_moved.is_empty() || instanced_done {+ if !placed.is_empty() || !rigid.is_empty() || !shared.is_empty() || !procs_moved.is_empty() || instanced_done {self.lit_changed = self.frame.max(1);}}@@ -1165,11 +1162,11 @@ impl LiveCore {}/// The kernel features the scene needs as it is now: what its materials and the environment ask for (edits change- /// them), with the structural ones the build found (textures, material functions, the traversal groups;+ /// them), with the structural ones the build found (textures, material functions;/// `gpu::instance_features`). A new variant is compiled once, then cached.pub(super) fn kernel_features(&self) -> u32 {- let (textures, functions, groups) = self.sc.fixed_features;- gpu::features_of(&self.sc.tables.materials, self.env.settings.features(), textures, functions, groups, self.sc.instance_features)+ let (textures, functions) = self.sc.fixed_features;+ gpu::features_of(&self.sc.tables.materials, self.env.settings.features(), textures, functions, self.sc.instance_features)}/// The view's state from the world as it is now (`ViewState::of`: the scene's camera with its lens, depth of field@@ -1279,13 +1276,13 @@ impl LiveCore {/// are its mesh's own: `placed_emitter`), for their weights. `all`: those without area too (a mesh that deforms:/// a pose may leave a triangle none, and the next give it some again).fn weigh_run(&mut self, r: u32, all: bool) {- let LoadedScene { tables, instances, pool_tris, edit, .. } = &mut self.sc;+ let LoadedScene { tables, instances, pool_tris, .. } = &mut self.sc;let Some(inst) = instances.get(r as usize) else { return };let run = emitter_run(&tables.emitter_tris, instances, r);for j in run.clone() {let e = tables.emitter_tris[j];if all || e.area > 0.0 {- let (area, c, _) = crate::placed_emitter(inst, &pool_tris[e.tri as usize - edit.pool_first], e.mat, &tables.materials);+ let (area, c, _) = crate::placed_emitter(inst, &pool_tris[e.tri as usize], e.mat, &tables.materials);(tables.emitter_tris[j].area, tables.emitter_tris[j].c) = (area, c);}}@@ -1330,7 +1327,7 @@ impl LiveCore {/// Instance `r`'s emitters become moving ones, where it has some that are not: a new run of the light list, placed/// by `to` (where this commit moves the instance); the light tree keeps the old one where it stood, at no weight.fn emitters_start_moving(&mut self, r: u32, to: glam::Mat4) {- let LoadedScene { tables, instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;+ let LoadedScene { tables, instances, pool_tris, meshes, rows, up, .. } = &mut self.sc;let old = emitter_run(&tables.emitter_tris, instances, r);if old.is_empty() || tables.emitter_tris[old.clone()].iter().all(|e| e.moves) {return;@@ -1340,7 +1337,7 @@ impl LiveCore {for j in old {let e = crate::EmitterTri { moves: true, in_tree: false, ..tables.emitter_tris[j] };tables.emitter_tris[j].area = 0.0;- let w = pool_tris[e.tri as usize - edit.pool_first].map(|v| glam::Vec3A::from(to.transform_point3(v.into())));+ let w = pool_tris[e.tri as usize].map(|v| glam::Vec3A::from(to.transform_point3(v.into())));self.pending_emitters.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));tables.emitter_tris.push(e);}@@ -1360,8 +1357,8 @@ impl LiveCore {/// each by its instance's mask above the triangles (a posed rigid model's every part's; a posed skinned model's/// own), where no ray sees a/// hidden one, and its row's power (`Tables::apply`: a hidden mesh's emitters at no weight). False where- /// something under it is drawn another way, or a mesh is not such an instance (the build flattened it, or an edit- /// took it out while it was hidden): the caller rebuilds.+ /// something under it is drawn another way, or a mesh is not such an instance (an edit took it out while it was+ /// hidden): the caller rebuilds.fn show_meshes(&mut self, world: &World, id: u32, children: &std::collections::HashMap<u32, Vec<u32>>, changes: &mut crate::world::Changes, build: &mut gpu::TopBuild) -> bool {for k in world.subtree_with(id, children) {match &world.objects[&k].kind {@@ -1385,12 +1382,12 @@ impl LiveCore {continue;}let Some(mut top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return false };- // (Software traversal: a mesh that deforms and has no tree is in the still tree, no instance to mask.)+ // (Software traversal: a mesh without a tree is no unit: no instance to mask.)if !top.has_mesh(inst.mesh) {return false;}(inst.hidden, inst.masked) = (unseen, unseen);- top.moved(top.inst_base() + r, w, Some((inst.cast_shadow, unseen)));+ top.moved(r, w, Some((inst.cast_shadow, unseen)));build.instances = true;changes.powers.insert(k);self.weigh_run(r as u32, false);@@ -1411,7 +1408,7 @@ impl LiveCore {for &r in &records {let Some(inst) = self.sc.instances.get_mut(r as usize) else { return false };(inst.hidden, inst.masked) = (unseen, unseen);- top.moved(top.inst_base() + r as usize, inst.world, Some((inst.cast_shadow, unseen)));+ top.moved(r as usize, inst.world, Some((inst.cast_shadow, unseen)));}build.instances = true;changes.powers.insert(k);@@ -1466,12 +1463,11 @@ impl LiveCore {let st = self.sc.tables.stride;let o = &mut self.sc.tables.objects[inst.object as usize * st];(o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);- let slot = top.inst_base() + i as usize;// (Unseen while it has no size, or its object is hidden: `Instance::masked`. Its row's power follows.)let unseen = gone || !world.shown(node);let flipped = inst.hidden != unseen;(inst.hidden, inst.masked) = (unseen, unseen);- top.moved(slot, w, Some((inst.cast_shadow, unseen)));+ top.moved(i as usize, w, Some((inst.cast_shadow, unseen)));self.inst_moving.push(i);if flipped {self.flipped.push(node);@@ -1794,39 +1790,25 @@ impl LiveCore {rec.p = old.p;gpu_instances[r] = rec;up.heap.write(q, Table::Instances, r as u64 * size, bytemuck::bytes_of(&rec));- top.moved(top.inst_base() + r, inst.world, Some((cast, inst.hidden)));+ top.moved(r, inst.world, Some((cast, inst.hidden)));build.instances = true;}Ok(())}- /// Emitter entries for the materials that started emitting (`Tables::started_emitting`): their flattened static- /// triangles (`mat_runs`), positions from `tris`, in the power-share part of the CDF (path code 0, as the light- /// tree's moving emitters; ROADMAP § 6 step 3). Returns them (each one's index and triangle) for `write_emitters`.+ /// Emitter entries for the materials that started emitting (`Tables::started_emitting`), in the power-share part+ /// of the CDF (path code 0, as the light tree's moving emitters; ROADMAP § 6 step 3). Returns them (each one's+ /// index and triangle) for `write_emitters`.pub(super) fn add_material_emitters(&mut self) -> Vec<(u32, crate::GpuEmitterTri)> {let q = &self.g.queue;let sc = &mut self.sc;let mut new = vec![];let started = std::mem::take(&mut sc.tables.started_emitting);- for &mat in &started {- for &[first, end, obj] in sc.mat_runs.get(&mat).map_or(&[][..], |v| v.as_slice()) {- for k in first..end {- let Some(&[a, b, c]) = sc.tri_order.get(k as usize).and_then(|&i| sc.tris.get(i as usize)) else { continue };- 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, part: 0, card: sc.tables.materials[mat as usize].tex1[2] == scene::MAT_EMITTER_CARD };- new.push((sc.tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, [a, b, c], 0)));- sc.tables.emitter_tris.push(e);- }- }- }- }// The instances with a row of one of them (a mesh's, a model's, an instanced object's copies): each gets its// emitters as a new run at the list's end, the sections that emit now one after another, where each starts// in its row and the run's first in the instance's record; the run it had, of fewer, stays at no weight.if !started.is_empty() && !sc.meshes.is_empty() {- let LoadedScene { tables, instances, meshes, pool_tris, pool_place, sections, rows, edit, up, .. } = sc;+ let LoadedScene { tables, instances, meshes, pool_tris, pool_place, sections, rows, up, .. } = sc;let moving = tables.retained.moving_records();let mut records: Vec<usize> = tables.retained@@ -1879,7 +1861,7 @@ impl LiveCore {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]), s))};- let first_tri = edit.pool_first + im.first as usize;+ let first_tri = im.first as usize;let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32)), None) {new.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));@@ -1898,37 +1880,27 @@ impl LiveCore {/// share of power, its count. With the tree's slot for emitters added in place (scenes that can edit geometry), their/// subtree is grown again first and their entries go right after the static ones (ROADMAP § 6 step 4); without it/// they stay at the end, by power share. `new`: the emitters made or made again since the last call (each one's- /// index and triangle): their triangles into the list, their entries into their triangles' attributes. The tables+ /// index and triangle): their triangles into the list. The tables/// grow (and the scene bind group is made again) when entries were added past them: a scene that adds none keeps/// its layout.pub(super) fn write_emitters(&mut self, new: &[(u32, crate::GpuEmitterTri)]) {self.land_powers_now();- 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 LoadedScene { tables: e, base: b, pool_tris, instances, codes_sent: sent, .. } = &mut self.sc;let size = std::mem::size_of::<crate::GpuEmitterTri>();- let (mut w_tris, mut w_rows) = (Gather::default(), Gather::default());+ let mut w_tris = 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_rows.put((t.tri as usize * 16 + 12) as u64, bytemuck::bytes_of(&(i + 1)));- }}- 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).if let Some(t) = e.light_tree.as_mut() {if t.dynamic.is_some() {- let (mats, objs, st, pf) = (&e.materials, &e.objects, e.stride, edit.pool_first);- // (An emitter's triangle in world space: an instance's is its mesh's, placed.)+ let (mats, objs, st) = (&e.materials, &e.objects, e.stride);+ // (An emitter's triangle in world space: its mesh's, placed by its instance.)let verts = |x: &crate::EmitterTri| {- let k = x.tri as usize;- let t = if k >= pf { pool_tris.get(k - pf).copied() } else { tri_order.get(k).and_then(|&i| flat.get(i as usize)).copied() };- match instances.get(x.inst as usize) {- Some(i) if x.inst != crate::NO_INST => t.map(|t| t.map(|v| glam::Vec3A::from(i.world.transform_point3(v.into())))),- _ => t,- }+ let (t, i) = (pool_tris.get(x.tri as usize)?, instances.get(x.inst as usize)?);+ Some(t.map(|v| glam::Vec3A::from(i.world.transform_point3(v.into()))))};let mut items = vec![];for (i, x) in e.emitter_tris.iter().enumerate() {@@ -2104,7 +2076,7 @@ impl LiveCore {/// An object given another material (`World::set_object`): every copy's row names it, with its class, and the/// copies' emitters go or are made with it./// Returns how many objects it updated; Err: why it cannot (software traversal, an object the build- /// flattened or did not place this way, a kernel feature the material needs), and the caller rebuilds.+ /// did not place this way, a kernel feature the material needs), and the caller rebuilds./// `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).pub(super) fn update_instanced(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> std::result::Result<usize, String> {use crate::world::Kind;@@ -2124,7 +2096,7 @@ impl LiveCore {let Some(n) = world.objects.get(&id).filter(|_| world.shown(id)) else { continue };let Kind::Instanced { capacity, procedural, materials, .. } = &n.kind else { continue };let (capacity, procedural) = (*capacity, *procedural);- let Some(&place) = sc.tables.retained.instanced(id) else { return Err("an instanced mesh the build flattened".into()) };+ let Some(&place) = sc.tables.retained.instanced(id) else { return Err("an instanced mesh the build did not place".into()) };if place.capacity != capacity || place.mesh.is_none() != procedural {return Err("an instanced mesh the build placed otherwise".into());}@@ -2167,7 +2139,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, 0)), mesh.count as usize, &sc.tables.materials, true, None);+ let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], a as u32, &|k| Some((k, mat, 0)), mesh.count as usize, &sc.tables.materials, true, None);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);@@ -2183,9 +2155,8 @@ impl LiveCore {w_rows.flush_section(&self.g.queue, &sc.up.words, Stream::Rows);cap = capacity as usize;}- // (A record's slot is `inst_base` + it, a procedural copy's record the first procedural one + its index.)+ // (A procedural copy's record: the first procedural one + its index.)let rec0 = if procedural { sc.proc_first + first } else { first };- let slot0 = top.inst_base() + rec0;for i in 0..cap {let (wm, hidden) = scene::instance_world(m, t, i);let old = sc.gpu_instances[rec0 + i];@@ -2211,7 +2182,7 @@ impl LiveCore {let run = emitter_run(&sc.tables.emitter_tris, &sc.instances, (rec0 + i) as u32);let inst = &sc.instances[first + i];for e in &mut sc.tables.emitter_tris[run] {- let (area, c, _) = crate::placed_emitter(inst, &sc.pool_tris[e.tri as usize - sc.edit.pool_first], e.mat, &sc.tables.materials);+ let (area, c, _) = crate::placed_emitter(inst, &sc.pool_tris[e.tri as usize], e.mat, &sc.tables.materials);reweigh |= (area - e.area).abs() > 1e-5 * area.max(e.area);(e.area, e.c) = (area, c);}@@ -2230,7 +2201,7 @@ impl LiveCore {let edited = if e[0][3] != entry[0][3] { now } else { e[1][3] };e.copy_from_slice(&entry[..st]);e[1][3] = edited;- top.moved(slot0 + i, wm, Some((casts, hidden)));+ top.moved(rec0 + i, wm, Some((casts, hidden)));}let q = &self.g.queue;sc.up.heap.write(q, Table::Instances, (rec0 * size) as u64, bytemuck::cast_slice(&sc.gpu_instances[rec0..rec0 + cap]));@@ -2274,7 +2245,7 @@ impl LiveCore {let o = &mut self.sc.tables.objects[p.object as usize * st];(o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);if let Some(accel) = self.sc.up.accel.as_mut() {- if let Some(t) = accel.tlas[accel.inst_base + i].as_mut() {+ if let Some(t) = accel.tlas[i].as_mut() {t.transform = gpu::tlas_rows(w);}}@@ -2354,7 +2325,7 @@ impl LiveCore {r.p = old.m;self.sc.gpu_instances[i as usize] = r;(ilo, ihi) = (ilo.min(i as usize), ihi.max(i as usize + 1));- top.moved(top.inst_base() + i as usize, w, Some((inst.cast_shadow, gone || inst.hidden)));+ top.moved(i as usize, w, Some((inst.cast_shadow, gone || inst.hidden)));// (Rigid models' instances are theirs alone: no other update this commit placed them.)self.inst_moving.push(i);}@@ -2467,7 +2438,7 @@ impl LiveCore {}let m = self.sc.meshes[sk.mesh as usize];let Some((vertices, index)) = self.sc.skins.get(sk.source as usize).filter(|s| s.1.len() == m.count as usize) else { return Ok(false) };- let first = self.sc.edit.pool_first + m.first as usize;+ let first = m.first as usize;let placed = |e: &crate::EmitterTri| {let k = (e.tri as usize).checked_sub(first)?;Some((m.first as usize + k, (*index.get(k)?).map(|v| glam::Vec3A::from(crate::skin::skin_corner(&vertices[v as usize], rows).0))))@@ -2503,41 +2474,6 @@ impl LiveCore {Ok(true)}- /// Re-skins posed models and re-transforms movable objects in place (hardware RT): their triangles and shading- /// attributes; the commit builds the dynamic BLASes and the TLAS. Their directly seen surfaces keep a short history for a moment,- /// like a power edit (no per-object motion vectors). False when it cannot (not dynamic at build, no hardware RT, a- /// different triangle count): the caller rebuilds.- pub(super) fn repose(&mut self, world: &World, ids: &std::collections::HashSet<u32>, build: &mut gpu::TopBuild) -> Result<bool> {- let dynamic = |p: &mut scene::Proxy| match &mut p.draw {- scene::Draw::Dynamic(d) => Some(std::mem::take(d)),- _ => None,- };- // (Their models out of the proxies while `reskin` has the scene, then back.)- let proxies = &mut self.sc.tables.retained.proxies;- let models: std::collections::HashMap<u32, scene::DynamicModel> = ids.iter().filter_map(|id| Some((*id, dynamic(proxies.get_mut(id)?)?))).collect();- let t_skin = Instant::now();- let res = if self.sc.up.accel.is_none() || models.len() < ids.len() { Ok(None) } else { self.reskin(world, ids, &models) };- self.cpu_skin_ms += t_skin.elapsed().as_secs_f32() * 1000.0;- for (id, d) in models {- self.sc.tables.retained.proxy(id).draw = scene::Draw::Dynamic(d);- }- let Some((lo, hi)) = res? else { return Ok(false) };- self.emitters_moved = true;- let t_up = Instant::now();- // Motion vectors: the GPU still holds the previous frame's vertices for this span (and for last update's span,- // if different): keep them as `prev_verts` before uploading the new ones.- let both = self.prev_span.map_or((lo, hi), |(a, b)| (a.min(lo), b.max(hi)));- self.keep_prev(both);- 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.- 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)- }-/// 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>) {@@ -2559,59 +2495,27 @@ impl LiveCore {}}- /// The emitters the CPU moves moved: their triangles in the list taken again on the GPU, from the triangles this- /// commit uploaded (`gpu::EmitterFills::moved`); and the light tree's moving subtree refit around them (the CPU copy- /// of the dynamic tail), its nodes and the root uploaded (`ltree::LightTree::refit_moving`).+ /// Emitters moved (their instances did, `fill_moved`): the light tree's moving subtree refit around them, its+ /// nodes and the root uploaded (`ltree::LightTree::refit_moving`).pub(super) fn move_emitters(&mut self) {- if let Some(f) = &self.sc.up.fills.moved {- let mut e = self.g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitter fill") });- self.g.fill_emitters(f, &mut e);- self.g.queue.submit([e.finish()]);- }- let first = self.sc.dynamic.0;- let (verts, tables) = (&self.sc.dynamic.1, &mut self.sc.tables);+ let tables = &mut self.sc.tables;let tris = &tables.emitter_tris;let (q, heap) = (&self.g.queue, &self.sc.up.heap);let Some(t) = tables.light_tree.as_mut().filter(|t| t.moving_count > 0) else { return };- let (instances, pool_tris, pool_first) = (&self.sc.instances, &self.sc.pool_tris, self.sc.edit.pool_first);+ let (instances, pool_tris) = (&self.sc.instances, &self.sc.pool_tris);t.refit_moving(&|e| {let x = &tris[e];- // (An instance's: its mesh's triangle, placed; none while the instance is hidden.)- if x.inst != crate::NO_INST {- let i = &instances[x.inst as usize];- return (!i.hidden).then(|| pool_tris[x.tri as usize - pool_first].map(|v| i.world.transform_point3(v.into()).to_array()));- }- let r = (x.tri as usize - first) * 3;- Some(crate::ltree::tri_vertices(&verts[r..r + 3]))+ // (Its mesh's triangle, placed; none while the instance is hidden.)+ let i = instances.get(x.inst as usize)?;+ (!i.hidden).then(|| pool_tris[x.tri as usize].map(|v| i.world.transform_point3(v.into()).to_array()))});heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));heap.write(q, Table::LightTree, 2 * 16, bytemuck::cast_slice(&t.nodes[2..3]));heap.write(q, Table::LightTree, t.moving_nodes as u64 * 16, bytemuck::cast_slice(&t.nodes[t.moving_nodes..]));}- /// 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_verts.0 as usize;- let mut e = self.g.device.create_command_encoder(&Default::default());- 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 vertex in the scene's, its first among the- /// previous frame's, how many vertices).+ /// Copies the GPU's current vertices of deforming meshes to the previous frame's, 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;@@ -2625,109 +2529,6 @@ impl LiveCore {self.g.queue.submit([e.finish()]);}- /// Skins / transforms the objects into the CPU copy of the dynamic tail; the touched span (relative to the tail), or- /// None when one cannot be updated in place.- pub(super) fn reskin(&mut self, world: &World, ids: &std::collections::HashSet<u32>, models: &std::collections::HashMap<u32, scene::DynamicModel>) -> Result<Option<(usize, usize)>> {- use rayon::prelude::*;- if ids.iter().any(|id| !world.shown(*id)) {- return Ok(None);- }- // Objects whose triangles form one run of the dynamic tail (one traversal group) are skinned / re-transformed in- // parallel, one task per object, straight into their own spans of the tail and of the CPU triangles (one core- // took 17 ms for the crowd scene's 150 walkers, docs/ROADMAP.md § 0): ordered by span, the objects split the- // arrays into disjoint slices. The others (e.g. opaque and cutout materials in different groups) one by one.- let run = |d: &scene::DynamicModel| !d.finals.is_empty() && d.finals.iter().enumerate().all(|(j, &f)| f == d.finals[0] + j as u32);- let (mut runs, scattered): (Vec<u32>, Vec<u32>) = ids.iter().copied().partition(|id| run(&models[id]));- runs.sort_by_key(|id| models[id].finals[0]);- let assets = &self.assets;- let sc = &mut self.sc;- let (first, verts, attrs, blas) = &mut sc.dynamic;- let first = *first;- let (mut lo, mut hi) = (usize::MAX, 0);- // The CPU triangles in build order: each object's slice.- let mut by_build = runs.clone();- by_build.sort_by_key(|id| models[id].first);- let mut tris_of: std::collections::HashMap<u32, &mut [[glam::Vec3A; 3]]> = std::collections::HashMap::with_capacity(runs.len());- let (mut tr, mut toff): (&mut [[glam::Vec3A; 3]], usize) = (&mut sc.tris[..], 0);- for id in &by_build {- let d = &models[id];- let (t0, n) = (d.first as usize, d.finals.len());- let (_, r) = std::mem::take(&mut tr).split_at_mut(t0 - toff);- let (t, r) = r.split_at_mut(n);- tr = r;- toff = t0 + n;- tris_of.insert(*id, t);- }- let (mut vr, mut ar, mut br): (&mut [[f32; 4]], &mut [scene::GpuTriAttr], &mut [[f32; 3]]) = (&mut verts[..], &mut attrs[..], &mut blas[..]);- let mut voff = 0usize;- let mut jobs = Vec::with_capacity(runs.len());- for id in &runs {- let d = &models[id];- let (k0, n) = (d.finals[0] as usize - first, d.finals.len());- let (_, r) = std::mem::take(&mut vr).split_at_mut(k0 * 3 - voff * 3);- let (v, r) = r.split_at_mut(n * 3);- vr = r;- let (_, r) = std::mem::take(&mut ar).split_at_mut(k0 - voff);- let (a, r) = r.split_at_mut(n);- ar = r;- let (_, r) = std::mem::take(&mut br).split_at_mut(k0 * 3 - voff * 3);- let (b, r) = r.split_at_mut(n * 3);- br = r;- voff = k0 + n;- (lo, hi) = (lo.min(k0), hi.max(k0 + n));- jobs.push((*id, v, a, b, tris_of.remove(id).unwrap()));- }- let ok: Vec<Result<bool>> = jobs- .into_par_iter()- .map(|(id, v, a, b, t)| {- let d = &models[&id];- let Some(tris) = scene::dynamic_tris(world, id, d, assets)? else { return Ok(false) };- if tris.len() != d.finals.len() {- return Ok(false);- }- for (j, (p, at)) in tris.into_iter().enumerate() {- let (e1, e2) = (p[1] - p[0], p[2] - p[0]);- v[j * 3..j * 3 + 3].copy_from_slice(&[[p[0].x, p[0].y, p[0].z, f32::from_bits(d.flags[j])], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);- // (x.w: an emitter's light-tree code, which stays with its triangle.)- a[j] = scene::GpuTriAttr { x: [at.x[0], f32::from_bits(d.object), at.x[2], a[j].x[3]], ..at };- b[j * 3..j * 3 + 3].copy_from_slice(&scene::blas_tri(p.map(|q| q.to_array())));- t[j] = p.map(glam::Vec3A::from);- }- Ok(true)- })- .collect();- for r in ok {- if !r? {- return Ok(None);- }- }- for id in &scattered {- let d = &models[id];- let Some(tris) = scene::dynamic_tris(world, *id, d, assets)? else { return Ok(None) };- if tris.len() != d.finals.len() {- return Ok(None);- }- for (j, (p, a)) in tris.into_iter().enumerate() {- let k = d.finals[j] as usize - first;- let (e1, e2) = (p[1] - p[0], p[2] - p[0]);- verts[k * 3..k * 3 + 3].copy_from_slice(&[[p[0].x, p[0].y, p[0].z, f32::from_bits(d.flags[j])], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);- attrs[k] = scene::GpuTriAttr { x: [a.x[0], f32::from_bits(d.object), a.x[2], attrs[k].x[3]], ..a };- blas[k * 3..k * 3 + 3].copy_from_slice(&scene::blas_tri(p.map(|v| v.to_array())));- sc.tris[(d.first + j as u32) as usize] = p.map(glam::Vec3A::from);- (lo, hi) = (lo.min(k), hi.max(k + 1));- }- }- for id in ids {- let d = &models[id];- // Pivot (material functions' object position). Motion vectors carry its history.- let pivot = world.world_matrix(*id).transform_point3(glam::Vec3::ZERO);- let st = sc.tables.stride;- let o = &mut sc.tables.objects[d.object as usize * st];- (o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);- }- Ok((lo < hi).then_some((lo, hi)))- }-/// Rebuilds the GPU scene from the world./// Applies geometry edits in place (`Changes::geometries`, `added`, `removed`; objects with their own BLAS:/// procedural meshes and `own_blas` meshes): each touched object's data is written into the edit room@@ -2767,16 +2568,15 @@ impl LiveCore {}}}- let (inst_base, proc_first) = (top.inst_base(), *proc_first);- // An object's (slot, record), where an edit can place it again or take it out: an instance of a mesh that is- // its own, or that an edit placed (a model the build placed is the build's to change), or procedural geometry.- let slot_of = |id: u32, edit: &EditState, tables: &tables::Tables| -> Option<(usize, usize)> {- let record = match &tables.retained.proxies.get(&id)?.draw {- scene::Draw::Instance(i) if i.mesh.own() || edit.in_room(i.instance as usize) => i.instance as usize,- scene::Draw::Procedural(j) => proc_first + *j as usize,- _ => return None,- };- Some((inst_base + record, record))+ let proc_first = *proc_first;+ // An object's record, where an edit can place it again or take it out: an instance of a mesh that is its own,+ // or that an edit placed (a model the build placed is the build's to change), or procedural geometry.+ let record_of = |id: u32, edit: &EditState, tables: &tables::Tables| -> Option<usize> {+ match &tables.retained.proxies.get(&id)?.draw {+ scene::Draw::Instance(i) if i.mesh.own() || edit.in_room(i.instance as usize) => Some(i.instance as usize),+ scene::Draw::Procedural(j) => Some(proc_first + *j as usize),+ _ => None,+ }};let q = &g.queue;// An instance's emitters go (area 0: their weight; the light tree keeps its shape) when its object is removed,@@ -2795,7 +2595,7 @@ impl LiveCore {if let Some((place, mesh)) = tables.retained.instanced(*id).and_then(|p| Some((*p, p.mesh?))) {let (r0, cap) = (place.first as usize, place.capacity as usize);for r in r0..r0 + cap {- top.clear(inst_base + r);+ top.clear(r);// (A copy's emitters go as an instance's do.)let run = emitter_run(&tables.emitter_tris, instances, r as u32);emitters_changed |= !run.is_empty();@@ -2818,7 +2618,7 @@ impl LiveCore {if let Some(r) = tables.retained.rigid(*id) {for rec in r.records() {let rec = rec as usize;- top.clear(inst_base + rec);+ top.clear(rec);let run = emitter_run(&tables.emitter_tris, instances, rec as u32);emitters_changed |= !run.is_empty();tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);@@ -2843,11 +2643,10 @@ impl LiveCore {// model, an instance of its own mesh, where its mesh is one the rays reach by its instance. Its mesh's// triangles and its skinning job stay until the next rebuild, as the build's do.)let its_own = |i: &scene::InstanceRef| whole(i, instances, meshes) || (matches!(i.mesh, scene::MeshKind::Skinned(_)) && instances.get(i.instance as usize).is_some_and(|x| top.has_mesh(x.mesh)));- let at = slot_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| its_own(i)).map(|i| (inst_base + i.instance as usize, i.instance as usize)));- // Drawn, and not at a record an edit can clear (a model of two instances, anything the build flattened): a- // rebuild takes it out.+ let at = record_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| its_own(i)).map(|i| i.instance as usize));+ // Drawn, and not at a record an edit can clear (a model of two instances): a rebuild takes it out.if at.is_none() && tables.retained.proxies.contains_key(id) {- return Err("an object the build placed otherwise (a model in parts, something it flattened) removed".into());+ return Err("an object the build placed otherwise (a model in parts) removed".into());}// (A skinned model an edit placed: with its mesh's triangles go the room of its previous vertices and its// slot among the skinned, which the next one placed takes. The build's stay until the next rebuild.)@@ -2865,8 +2664,8 @@ impl LiveCore {edit.free_skinned.push(g as u32);}let proxy = tables.retained.proxies.remove(id);- if let Some((slot, record)) = at {- top.clear(slot);+ if let Some(record) = at {+ top.clear(record);if let Some(k) = undraw(proxy.as_ref().map(|p| &p.draw), instances, procs) {drop_mesh_user(k, edit, tables, meshes);}@@ -2894,13 +2693,13 @@ impl LiveCore {let mask = |shadow: bool| if shadow { 1 } else { 2 };for id in todo {let Some(o) = world.objects.get(&id) else { continue };- let at = slot_of(id, edit, tables);+ let at = record_of(id, edit, tables);emitters_changed |= release(id, tables, instances);// (A mesh that is hidden is placed all the same, as an instance no ray sees: below.)let is_mesh = matches!(o.kind, Kind::Mesh { .. });if !world.shown(id) && !is_mesh {- if let Some((slot, _)) = at {- top.clear(slot);+ if let Some(r) = at {+ top.clear(r);}if tables.retained.instanced(id).is_some_and(|p| edit.in_room(p.first as usize)) {return Err("an instanced mesh added in place hidden".into());@@ -2911,10 +2710,10 @@ impl LiveCore {continue;}// The mesh it draws now, as an instance at its record: a user fewer once it is placed again (below).- let was = at.and_then(|(_, r)| instances.get(r)).filter(|i| !i.hidden || i.masked).map(|i| i.mesh);- // Drawn but not by a TLAS instance of its own: the build flattened it (movable, or a material instances skip).+ let was = at.and_then(|r| instances.get(r)).filter(|i| !i.hidden || i.masked).map(|i| i.mesh);+ // Drawn but not by an instance an edit can place again (a model the build placed).if at.is_none() && tables.retained.proxies.contains_key(&id) {- return Err("an object the build flattened".into());+ return Err("an object the build placed otherwise".into());}let m = world.world_matrix(id);// A mesh that is hidden, or placed without size, is an instance no ray sees, at a point if it has no size@@ -2944,8 +2743,8 @@ impl LiveCore {return Err("the scene's first procedural object (kernel feature)".into());}let Some(p) = scene::proc_object(world, id, m, object as u32, &tables.retained.materials, assets).map_err(|e| format!("{e:#}"))? else {- if let Some((slot, _)) = at {- top.clear(slot);+ if let Some(r) = at {+ top.clear(r);}undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs);continue;@@ -2987,7 +2786,7 @@ impl LiveCore {let blas = g.proc_blas(&p.blob, &mut pending_procs);let entry = p.object_entry(o);let gpu = p.gpu(header as u32);- (at.map(|(_, r)| r), Placed::Proc(blas, p, gpu), entry)+ (at, Placed::Proc(blas, p, gpu), entry)}Kind::Model { uri, nodes, animation, functions } => {// A model already in the scene: another instance of its mesh, of each of its parts' meshes if it is@@ -3101,7 +2900,7 @@ impl LiveCore {};sections[sect_first as usize..][..ns].copy_from_slice(§s);// (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 own = scene::own_inst_mesh(&t, 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, vfirst: vfirst as u32, vcount: nv as u32, ..own };let mesh = match &mut top {@@ -3130,11 +2929,10 @@ impl LiveCore {}// (It has not moved yet: its previous vertices are its own.)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]);+ if pool_tris.len() < first + n {+ pool_tris.resize(first + n, [glam::Vec3A::ZERO; 3]);}- pool_tris[rel..rel + n].copy_from_slice(&t);+ pool_tris[first..first + n].copy_from_slice(&t);// Its slot among the skinned (one an edit took out again, else a new one), and the pass's job.let slot = edit.free_skinned.pop().unwrap_or(tables.retained.skinned.len() as u32);let sk = scene::Skinned { mesh, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order, object: id, instance: 0, source, palette_len, mirrors };@@ -3156,7 +2954,7 @@ impl LiveCore {let mut placed = vec![];for &(node, mesh) in &parts {if !top.has_mesh(mesh) {- return Err("a model whose mesh is no unit (software traversal flattens it)".into());+ return Err("a model whose mesh is no unit (software traversal has no tree for it)".into());}let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();if glass_caster(&mine) {@@ -3235,7 +3033,7 @@ impl LiveCore {};let im = meshes[mesh as usize];if !top.has_mesh(mesh) {- return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into());+ return Err("a model whose mesh is no unit (software traversal has no tree for it)".into());}// (Its rows, the mesh's own, are placed with its record below.)let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();@@ -3249,7 +3047,7 @@ impl LiveCore {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)+ (at, Placed::Mesh(inst, mine), entry)}}Kind::Mesh { .. } | Kind::Instanced { procedural: false, .. } => {@@ -3304,8 +3102,8 @@ impl LiveCore {let had = tables.retained.own_mesh.get(&key).is_some_and(|&k| meshes[k as usize].colored);let data = scene::section_mesh(geo, grouped, 0, 0, colored || had);if data.tris.is_empty() {- if let Some((slot, _)) = at {- top.clear(slot);+ if let Some(r) = at {+ top.clear(r);}// (No longer drawn: its mesh a user fewer now, as when it is hidden.)if let Some(k) = undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs) {@@ -3331,8 +3129,8 @@ impl LiveCore {drop_mesh_user(k, edit, tables, meshes);}if let Some(cap) = capacity {- // An instanced mesh added in place: `cap` records (their TLAS instances `inst_base` + them) and- // object entries, contiguous, as the build places one (`update_instanced` then rewrites them).+ // An instanced mesh added in place: `cap` records and object entries, contiguous, as the build+ // places one (`update_instanced` then rewrites them).let empty = crate::world::InstanceTable::default();let t = world.instanced.get(&id).unwrap_or(&empty);if t.colors.is_some() && features & gpu::F_TINT == 0 {@@ -3375,7 +3173,7 @@ impl LiveCore {for (i, &(wm, hidden)) in placed.iter().enumerate() {let row_at = run + i;let mut row = scene::row_of(mat, &tables.materials);- row[1] = edit.pool_first as u32 + im.first;+ row[1] = 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, 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.@@ -3383,7 +3181,7 @@ impl LiveCore {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, 0)), im.count as usize, &tables.materials, true, None);+ let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], a as u32, &|k| Some((k, mat, 0)), im.count as usize, &tables.materials, true, None);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);@@ -3396,10 +3194,10 @@ impl LiveCore {rows.resize(row_at + 1, [0; 4]);}rows[row_at] = row;- let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow);+ let rec = top.record(inst.gpu(im.first), mesh, inst.cast_shadow);w_records.put(((r0 + i) * size) as u64, bytemuck::bytes_of(&rec));gpu_instances[r0 + i] = rec;- top.place(inst_base + r0 + i, mesh, wm, gpu::INSTANCE_BIT | (r0 + i) as u32, inst.cast_shadow, hidden);+ top.place(r0 + i, mesh, wm, inst.cast_shadow, hidden);let (lo, hi) = im.placed_bounds(wm);let entry = scene::copy_row(scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i)), emits && hidden);w_objects.put(((o0 + i) * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));@@ -3419,7 +3217,7 @@ impl LiveCore {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)+ (at, Placed::Mesh(inst, mine), entry)}_ => return Err("not an object an edit places".into()),};@@ -3429,8 +3227,8 @@ impl LiveCore {Placed::Parts(parts) => parts.len(),_ => 1,};- let (slot, record) = match (at, record) {- (Some((slot, _)), Some(r)) => (slot, r),+ let record = match (at, record) {+ (Some(_), Some(r)) => r,_ => {let r = match edit.records.take(n) {Some(r) => r,@@ -3441,7 +3239,7 @@ impl LiveCore {}None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: records (software traversal's does not grow)" } else { "edit room: records (particles, or the device's limits)" }.into()),};- (inst_base + r, r)+ r}};// Above the triangles, and the record's value where the build's are: `instances[record]`, or `procs` at the@@ -3449,7 +3247,7 @@ impl LiveCore {// (A mesh a body drives moves as an instance does, as the build's: `commit`.)let moves = o.driven || world.movable(id);let mut place = |record: usize, inst: &mut scene::Instance, mine: &mut [scene::Row], moves: bool| {- let mut cx = Placing { edit: &mut *edit, grow: &grow, words: &mut up.words, tables: &mut *tables, instances: &mut *instances, gpu_instances: &mut *gpu_instances, meshes: &meshes[..], sections: §ions[..], rows: &mut *rows, pool_tris: &pool_tris[..], pool_place: &pool_place[..], w_rows: &mut w_rows, w_records: &mut w_records, new_emitters: &mut new_emitters, emitters_changed: &mut emitters_changed, top: &mut top, inst_base };+ let mut cx = Placing { edit: &mut *edit, grow: &grow, words: &mut up.words, tables: &mut *tables, instances: &mut *instances, gpu_instances: &mut *gpu_instances, meshes: &meshes[..], sections: §ions[..], rows: &mut *rows, pool_tris: &pool_tris[..], pool_place: &pool_place[..], w_rows: &mut w_rows, w_records: &mut w_records, new_emitters: &mut new_emitters, emitters_changed: &mut emitters_changed, top: &mut top };place_instance(&mut cx, record, inst, mine, moves)};let draw = match blas {@@ -3459,7 +3257,7 @@ impl LiveCore {gpu_instances.resize(record + 1, scene::GpuInstance::default());}gpu_instances[record] = gpu;- top.place_blas(slot, &blas, m, record as u32, mask(o.cast_shadow));+ top.place_blas(record, &blas, m, mask(o.cast_shadow));let j = record - proc_first;if procs.len() <= j {procs.resize(j + 1, scene::ProcObject { name: String::new(), materials: vec![], hidden: true, ..p.clone() });diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex f6cc507..cce6d41 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -207,7 +207,7 @@ impl LiveCore {// A camera cut (a jump no camera makes in one frame: 2 m or 30 degrees) is not motion: no blur (UE: bCameraCut).let cut = (self.cam.pos - self.prev_cam.pos).length() > 2.0 || self.cam.fwd.dot(self.prev_cam.fwd) < 0.866;// (Objects moved this frame: re-posed triangles or moved instances, e.g. a crowd's walkers.)- let blur = self.blur.0 > 0.0 && (moved || self.reposed || self.pose_reposed || self.inst_moved) && !cut;+ let blur = self.blur.0 > 0.0 && (moved || self.pose_reposed || self.inst_moved) && !cut;// Camera motion is reprojected exactly (disocclusions are rejected per pixel), so history survives motion;// the cap only bounds smearing of view-dependent shading (glossy reflections).// Diffuse lighting reprojects exactly with the camera; view-dependent specular is handled per pixel (temporal pass).@@ -262,12 +262,6 @@ impl LiveCore {if measure {let _ = g.device.poll(wgpu::PollType::wait_indefinitely());}- // Nothing moved since the last in-place update: its span's previous-frame vertices become the current ones.- if let (false, Some(span)) = (self.reposed, self.prev_span) {- self.keep_prev(span);- self.prev_span = None;- }- self.reposed = false;if !self.pose_reposed && !self.pose_spans.is_empty() {let spans = std::mem::take(&mut self.pose_spans);self.keep_prev_spans(&spans);@@ -314,7 +308,7 @@ impl LiveCore {}let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));// Something moves (triangles re-transformed, instances' transforms): the kernel writes motion vectors.- let moving = !self.sc.dynamic.1.is_empty() || self.sc.moving_instances || gpu::Gpu::particle_meshes(&self.sc.up);+ let moving = self.sc.moving_instances || gpu::Gpu::particle_meshes(&self.sc.up);for k in 0..spp.max(1) {let mut p = self.sc.base;p.motion[1] = reconstruction.raw_signal() as u32 as f32;@@ -329,7 +323,6 @@ impl LiveCore {}p.jitter = [jitter.0, jitter.1, if self.rays { 0.0 } else { 1.0 }, 0.0];if moving {- // The kernel finds the first dynamic triangle in Params::group_first (group 4), a u32.p.motion[0] = 1.0;}if self.cache.is_some() {@@ -363,7 +356,7 @@ impl LiveCore {}}// Stateful GPU particles first (their emissions, the game's spawns): with stateless ones the pass below- // rebuilds the dynamic BLASes for both, else this one does.+ // rebuilds the systems' BLASes for both, else this one does.if let (Some(_), 0) = (&self.sc.up.gpu_particles, k) {let n = self.passes.pipes.len() as u32 + 2;let stateless = self.sc.up.particles.is_some();diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 9559bc1..a0f4f20 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -120,7 +120,7 @@ fn forget(core: &mut LiveCore) {/// Whether the rays see the instance at `record`: by its mask above the triangles, or its unit.fn seen_by_rays(c: &LiveCore, record: u32) -> bool {match (&c.sc.up.accel, &c.sc.up.units) {- (Some(a), _) => a.tlas[a.inst_base + record as usize].as_ref().is_some_and(|t| t.mask != 0),+ (Some(a), _) => a.tlas[record as usize].as_ref().is_some_and(|t| t.mask != 0),(None, Some(u)) => u.slots.get(record as usize).copied().flatten().is_some_and(|x| !x.hidden),_ => false,}@@ -355,7 +355,7 @@ fn a_ray_that_meets_an_emitter_weighs_it_by_that_triangles_entry() {(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, &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();+ let frame = g.render(&sc, 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));@@ -589,7 +589,6 @@ fn a_moved_card_beside_another_is_placed_where_its_light_is() {.collect()};let placed = |m: glam::Mat4, to: Vec3| m.abs_diff_eq(scene::card_world(glam::Mat4::from_rotation_translation(turn, to), 0.4, 0.3), 1e-6);- assert!(live.sc.dynamic.1.is_empty() && live.sc.tris.is_empty(), "a card is no world-space triangle");let first = cards(&live);assert!((0..3).all(|k| placed(first[k].0, at[k])), "as loaded: each card where its light is");assert!(first.iter().all(|c| c.1.m == c.1.p), "as loaded: nothing has moved");@@ -759,17 +758,15 @@ fn a_skinned_primitive_without_normals_is_shaded_by_its_triangles() {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, &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 (sc, _) = 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 first = 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");@@ -777,7 +774,7 @@ fn a_skinned_primitive_without_normals_is_shaded_by_its_triangles() {};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 frame = g.render(&sc, 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}");}@@ -1006,8 +1003,7 @@ fn moves_in_place_leave_what_a_build_does() {}}-/// An instanced object whose copies emit is gone from the picture once it is removed (its copies were flattened once,-/// and nothing took them out).+/// An instanced object whose copies emit is gone from the picture once it is removed.#[test]fn an_emitting_instanced_object_removed_is_gone() {let presets = crate::default_presets_dir();@@ -1072,10 +1068,9 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {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);- // (The triangles as the kernel reads them: three indices each; the vertices; the rows of those that have one.)+ // (The triangles as the kernel reads them: three indices each; the vertices.)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());@@ -1096,40 +1091,33 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {if e.area <= 0.0 {continue;}- // (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 };+ // (A mesh's indices count from its instance's first vertex.)+ let base = 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 {- // (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 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: 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);- 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);+ // (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 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: 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);+ 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;}assert!(alive > 0, "{what}: the list has emitters");@@ -1491,7 +1479,6 @@ fn the_light_list_holds_its_triangles() {w.take_changes();assert_eq!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.moving_count > 0), tree, "the mover is in the tree's moving subtree");assert!(live.sc.tables.emitter_tris.iter().any(|e| e.inst != crate::NO_INST && e.moves), "the mover's emitters are its instance's");- assert!(live.sc.up.fills.moved.is_none(), "no triangle is left for the CPU to move");list_is_its_triangles("a moving emitter, as loaded", &live);w.set_transform(13, Vec3::new(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap();let rebuilt = live.commit(&mut w).unwrap();@@ -2639,10 +2626,9 @@ fn an_instanced_object_given_another_material_has_it_in_its_copies_rows() {lit_as_a_build(what, &mut live, &mut open(&w).unwrap());}-/// What still changes by a rebuild: a material of world-space triangles. Particles' (dynamic triangles: their class-/// is theirs, and they get no emitters in place) when it starts emitting or becomes a cutout; one that still-/// triangles have (the build groups them by whether they are cutouts) when it becomes a cutout. The same change of-/// a material that only instances' rows name is in place.+/// What still changes by a rebuild: a particle system's material (its triangles are its pass's: they get no emitters+/// in place) when it starts emitting or becomes a cutout. The same change of a material that only instances' rows+/// name is in place.#[test]fn a_material_of_world_space_triangles_changes_by_a_rebuild() {let presets = crate::default_presets_dir();@@ -2669,17 +2655,12 @@ fn a_material_of_world_space_triangles_changes_by_a_rebuild() {};w.take_changes();let index = |c: &LiveCore, id: u32| c.sc.tables.retained.materials[&id];- assert!(live.sc.tables.moving_mats.contains(&index(&live, 62)) && !live.sc.tables.moving_mats.contains(&index(&live, 64)), "the particles' material is dynamic triangles', the tile's is not");+ assert!(live.sc.tables.moving_mats.contains(&index(&live, 62)) && !live.sc.tables.moving_mats.contains(&index(&live, 64)), "the particles' material is the pass's, the tile's is not");// The tile's material, which rows alone name: a cutout and back, in place.for (test, what) in [(0.5, "becomes a cutout"), (0.0, "is none again")] {w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": test })));assert!(!live.commit(&mut w).unwrap(), "a material of rows {what}: in place ({:?})", live.fallback);}- // The same, were it still triangles' too: a rebuild.- let k = index(&live, 64);- live.sc.tables.static_mats.insert(k);- w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": 0.5 })));- assert!(live.commit(&mut w).unwrap(), "a material of still triangles becomes a cutout: a rebuild");// The particles' material: it starts emitting, it becomes a cutout.w.set_material(62, plain(serde_json::json!({ "emissive": [1.0, 0.8, 0.6], "emissiveIntensity": 20 })));assert!(live.commit(&mut w).unwrap(), "the particles' material starts emitting: a rebuild");@@ -3164,7 +3145,7 @@ fn a_posed_rigid_model_with_a_second_mesh_is_hidden_and_removed_in_place() {w.take_changes();{let r = live.sc.tables.retained.rigid(32).expect("a posed rigid model");- assert!(live.sc.tris.is_empty() && r.records().iter().any(|&i| live.sc.meshes.iter().any(|m| m.over == live.sc.instances[i as usize].mesh)), "one of its instances is of a part's second mesh");+ assert!(r.records().iter().any(|&i| live.sc.meshes.iter().any(|m| m.over == live.sc.instances[i as usize].mesh)), "one of its instances is of a part's second mesh");}let before = picture(&mut live, 48);w.set_visible(32, false).unwrap();@@ -3257,7 +3238,7 @@ fn a_posed_skinned_models_emitters_follow_its_pose() {w.take_changes();let sk = live.sc.tables.retained.skinned.iter().find(|s| s.object == 30).expect("a posed skinned model").clone();let its = |c: &LiveCore| c.sc.tables.emitter_tris.iter().filter(|e| e.inst == sk.instance && e.area > 0.0).copied().collect::<Vec<_>>();- assert!(live.sc.tris.is_empty() && !its(&live).is_empty() && its(&live).iter().all(|e| e.moves), "its emitters are its instance's, moving ones");+ assert!(!its(&live).is_empty() && its(&live).iter().all(|e| e.moves), "its emitters are its instance's, moving ones");list_is_its_triangles("as loaded", &live);// (The codes the load uploaded are on record: the first write of the weights sends those that change, not all.){@@ -3275,7 +3256,7 @@ fn a_posed_skinned_models_emitters_follow_its_pose() {let cpu = skinned_on_cpu(&live, &sk, &bend(time).unwrap()).p;let m = live.sc.meshes[sk.mesh as usize];for e in its(&live) {- let k = e.tri as usize - live.sc.edit.pool_first - m.first as usize;+ let k = e.tri as usize - m.first as usize;let got: Vec<f32> = live.sc.pool_tris[m.first as usize + k].iter().flat_map(|v| v.to_array()).collect();assert!(got.iter().zip(&cpu[k * 9..k * 9 + 9]).all(|(a, b)| (a - b).abs() < 1e-5), "{what}: the CPU has triangle {k} at {got:?}, the pose {:?}", &cpu[k * 9..k * 9 + 9]);}@@ -3373,7 +3354,7 @@ fn a_posed_skinned_model_is_added_in_place() {w.set_object(id, format!("m{id}"), None, model(name, bend(0.0)), true, false).unwrap();w.set_transform(id, Vec3::new(x, -0.8, 0.8), glam::Quat::IDENTITY, Vec3::splat(1.2)).unwrap();}- // (A movable rect light's card: world-space triangles that move, whose previous vertices lie before the meshes'.)+ // (A movable rect light's card: an instance of the cards' mesh.)let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 0.3, "height": 0.3, "range": 0 })).unwrap();w.set_object(22, "card".into(), None, Kind::Light(card), true, true).unwrap();w.set_transform(22, Vec3::new(-2.4, 1.3, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();@@ -3731,7 +3712,7 @@ fn a_posed_skinned_model_is_removed_in_place() {/// vertices two joints hold, weights that do not sum to one, a primitive with tangents and one without normals, a/// mesh on a node beside the skin that mirrors it, a joint turned about an axis that is neither the normals' nor the/// tangents', its materials in an order a mesh laid out by material does not keep; and arm.glb), two of each, each-/// a mesh of its own, in a scene with world-space triangles before the meshes': after each new pose the GPU's+/// a mesh of its own, in a scene with a movable light's card: after each new pose the GPU's/// triangles, shading attributes and BLAS input of each mesh are its model's triangles for the pose, the previous/// frame's vertices are the pose before, and the CPU has the mesh as it is now when asked. One posed alone leaves/// the others' as they were. Also after the scene's buffers were made again larger, and a pose that mirrors otherdiff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex 5d43a6c..0b4663b 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -6,17 +6,13 @@ use super::*;pub(super) struct LoadedScene {/// Load phases (parse, bvh, sky, accel build, upload) in ms.pub(super) timings: Vec<(String, f64)>,- /// World-space triangles + per-node ranges, kept on the CPU for picking and selection outlines; instanced meshes- /// (model space) and their placements likewise.- pub(super) tris: Vec<[glam::Vec3A; 3]>,- pub(super) tri_nodes: Vec<(String, u32, u32)>,- /// Flattened instances of instanced objects: (first, end, instance index), for picking.- pub(super) tri_instances: Vec<(u32, u32, u32)>,+ /// The meshes' triangles (model space) and their placements, kept on the CPU for picking and selection outlines./// (A mesh the GPU skins has its build's pose here, but for its triangles that emit, which a new pose places:/// `repose_skinned`. `LiveCore::mesh_tris` has the mesh as it is now.)pub(super) pool_tris: Vec<[glam::Vec3A; 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`).+ #[cfg_attr(not(test), allow(dead_code))]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@@ -49,13 +45,8 @@ 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 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 of the scene as a whole: whether it has textures, whether it has material functions,- /// its traversal groups (edits cannot change the groups).- pub(super) fixed_features: (bool, bool, [usize; crate::GROUPS]),+ pub(super) fixed_features: (bool, bool),/// The scene's material functions (name, code, helpers), each at its number (`Retained::shaders`): the build's/// by name, one that came while the scene runs after them (`set_functions`).pub(super) shaders: Vec<(String, String, String)>,@@ -70,10 +61,6 @@ pub(super) struct LoadedScene {pub(super) edit: EditState,/// Power edits' emitter rebuilds on a worker (`EmitterWorker`), for scenes with many emitters.pub(super) emit: Option<EmitterWorker>,- /// For materials that start emitting (`add_material_emitters`): their flattened static triangles' runs (`prepare`)- /// and the flattened triangles' build indices in traversal order (positions in `tris`).- pub(super) mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,- pub(super) tri_order: Vec<u32>,/// The light list's path codes as the GPU has them (`GpuEmitterTri::code`, by emitter): the upload's, then what/// `write_emitters` wrote, which writes only those that changed since.pub(super) codes_sent: Vec<u32>,@@ -244,12 +231,10 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet mut tables = tables::Tables::new(&sc, std::mem::take(&mut prep.emitter_tris), prep.light_tree.take());// (THREERT_EDIT_REBUILD=1: every edit rebuilds, a material that starts emitting too: the A/B.)tables.emit_in_place = std::env::var("THREERT_EDIT_REBUILD").map_or(true, |v| v != "1");- tables.static_mats = prep.mat_runs.keys().copied().collect();tables.moving_mats = std::mem::take(&mut prep.moving_mats);let emit = EmitterWorker::new(&tables, &g.device);tables.defer_powers = emit.is_some();- let (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);+ let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty());let shaders = sc.shaders.clone();let volume_fns = sc.volume_fns.clone();let translucent_mats = sc.translucent_mats();@@ -257,7 +242,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P// (The light tree is the tables' by now: its nodes from there.)// (The codes the upload writes with the list: `write_emitters` sends those that change after.)let codes_sent: Vec<u32> = prep.gpu_emitter_tris.iter().map(|t| t.code).collect();- 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 up = g.upload(&sc, &targets.accum, 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");@@ -280,7 +265,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P}base.ltile[3] = super::LIST_CANDIDATES;base.cam_fwd[3] = w as f32 / h as f32;- let (tris, tri_nodes, tri_instances) = (std::mem::take(&mut sc.tris), std::mem::take(&mut sc.tri_nodes), std::mem::take(&mut sc.tri_instances));let 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));@@ -295,19 +279,10 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet procs = std::mem::take(&mut sc.procs);// (A proxy's index in `procs` is the build's: nothing between the build and here may take one out.)assert!(tables.retained.proxies.iter().all(|(id, p)| !matches!(p.draw, scene::Draw::Procedural(j) if procs.get(j as usize).map(|q| q.node) != Some(*id))), "a procedural object's proxy names another's place");- let triangles = sc.stats.get("triangles").map_or(tris.len(), |t| *t as usize);- let first = prep.groups[..4].iter().sum::<usize>();- // The kernel's first dynamic triangle (motion vectors, prev_verts) is group 4's first.- debug_assert_eq!(prep.params.group_first[1][0] as usize, first);- // The dynamic tail: groups 4..8 (the instanced pool follows them).- let end = prep.groups.iter().sum::<usize>();- let blas = prep.tri_verts[first * 3..end * 3].chunks(3).flat_map(|t| [0, 1, 2].map(|k| if k == 0 { [t[0][0], t[0][1], t[0][2]] } else { [t[0][0] + t[k][0], t[0][1] + t[k][1], t[0][2] + t[k][2]] })).collect();- let dynamic = (first, prep.tri_verts[first * 3..end * 3].to_vec(), sc.attrs[first..end].to_vec(), blas);+ let triangles = sc.stats.get("triangles").map_or(0, |t| *t as usize);let blobs = sc.proc_layout.as_ref().map_or_else(Default::default, |l| l.blobs.iter().map(|(b, off)| (b.hash, l.head.len() + off)).collect());- let slot = up.accel.as_ref().map_or(0, |a| a.proc_base + procs.len());- let room_base = (prep.tri_verts.len() / 3, gpu_instances.len(), tables.objects.len() / tables.stride, up.region_words, slot);- // A record's TLAS instance is `inst_base` + it (model instances, then procedural objects, then the room's).- debug_assert!(up.accel.as_ref().is_none_or(|a| room_base.4 == a.inst_base + room_base.1));+ // (A record's TLAS instance is at it: model instances, then procedural objects, then the room's.)+ let room_base = (prep.tri_verts.len() / 3, gpu_instances.len(), tables.objects.len() / tables.stride, up.region_words);let room = up.room;let mut users: std::collections::HashMap<u32, u32> = Default::default();for i in &instances {@@ -328,7 +303,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pbase: room_base,rows: Holes::new(rows.len(), rows.len() + room.records),row_runs: Default::default(),- pool_first: prep.groups.iter().sum(),blobs,// (The previous positions at the build: the vertices that move. No room: it grows with the first deforming// mesh an edit places.)@@ -337,5 +311,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pverts: Holes::new(vertices, vertices + room.tris * 3),free_skinned: vec![],};- 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(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, dynamic, edit, emit, mat_runs, tri_order, codes_sent }, view, env))+ Ok((LoadedScene { timings, triangles, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, edit, emit, codes_sent }, view, env))}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex 673d688..e28597c 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -356,11 +356,6 @@ pub struct LiveCore {kernel_bg: wgpu::BindGroup,/// The same for the translucency pass (`gpu::Gpu::tl_live_layout`; hardware traversal).tl_kernel_bg: Option<wgpu::BindGroup>,- /// Span (relative to the dynamic tail) re-transformed by the last in-place update whose previous-frame vertices- /// (`Uploaded::prev_verts`) still hold the frame before it: synced to the current ones next frame.- prev_span: Option<(usize, usize)>,- /// An in-place update happened this frame (it keeps `prev_verts` itself).- reposed: bool,/// Dynamic triangles moved in this commit: the light tree's moving subtree is refit once at its end.emitters_moved: bool,/// An instanced object's emitting copies changed size or were shown or hidden in this commit: the emitters are@@ -582,7 +577,7 @@ impl LiveCore {let mut core = LiveCore {kernel: None,more_features: Default::default(),- reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };+ reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, cache, kernel_bg, tl_kernel_bg, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);core.apply_post();Ok(core)@@ -669,7 +664,7 @@ impl LiveCore {}let Some(a) = up.accel.as_ref() else { return serde_json::Value::Null };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 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>();let mb = |b: f64| (b / (1 << 20) as f64 * 10.0).round() / 10.0;serde_json::json!({"tris": [e.tris.used(), e.tris.cap], "records": [e.records.used(), e.records.cap], "objects": [e.objects.used(), e.objects.cap],@@ -702,7 +697,6 @@ impl LiveCore {self.kernel = None;self.spark_lights = self.sc.tables.emitter_tris.iter().any(|e| e.nominal);self.inst_moving.clear();- self.prev_span = None;self.pose_spans.clear();self.emitters_moved = false;self.emitters_reweigh = false;@@ -1075,9 +1069,7 @@ impl LiveCore {}best};- let (mut t, i) = closest(&self.sc.tris, o, d);- let mut node = self.sc.tri_nodes.iter().find(|(_, a, b)| (*a as usize..*b as usize).contains(&i)).map(|n| n.0.as_str());- let mut sub = self.sc.tri_instances.iter().find(|(a, b, _)| (*a as usize..*b as usize).contains(&i)).map(|r| r.2);+ let (mut t, mut node, mut sub) = (f32::INFINITY, None, None);let mut posed = Default::default();for inst in self.sc.instances.iter().filter(|i| !i.hidden) {let m = self.sc.meshes[inst.mesh as usize];@@ -1121,8 +1113,7 @@ impl LiveCore {/// World-space triangles of a node (empty for lights without geometry, cameras, hidden nodes).pub fn node_tris(&self, id: &str) -> Vec<[glam::Vec3A; 3]> {- // World-space triangles (what the build flattened of an instance's mesh among them), then its instanced mesh.- let mut out: Vec<[glam::Vec3A; 3]> = scene::node_ranges(&self.sc.tri_nodes, id).flat_map(|r| self.sc.tris[r].iter().copied()).collect();+ let mut out = vec![];// A model's first instance; every drawn instance of an instanced object.let mut of_node = self.sc.instances.iter().filter(|i| i.name == id && !i.hidden);let first = of_node.next();@@ -1396,7 +1387,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.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, 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));diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rsindex d75f5c6..9e65812 100644--- a/renderer/src/ltree.rs+++ b/renderer/src/ltree.rs@@ -10,7 +10,7 @@//! triangle carries) x its weight / its leaf's, so a BSDF ray that hits it weighs its MIS by the same pmf. A node is one//! vec4 (one load per child visited): centre and radius as half floats, power, child word.//!-//! Moving emitters (dynamic triangles: a van's lights, a swinging lantern) have a subtree of their own: the root's+//! Moving emitters (a moving instance's: a van's lights, a swinging lantern) have a subtree of their own: the root's//! right child, the static emitters' subtree its left. They move, so their subtree is refit as they do//! (`refit_moving`: leaf spheres from their triangles now, then every node's from its children's), keeping its//! topology and so the codes their triangles carry. Particles (placed by a GPU pass) follow the tree's entries in thediff --git a/renderer/src/main.rs b/renderer/src/main.rsindex f24dcb6..6a2677c 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -269,9 +269,9 @@ fn main() -> Result<()> {let mut sc = scene::build(&w, &assets, &presets, None)?;let prep = threert_render::prepare_as(true, &mut sc, &mut vec![]);let prepare_ms = tb.elapsed().as_secs_f64() * 1000.0;- // Same counts the render stats report (scene.rs `stats`): flat + instanced triangles.- let triangles = sc.stats.get("triangles").map_or(sc.tris.len() as u64, |t| *t as u64);- println!("{}", serde_json::json!({ "engine": "quickjs", "bundle_load_ms": load_ms, "setup_ms": setup_ms, "prepare_ms": prepare_ms, "objects": w.objects.len(), "geometries": w.geometries.len(), "materials": w.materials.len(), "textures": w.textures.len(), "triangles": triangles, "flat_triangles": sc.tris.len(), "instances": sc.instances.len(), "instanced_triangles": sc.stats.get("instanced_triangles").copied().unwrap_or(0.0) as u64, "emitters": prep.emitter_tris.len(), "info": host.info }));+ // Same counts the render stats report (scene.rs `stats`).+ let triangles = sc.stats.get("triangles").map_or(0, |t| *t as u64);+ println!("{}", serde_json::json!({ "engine": "quickjs", "bundle_load_ms": load_ms, "setup_ms": setup_ms, "prepare_ms": prepare_ms, "objects": w.objects.len(), "geometries": w.geometries.len(), "materials": w.materials.len(), "textures": w.textures.len(), "triangles": triangles, "instances": sc.instances.len(), "instanced_triangles": sc.stats.get("instanced_triangles").copied().unwrap_or(0.0) as u64, "emitters": prep.emitter_tris.len(), "info": host.info }));}"edit-check" => {// threert-render edit-check <bundle.js> [--assets DIR] --events '[{"type":..,"payload":..}, ..]'@@ -520,7 +520,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.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, 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();@@ -589,8 +589,8 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos"scene": sc.name,"out": job.out,"width": w, "height": h, "spp": spp,- "triangles": sc.stats.get("triangles").map_or(sc.tris.len(), |t| *t as usize), "instances": sc.instances.len(), "meshes": sc.meshes.len(), "sections": sc.sections.len(), "rows": sc.rows.len(), "pool_triangles": sc.pool_tris.len(),- "instanced_triangles": sc.stats.get("instanced_triangles").copied().unwrap_or(0.0) as u64, "flat_triangles": sc.tris.len(), "bvh_nodes": prep.nodes.len(), "emitters": prep.emitter_tris.len(), "lights": sc.lights.len(), "textures": sc.textures.len(),+ "triangles": sc.stats.get("triangles").map_or(0, |t| *t as usize), "instances": sc.instances.len(), "meshes": sc.meshes.len(), "sections": sc.sections.len(), "rows": sc.rows.len(), "pool_triangles": sc.pool_tris.len(),+ "instanced_triangles": sc.stats.get("instanced_triangles").copied().unwrap_or(0.0) as u64, "bvh_nodes": prep.nodes.len(), "emitters": prep.emitter_tris.len(), "lights": sc.lights.len(), "textures": sc.textures.len(),"adapter": g.adapter_info.name, "backend": format!("{:?}", g.adapter_info.backend), "hwrt": g.hwrt,"ev100": ev100, "denoise": denoiser, "preset": preset.name,"samples_per_sec": (w * h) as f64 * spp as f64 / (trace_ms / 1000.0).max(1e-9),diff --git a/renderer/src/merged.rs b/renderer/src/merged.rsindex 6213db3..f7b2c75 100644--- a/renderer/src/merged.rs+++ b/renderer/src/merged.rs@@ -86,8 +86,8 @@ mod tests {let (m, info) = parse(&variant(0, false));let (used, declared) = storage_buffers(&m, &info);assert_eq!(declared, 22, "the kernel as written");- // (`main` no longer adds to the cache's sums: `finish` trains it.)- assert_eq!(used.iter().map(|u| u.1).max(), Some(21), "{used:?}");+ // (`main` no longer adds to the cache's sums: `finish` trains it. Without units it reads no node.)+ assert_eq!(used.iter().map(|u| u.1).max(), Some(20), "{used:?}");let hw = kernel_wgsl(&kernel_template(), &KernelVariant::new(true, Default::default(), 0));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] {@@ -97,7 +97,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 a page has (the trees' leaves the eighth)");+ let read = if features & crate::gpu::F_UNITS != 0 { 8 } else { 7 };+ assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(read), "the trace reads all eight a page has with units (the trees' leaves the eighth), no tree without");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));diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 0a4632c..88a6129 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -1,11 +1,11 @@-//! The engine's world (world.rs) + asset files -> flat GPU-ready scene (world-space triangles, materials, textures,+//! The engine's world (world.rs) + asset files -> GPU-ready scene (meshes and their instances, materials, textures,//! lights).use crate::desc::{self, Light, Sky};use crate::skin;use crate::world::{self, Kind, World};use anyhow::{anyhow, Context, Result};-use glam::{Mat3, Mat4, Vec2, Vec3, Vec3A};+use glam::{Mat4, Vec2, Vec3, Vec3A};use rayon::prelude::*;use std::collections::HashMap;use std::path::Path;@@ -18,8 +18,6 @@ pub const MAT_UNLIT: i32 = 4;pub const TRI_NO_SHADOW: u32 = 1;/// Alpha-tested triangle (cutout material): traversal runs an any-hit test.pub const TRI_MASKED: u32 = 2;-/// Triangle of a posed model (animated character): kept in its own acceleration structures, re-skinned in place.-pub const TRI_DYNAMIC: u32 = 4;/// vec4s per object in the objects table (pathtrace.wgsl `OBJECT_STRIDE`): (pivot, power), (bounds size, time of the/// last power edit), per-instance data (`custom`); in a scene with instance colours (`Scene::tinted`, the kernel's/// F_TINT) a 4th, (colour, -): an instanced object's instance colour (`InstanceTable`), white otherwise. Other scenes@@ -165,11 +163,6 @@ pub fn section_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMate.collect()}-/// Pool triangles of the deforming meshes, which the build puts first in the pool.-pub fn deforming_pool(meshes: &[InstMesh]) -> usize {- meshes.iter().filter(|m| m.deforms).map(|m| m.count as usize).sum()-}-impl InstMesh {/// Its BLAS geometries (`sections`: the scene's): one a section, its first triangle in the mesh and how many./// Every one is flagged opaque, whatever an instance's materials are (a query forces opacity; a cutout's and@@ -207,7 +200,7 @@ pub struct Instance {/// The scene node's id (picking, selection outlines).pub name: String,/// An instanced object's instance (`Kind::Instanced`): its index there (picking reports it), and whether it is- /// hidden (`instance_world`: TLAS mask 0, never flattened or picked).+ /// hidden (`instance_world`: TLAS mask 0, never picked).pub sub: Option<u32>,pub hidden: bool,/// Hidden by its object's visibility (`World::shown`) or for a placement without size (`placed_world`), which@@ -251,44 +244,16 @@ impl Instance {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, 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).- pub fn resolved(&self, a: &GpuTriAttr, rows: &[Row]) -> GpuTriAttr {- let mat = rows.get(a.uv[3].to_bits() as usize).map_or(0, row_material);- GpuTriAttr { uv: [a.uv[0], a.uv[1], a.uv[2], f32::from_bits(mat)], x: [a.x[0], a.x[1], a.x[2], 0.0], ..*a }- }- /// Model-space triangle `t` of its mesh in world space (the same transform the flattening path applies).+ /// Model-space triangle `t` of its mesh in world space.pub fn tri(&self, t: &[Vec3A; 3]) -> [Vec3A; 3] {t.map(|v| self.world.transform_point3a(v))}- /// A triangle of its mesh (vertices `t`, attributes `a`, vertex colours `c`) as flattening has it: in world space- /// (`tri`, `instance_attr`), and under a mirroring instance with its second and third vertex changed places, so- /// that it faces as the mesh's does (as `append_arrays` flattens a mirrored placement).- pub fn flat(&self, t: &[Vec3A; 3], a: &GpuTriAttr, c: Option<[u32; 3]>) -> ([Vec3A; 3], GpuTriAttr, Option<[u32; 3]>) {- let (w, b) = (self.tri(t), instance_attr(a, self.world, self.object));- if !mirrors(self.world) {- return (w, b, c);- }- // (The UVs are packed along the normals: uv0 in n0.w n1.w, uv1 in n2.w uv.x, uv2 in uv.y uv.z.)- let swapped = GpuTriAttr { n1: [b.n2[0], b.n2[1], b.n2[2], b.n1[3]], n2: [b.n1[0], b.n1[1], b.n1[2], b.uv[1]], uv: [b.uv[2], b.n2[3], b.uv[0], b.uv[3]], t1: b.t2, t2: b.t1, ..b };- ([w[0], w[2], w[1]], swapped, c.map(|c| [c[0], c[2], c[1]]))- }}/// A triangle's tangents, one a corner: the direction of u on the surface and the frame's hand (1 or -1). A file's,/// or generated (tangents.rs); a triangle without has none (`GpuTriAttr::t`'s hand is 0).pub type CornerTangents = [(Vec3, f32); 3];-/// A triangle in a node's own space (vertices, normals, UVs, tangents) placed by `w` as the build flattens it: under-/// a mirroring `w` the second and third vertex change places, so that it faces as its mesh does, and its tangents'-/// frame changes hand (`Instance::flat` does the same with a mesh's triangle).-#[allow(clippy::type_complexity)]-pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent: Option<CornerTangents>) -> ([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>) {- let nm = Mat3::from_mat4(w).inverse().transpose();- let (k, hand) = if mirrors(w) { ([0, 2, 1], -1.0) } else { ([0, 1, 2], 1.0) };- (k.map(|i| w.transform_point3(p[i])), k.map(|i| (nm * n[i]).normalize_or_zero()), k.map(|i| uv[i]), tangent.map(|t| k.map(|i| (w.transform_vector3(t[i].0).normalize_or_zero(), t[i].1 * hand))))-}-/// Bit of an instance record's n1.w, beside the units' flags there (units.rs `UNIT_*`): the instance mirrors its mesh/// (the kernel's `inst_sign`).pub const INST_MIRRORED: u32 = 4;@@ -511,37 +476,6 @@ pub fn proc_layout(procs: &[ProcObject], sw: bool) -> ProcLayout {ProcLayout { head, headers, blobs, blob_of, blob_words, sw }}-/// Flags of an instance's pool triangle as a world-space triangle (software traversal): the placement's shadow flag,-/// the material's cutout, and no shadow for glass (the build's flag pass ran before the instances were flattened).-pub fn instance_tri_flags(inst: &Instance, a: &GpuTriAttr, materials: &[GpuMaterial]) -> u32 {- let m = materials.get(a.uv[3].to_bits() as usize);- let shadow = if inst.cast_shadow && !m.is_some_and(|m| m.layer[0] > 0.0) { 0 } else { TRI_NO_SHADOW };- shadow | if m.is_some_and(|m| m.uv2[3] > 0.0) { TRI_MASKED } else { 0 }-}--/// Triangle ranges of node `id` in build order: one, or two for an instanced node flattened by software traversal (its-/// glass / function part from the build, its mesh appended by `prepare`).-pub fn node_ranges<'a>(tri_nodes: &'a [(String, u32, u32)], id: &'a str) -> impl Iterator<Item = std::ops::Range<usize>> + 'a {- tri_nodes.iter().filter(move |(n, _, _)| n == id).map(|(_, a, b)| *a as usize..*b as usize)-}--/// Model-space shading attributes of a pool triangle placed by `w` (normals by the inverse transpose, tangents by-/// the matrix, their frame's hand changed by a mirroring one), object `object`.-pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr {- let m3 = glam::Mat3::from_mat4(w);- let nm = m3.inverse().transpose();- let n = |v: [f32; 4]| {- let r = (nm * Vec3::new(v[0], v[1], v[2])).normalize_or_zero();- [r.x, r.y, r.z, v[3]]- };- let flip = if mirrors(w) { -1.0 } else { 1.0 };- let t = |v: [f32; 4]| {- let r = (m3 * Vec3::new(v[0], v[1], v[2])).normalize_or_zero();- [r.x, r.y, r.z, v[3] * flip]- };- GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: t(a.t), x: [a.x[0], f32::from_bits(object), a.x[2], a.x[3]], t1: t(a.t1), t2: t(a.t2) }-}-#[repr(C)]#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]pub struct GpuTriAttr {@@ -670,15 +604,13 @@ pub struct Scene {pub time: f32,pub width: u32,pub height: u32,- pub tris: Vec<[Vec3A; 3]>,- pub tri_flags: Vec<u32>,- /// Vertex colours (`tri_colors`) of the triangles in `tris` and `pool_tris` whose material has `vertexColors`, by- /// index (shorter: white past the end); `prepare` lays them out as the GPU's triangles (F_VCOLOR).- pub vcolors: Vec<[u32; 3]>,+ /// Vertex colours (`tri_colors`) of the triangles in `pool_tris` whose material has `vertexColors`, by index+ /// (shorter: white past the end); `prepare` lays them out as the GPU's triangles (F_VCOLOR).pub pool_vcolors: Vec<[u32; 3]>,/// The vertex colours as the GPU reads them (`prepare`): three words per triangle in GPU order, none in a scene/// without them (gpu.rs F_VCOLOR).pub gpu_vcolors: Vec<u32>,+ /// The triangles' attributes in the GPU's order (`prepare`: `pool_attrs`, as the trees left them).pub attrs: Vec<GpuTriAttr>,pub materials: Vec<GpuMaterial>,pub textures: Vec<Texture>,@@ -689,15 +621,10 @@ pub struct Scene {pub environment: EnvSettings,pub preset: desc::Preset,pub stats: HashMap<&'static str, f64>,- /// Triangle ranges per object (name, first, end), in `tris` order: picking and selection outlines.- pub tri_nodes: Vec<(String, u32, u32)>,- /// Triangle ranges of flattened instances of instanced objects (first, end, instance index): picking.- pub tri_instances: Vec<(u32, u32, u32)>,/// Some object has instance colours (`InstanceTable::colors`): the kernel's F_TINT, 4 vec4s an object/// (`object_stride`).pub tinted: bool,- /// Instanced static glTF meshes (model-space triangles, flags, attributes) and their placements. `prepare` appends- /// the pool after the flattened triangles (hardware RT) or flattens the instances (software traversal).+ /// The meshes (model-space triangles, attributes), one after another, and their placements.pub pool_tris: Vec<[Vec3A; 3]>,pub pool_attrs: Vec<GpuTriAttr>,pub meshes: Vec<InstMesh>,@@ -820,7 +747,7 @@ pub struct Retained {#[derive(Clone, Default)]pub struct Proxy {/// Object-table index (pivot, bounds, power, customData). None: an instanced object (an entry a copy: from- /// `InstancedPlace::object` for instances; a flattened one's are the build's alone).+ /// `InstancedPlace::object`).pub object: Option<u32>,/// A rect light's visible card: its material.pub card: Option<u32>,@@ -830,13 +757,10 @@ pub struct Proxy {/// How a drawn object's geometry is held.#[derive(Clone, Default)]pub enum Draw {- /// As the build placed it, with nothing kept to change it by: triangles flattened into the static groups, a- /// static model's instance. An edit that would change it rebuilds.+ /// As the build placed it, with nothing kept to change it by: a static model's instances. An edit that would+ /// change it rebuilds.#[default]Fixed,- /// World-space triangles in the dynamic groups, re-transformed (a movable object) or re-skinned (a posed model)- /// on the CPU.- Dynamic(DynamicModel),/// An instance of a model-space mesh (hardware RT, or software traversal's units).Instance(InstanceRef),/// Procedural geometry: its index in `procs` (its record less the first procedural record).@@ -933,13 +857,6 @@ impl Retained {self.edits_meshes}- /// The triangles re-transformed on the CPU: the dynamic objects' and the rigid models' flattened ones.- pub fn dynamics_mut(&mut self) -> impl Iterator<Item = &mut DynamicModel> {- self.proxies.values_mut().filter_map(|p| match &mut p.draw {- Draw::Dynamic(d) => Some(d),- _ => None,- })- }}/// Where an instanced object's instances are: `capacity` of them from `first` in `instances` (instances of `mesh`) or@@ -1159,18 +1076,6 @@ pub struct GpuParticleSystem {pub collide: world::ParticleCollide,}-/// A dynamic object's triangles (a posed model's, or a movable mesh's or model's the build flattened): their range in build order,-/// and per triangle the material and flags.-#[derive(Clone, Default)]-pub struct DynamicModel {- pub first: u32,- pub mats: Vec<u32>,- pub flags: Vec<u32>,- pub object: u32,- /// Index of each triangle in the GPU triangle order (`prepare`; empty without hardware RT).- pub finals: Vec<u32>,-}-struct TexCache {textures: Vec<Texture>,by_key: HashMap<(String, bool), i32>,@@ -1650,13 +1555,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sematerials.push(gm);}- let tris: Vec<[Vec3A; 3]> = vec![];- let mut tri_flags: Vec<u32> = vec![];- let mut attrs: Vec<GpuTriAttr> = vec![];let mut lights: Vec<GpuLight> = vec![];let mut camera: Option<CameraData> = None;let mut asset_materials: HashMap<(String, usize), u32> = HashMap::new();- let mut tri_nodes: Vec<(String, u32, u32)> = vec![];let mut particles: Vec<ParticleSystem> = vec![];let mut gpu_particles: Vec<GpuParticleSystem> = vec![];let particle_programs: Vec<(String, String, String, String)> = w.particle_programs.iter().map(|(k, (e, u, h))| (k.clone(), e.clone(), u.clone(), h.clone())).collect();@@ -1672,7 +1573,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet grid_programs: Vec<(String, String, String)> = w.grid_programs.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();let mut objects: Vec<[f32; 4]> = vec![];let mut pool_tris: Vec<[Vec3A; 3]> = vec![];- let (vcolors, mut pool_vcolors): (Vec<[u32; 3]>, Vec<[u32; 3]>) = (vec![], vec![]);+ let mut pool_vcolors: Vec<[u32; 3]> = vec![];let mut pool_attrs: Vec<GpuTriAttr> = vec![];let mut meshes: Vec<InstMesh> = vec![];let mut instances: Vec<Instance> = vec![];@@ -1697,8 +1598,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet mut skin_sources: Vec<Vec<[skin::SkinCorner; 3]>> = vec![];let mut skin_rest: Vec<Vec<skin::PaletteRows>> = vec![];let mut skin_source_of: HashMap<(String, Option<Vec<String>>, Vec<bool>), (u32, Arc<Vec<(u32, u32, u32)>>)> = HashMap::new();- // Flattened instances' triangle ranges.- let tri_instances: Vec<(u32, u32, u32)> = vec![];// The rect lights' card mesh, once a scene has a card (`card_mesh`).let mut card: Option<u32> = None;// Instance colours anywhere: object entries of 4 vec4s, and the kernel's F_TINT.@@ -1707,7 +1606,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sefor id in &order {let n = &w.objects[id];let m = worlds[id];- let first = tris.len() as u32;let shown = w.shown(*id);match &n.kind {Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } => {@@ -2155,30 +2053,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seKind::Camera(c) if st.camera == Some(*id) => camera = Some(camera_data(m, c)),_ => {}}- if tris.len() as u32 > first && !matches!(n.kind, Kind::Instanced { .. }) {- // Object pivot + world bounds (UE ObjectPositionWS / ObjectBounds) for material functions, and the object's- // power (scales everything it emits).- let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));- for t in &tris[first as usize..] {- for v in t {- lo = lo.min(*v);- hi = hi.max(*v);- }- }- let pivot = m.transform_point3(Vec3::ZERO);- let size = hi - lo;- let oi = (objects.len() / stride) as u32;- objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);- for a in &mut attrs[first as usize..] {- a.x[1] = f32::from_bits(oi);- }- let proxy = retained.proxy(*id);- proxy.object = Some(oi);- if let Draw::Dynamic(d) = &mut proxy.draw {- d.object = oi;- }- tri_nodes.push((n.name.clone(), first, tris.len() as u32));- }}let (sky, sun) = sky_data(w, assets, &|id| worlds.get(&id).copied().unwrap_or(Mat4::IDENTITY))?;@@ -2187,11 +2061,11 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet mut stats = HashMap::new();stats.insert("load_ms", t0.elapsed().as_secs_f64() * 1000.0);let instanced: u64 = instances.iter().map(|i| meshes[i.mesh as usize].count as u64).sum();- stats.insert("triangles", (tris.len() as u64 + instanced) as f64);+ stats.insert("triangles", instanced as f64);stats.insert("instances", instances.len() as f64);stats.insert("instanced_triangles", instanced as f64);- // Deforming meshes (posed skinned models') first in the pool: the previous frame's vertices (`prev_verts`, motion vectors)- // cover the dynamic tail and, right after it, them.+ // Deforming meshes (posed skinned models') first in the pool: the previous frame's vertices (`prev_verts`, motion+ // vectors) cover them.if meshes.iter().any(|m| m.deforms) {let (mut pt, mut pa) = (Vec::with_capacity(pool_tris.len()), Vec::with_capacity(pool_attrs.len()));let mut pv = vec![];@@ -2211,21 +2085,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sepool_vcolors = pv;}}- stats.insert("unique_triangles", (tris.len() + pool_tris.len()) as f64);- // Cutout materials: their triangles take the any-hit path in traversal. Glass casts no shadow of its own: what a- // shadow ray keeps past it is the kernel's (`glass_tr`; in full with `A_GLASS_SHADOWS`).- for (f, a) in tri_flags.iter_mut().zip(&attrs) {- let m = &materials[a.uv[3].to_bits() as usize];- if m.uv2[3] > 0.0 {- *f |= TRI_MASKED;- }- if m.layer[0] > 0.0 {- *f |= TRI_NO_SHADOW;- }- }- for d in retained.dynamics_mut() {- d.flags = tri_flags[d.first as usize..d.first as usize + d.mats.len()].to_vec();- }+ stats.insert("unique_triangles", pool_tris.len() as f64);retained.asset_materials = asset_materials;Ok(Scene {name: st.name.clone(),@@ -2235,12 +2095,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&setime: st.time,width: st.width,height: st.height,- tris,- vcolors,pool_vcolors,gpu_vcolors: vec![],- tri_flags,- attrs,+ attrs: vec![],materials,textures: texcache.textures,lights,@@ -2249,8 +2106,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seenvironment: EnvSettings::of(w),preset,stats,- tri_nodes,- tri_instances,tinted,retained,particles,@@ -2404,34 +2259,6 @@ pub fn drawn_world(w: &World, node: u32) -> Mat4 {}}-/// A dynamic object's triangles at its current transform / pose, with their shading attributes (materials as built):-/// what an in-place update writes. None: it no longer matches its build (a different kind).-pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Result<Option<Vec<([Vec3; 3], GpuTriAttr)>>> {- let Some(o) = w.objects.get(&id) else { return Ok(None) };- let m = w.world_matrix(id);- Ok(match &o.kind {- Kind::Mesh { geometry, materials, .. } => {- let Some(g) = w.geometries.get(geometry) else { return Ok(None) };- let (mut tris, mut flags, mut attrs) = (vec![], vec![], vec![]);- // The triangles the build drew (groups' only, with several materials), each with the material it had.- let drawn = group_materials(g, &vec![0; materials.len()]);- append_arrays(g, m, 0, 0, drawn.as_deref(), &mut tris, &mut flags, &mut attrs);- for (k, a) in attrs.iter_mut().enumerate() {- a.uv[3] = f32::from_bits(d.mats.get(k).copied().unwrap_or(0));- }- Some(tris.iter().zip(attrs).map(|(t, a)| (t.map(Vec3::from), a)).collect())- }- Kind::Model { uri, nodes, animation, .. } => {- let tris = model_gltf(uri, assets)?.triangles(m, nodes.as_deref(), animation.as_ref())?;- if tris.len() != d.mats.len() {- return Ok(None);- }- Some(tris.iter().zip(&d.mats).map(|(t, &mat)| (t.p, tri_attr(t.n, t.uv, t.tangent, mat))).collect())- }- _ => None,- })-}-/// A model's triangles by class (`classed`: opaque, cutout, glass; each a triangle's index and material): those that/// lie on exactly another's vertices leave the mesh, in two cases: a cutout on a triangle that emits (a material of/// `emitting`; Zero Day: masked decals over emissive quads of the same shape), and glass on an opaque triangle or@@ -2574,8 +2401,8 @@ pub fn section_mesh(g: &world::Geometry, grouped: bool, first: u32, sect_first:}}}- let (mut t, mut flags, mut a) = (vec![], vec![], vec![]);- append_arrays(g, Mat4::IDENTITY, 0, 0, Some(&group), &mut t, &mut flags, &mut a);+ let (mut t, mut a) = (vec![], vec![]);+ append_arrays(g, Mat4::IDENTITY, 0, Some(&group), &mut t, &mut a);// (`append_arrays` left each triangle's group where its material goes.)let group_of = |k: usize| a[k].uv[3].to_bits();let mut order: Vec<usize> = (0..t.len()).collect();@@ -2750,8 +2577,7 @@ pub fn group_materials(g: &world::Geometry, mats: &[u32]) -> Option<Vec<Option<u}/// A geometry's triangles at `world`, with `mat`, or per triangle `per_tri`'s (`group_materials`: None not drawn).-#[allow(clippy::too_many_arguments)]-fn append_arrays(g: &world::Geometry, world: Mat4, mat: u32, flags: u32, per_tri: Option<&[Option<u32>]>, tris: &mut Vec<[Vec3A; 3]>, tri_flags: &mut Vec<u32>, attrs: &mut Vec<GpuTriAttr>) {+fn append_arrays(g: &world::Geometry, world: Mat4, mat: u32, per_tri: Option<&[Option<u32>]>, tris: &mut Vec<[Vec3A; 3]>, attrs: &mut Vec<GpuTriAttr>) {let nm = glam::Mat3::from_mat4(world).inverse().transpose();let mirrored = world.determinant() < 0.0;let p = |i: usize| world.transform_point3(Vec3::new(g.positions[i * 3], g.positions[i * 3 + 1], g.positions[i * 3 + 2]));@@ -2776,27 +2602,11 @@ fn append_arrays(g: &world::Geometry, world: Mat4, mat: u32, flags: u32, per_tri*v = gn;}}- push_tri(tris, tri_flags, attrs, pos, nrm, [uv(a), uv(b), uv(c)], None, mat, flags);+ tris.push([pos[0].into(), pos[1].into(), pos[2].into()]);+ attrs.push(tri_attr(nrm, [uv(a), uv(b), uv(c)], None, mat));}}-#[allow(clippy::too_many_arguments)]-fn push_tri(- tris: &mut Vec<[Vec3A; 3]>,- tri_flags: &mut Vec<u32>,- attrs: &mut Vec<GpuTriAttr>,- p: [Vec3; 3],- n: [Vec3; 3],- uv: [Vec2; 3],- tangent: Option<CornerTangents>,- mat: u32,- flags: u32,-) {- tris.push([p[0].into(), p[1].into(), p[2].into()]);- tri_flags.push(flags);- attrs.push(tri_attr(n, uv, tangent, mat));-}-/// Shading attributes of a triangle: normals, UVs, its tangents if it has them, its material.pub fn tri_attr(n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<CornerTangents>, mat: u32) -> GpuTriAttr {let t = |c: usize| tangent.map_or([0.0; 4], |t| [t[c].0.x, t[c].0.y, t[c].0.z, t[c].1]);@@ -2918,68 +2728,6 @@ mod instance_tests {assert_eq!(texture_image(&tex(0), assets).unwrap().0, kb);}- /// An instance's placed triangle and attributes equal flattening the same triangle at the instance transform: as- /// the flattening path has them (`Instance::flat`) against the triangle built in world space as `append_arrays`- /// builds it, under a transform that keeps the hand and under one that mirrors (the second and third vertex- /// change places, the tangent frame changes hand), with distinct normals, UVs, tangents and vertex colours a- /// vertex.- #[test]- fn instance_matches_flattening() {- let p = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.5, 0.2)];- let n = [Vec3::new(0.0, -0.37, 0.93).normalize(), Vec3::new(0.1, -0.3, 0.9).normalize(), Vec3::new(-0.2, -0.4, 0.8).normalize()];- let uv = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.25), Vec2::new(0.5, 1.0)];- let colors = [1, 2, 3];- let keeps = Mat4::from_scale_rotation_translation(Vec3::splat(2.0), glam::Quat::from_rotation_y(0.7) * glam::Quat::from_rotation_x(-0.3), Vec3::new(5.0, 1.0, -3.0));- let tg = [(Vec3::new(1.0, 0.1, 0.0).normalize(), 1.0), (Vec3::new(0.9, 0.0, 0.3).normalize(), 1.0), (Vec3::new(0.8, -0.2, 0.1).normalize(), 1.0)];- let local = tri_attr(n, uv, Some(tg), 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, 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.- let order = if mirrored { [0, 2, 1] } else { [0, 1, 2] };- let nm = glam::Mat3::from_mat4(w).inverse().transpose();- let wp = order.map(|k| w.transform_point3(p[k]));- let hand = if mirrored { -1.0 } else { 1.0 };- let flat = tri_attr(order.map(|k| (nm * n[k]).normalize()), order.map(|k| uv[k]), Some(order.map(|k| (w.transform_vector3(tg[k].0).normalize(), tg[k].1 * hand))), 7);- for k in 0..3 {- assert!((Vec3::from(placed[k]) - wp[k]).length() < 1e-5, "mirrored {mirrored}: vertex {k}");- }- assert!((placed[1] - placed[0]).cross(placed[2] - placed[0]).dot(Vec3A::from(nm * n[0])) > 0.0, "mirrored {mirrored}: it faces as its normals do");- for (a, b) in [(got.n0, flat.n0), (got.n1, flat.n1), (got.n2, flat.n2), (got.t, flat.t), (got.t1, flat.t1), (got.t2, flat.t2)] {- assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5, "mirrored {mirrored}: {a:?} vs {b:?}");- assert_eq!(a[3], b[3], "mirrored {mirrored}: the UV packed there, the tangent frame's hand");- }- assert_eq!(got.uv, flat.uv, "mirrored {mirrored}");- // (`placed_tri` places a triangle the same way.)- let (_, pn, puv, ptg) = placed_tri(w, &p, &n, &uv, Some(tg));- let by = tri_attr(pn, puv, ptg, 7);- for (a, b) in [(by.n0, flat.n0), (by.n1, flat.n1), (by.n2, flat.n2), (by.t, flat.t), (by.t1, flat.t1), (by.t2, flat.t2)] {- assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5 && a[3] == b[3], "mirrored {mirrored}, placed_tri: {a:?} vs {b:?}");- }- assert_eq!(got_colors, Some(order.map(|k| colors[k])), "mirrored {mirrored}: the vertex colours follow their vertices");- assert_eq!(got.x[1].to_bits(), 3);- }- }-- /// Software traversal flattens instances: a cutout material's triangles keep TRI_MASKED (any-hit alpha test),- /// the placement's shadow flag applies to all.- #[test]- fn flattened_instance_keeps_cutout_flag() {- let opaque = GpuMaterial::default();- let mut cutout = GpuMaterial::default();- cutout.uv2[3] = 0.5;- let mats = [opaque, cutout];- let a = |m: u32| tri_attr([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, 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);- }-- /// A node's triangles may come in two ranges (what the build flattened of an instance's mesh, the mesh appended- /// by software traversal): selection outlines need both./// An instanced object: one shared mesh, an instance and an object entry per copy (capacity, not count), hidden/// past the count and where a matrix scales to 0; a copy may mirror the mesh.#[test]@@ -2995,7 +2743,7 @@ mod instance_tests {let m = [Mat4::IDENTITY, Mat4::from_translation(Vec3::X), Mat4::from_scale(Vec3::ZERO), Mat4::from_translation(Vec3::Y)];w.set_instances(2, 3, Some(m.iter().flat_map(|m| m.to_cols_array()).collect()), Some(vec![0.5; 12]), None).unwrap();let sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.meshes.len(), sc.instances.len(), sc.tris.len(), sc.objects.len() / 4), (1, 4, 0, 4), "tinted: 4 vec4s an object");+ assert_eq!((sc.meshes.len(), sc.instances.len(), sc.objects.len() / 4), (1, 4, 4), "tinted: 4 vec4s an object");assert_eq!(sc.instances.iter().map(|i| (i.sub, i.hidden)).collect::<Vec<_>>(), vec![(Some(0), false), (Some(1), false), (Some(2), true), (Some(3), true)]);assert_eq!((sc.objects[4][0], sc.objects[4 + 3]), (1.0, [0.5, 0.5, 0.5, 0.0]));assert!(sc.tinted && sc.retained.instanced(2).unwrap().capacity == 4);@@ -3003,14 +2751,14 @@ mod instance_tests {m[0] = -1.0;w.set_instances(2, 3, Some(m), None, None).unwrap();let sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.instances.len(), sc.tris.len()), (4, 0), "a copy that mirrors the mesh is an instance as the others");+ assert_eq!(sc.instances.len(), 4, "a copy that mirrors the mesh is an instance as the others");assert_eq!(sc.instances.iter().map(|i| i.gpu(0).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED, 0, 0, 0], "and its record says so");}/// A visible rect light's card is an instance of one card mesh: the lights share the mesh, each instance has its/// light's size and place, its material in its row, and casts no shadow; its two triangles stand 1 mm in front of/// the light, facing where it shines, and are its emitters, marked as a card's. A light without size has an- /// instance no ray sees. No world-space triangle. No GPU.+ /// instance no ray sees. No GPU.#[test]fn a_rect_lights_card_is_an_instance_of_the_card_mesh() {let mut w = World::default();@@ -3024,7 +2772,7 @@ mod instance_tests {w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();w.set_settings(world::Settings { camera: Some(9), ..Default::default() });let mut sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.tris.len(), sc.meshes.len(), sc.instances.len(), sc.lights.len()), (0, 1, 3, 0), "one mesh, an instance a card, no table light");+ assert_eq!((sc.meshes.len(), sc.instances.len(), sc.lights.len()), (1, 3, 0), "one mesh, an instance a card, no table light");let m = sc.meshes[0];assert_eq!((m.count, m.sect_count, m.deforms), (2, 1, false));let inst = |id: u32| sc.instances[sc.retained.instance(id).expect("a card is an instance").instance as usize].clone();@@ -3065,7 +2813,7 @@ mod instance_tests {let m = [Mat4::from_scale(Vec3::splat(2.0)), Mat4::from_translation(Vec3::X), Mat4::from_scale(Vec3::ZERO), Mat4::from_translation(Vec3::Y)];w.set_instances(2, 3, Some(m.iter().flat_map(|m| m.to_cols_array()).collect()), None, None).unwrap();let mut sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.meshes.len(), sc.meshes[0].sect_count, sc.instances.len(), sc.tris.len()), (1, 1, 4, 0));+ assert_eq!((sc.meshes.len(), sc.meshes[0].sect_count, sc.instances.len()), (1, 1, 4));assert_eq!(sc.instances.iter().map(|i| (i.rows, i.bits)).collect::<Vec<_>>(), [(0, 0), (1, 0), (2, 0), (3, 0)], "a row a copy");let (st, first) = (sc.object_stride(), sc.retained.instanced(2).unwrap().object as usize);assert_eq!((0..4).map(|i| sc.objects[(first + i) * st][3]).collect::<Vec<_>>(), [2.0, 2.0, 0.0, 0.0], "a hidden copy's entry has no power");@@ -3100,12 +2848,12 @@ mod instance_tests {let meshes = |sc: &Scene| sc.meshes.iter().map(|m| (m.first, m.count, m.sect_count, m.over)).collect::<Vec<_>>();assert_eq!(meshes(&mirrored), meshes(&straight));assert_eq!(mirrored.pool_tris, straight.pool_tris, "the meshes' triangles are the model's own, whatever places them");- assert_eq!((mirrored.instances.len(), mirrored.tris.len()), (straight.instances.len(), straight.tris.len()));+ assert_eq!(mirrored.instances.len(), straight.instances.len());assert_eq!((&mirrored.sections, &mirrored.rows), (&straight.sections, &straight.rows), "and their sections and rows");assert!(straight.instances.len() >= 2 && straight.instances.iter().all(|i| i.gpu(0).n[1][3].to_bits() & INST_MIRRORED == 0));assert!(mirrored.instances.iter().all(|i| i.gpu(0).n[1][3].to_bits() & INST_MIRRORED != 0), "every instance of a mirrored model mirrors");// (The cutout on an emitter: a mesh apart, a still model's and a moving node's, an instance each.)- assert!(straight.tris.is_empty() && straight.meshes.iter().filter(|m| m.over != NO_OVER).count() == 2 && straight.instances.len() == 4);+ assert!(straight.meshes.iter().filter(|m| m.over != NO_OVER).count() == 2 && straight.instances.len() == 4);}/// A mesh of a geometry drawn by its groups lies by section, a group after another: a triangle in no group is not@@ -3173,7 +2921,7 @@ mod instance_tests {}/// A model's mesh lies by section, a section a material of the file (tests/render/data/frame-pane.glb: an opaque,- /// a cutout and a glass quad; placed twice): one mesh of three sections, nothing flattened. Each instance has its+ /// a cutout and a glass quad; placed twice): one mesh of three sections. Each instance has its/// three rows, with the classes, and casts (not all of it is glass); its record has the rows' first, a row where/// its section's triangles start; the kernel's features for a cutout and for glass among other sections are set.#[test]@@ -3188,7 +2936,7 @@ mod instance_tests {}let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.over)).collect::<Vec<_>>(), [(6, 3, NO_OVER)]);- assert_eq!((sc.instances.len(), sc.tris.len()), (2, 0));+ assert_eq!(sc.instances.len(), 2);assert_eq!(sc.meshes[0].parts(&sc.sections), [(0, 2), (2, 2), (4, 2)], "a geometry a section");assert_eq!(sc.pool_attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)], "a triangle's section and its index in it");assert_eq!(sc.instances.iter().map(|i| (i.rows, i.bits, i.cast_shadow)).collect::<Vec<_>>(), [(0, INST_CUTOUT | INST_GLASS, true), (3, INST_CUTOUT | INST_GLASS, true)], "rows of its own an instance");@@ -3214,7 +2962,7 @@ mod instance_tests {}/// A model placed without size (scene code hides by scaling to 0) is an instance no ray sees, of the model's- /// mesh, as one with a size is: nothing of it is a world-space triangle, and its object has no power.+ /// mesh, as one with a size is, and its object has no power.#[test]fn a_model_without_size_is_an_instance_no_ray_sees() {let mut w = World::default();@@ -3226,7 +2974,7 @@ mod instance_tests {w.set_transform(id, Vec3::new(id as f32 * 5.0, 0.0, 0.0), glam::Quat::IDENTITY, scale).unwrap();}let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.tris.len(), sc.meshes.len(), sc.instances.len()), (0, 1, 3), "one mesh, an instance a placement");+ assert_eq!((sc.meshes.len(), sc.instances.len()), (1, 3), "one mesh, an instance a placement");assert_eq!(sc.instances.iter().map(|i| (i.hidden, i.masked)).collect::<Vec<_>>(), [(false, false), (true, true), (true, true)]);assert!(sc.instances.iter().all(|i| i.world.is_finite() && glam::Mat3::from_mat4(i.world).determinant() != 0.0), "each stands somewhere");let power = |id: u32| sc.objects[sc.retained.proxies[&id].object.unwrap() as usize * object_stride(sc.tinted)][3];@@ -3236,7 +2984,7 @@ mod instance_tests {/// A posed skinned model's triangles that emit stay in its mesh (tests/render/data/arm-glow.glb: arm.glb with its/// light half emitting, and a clip, `vanish`, that scales its tip joint from nothing to its size): the model is an instance of a mesh that deforms, and they are its instance's emitters,- /// moving ones, each its mesh's triangle as the instance places it. Nothing is a world-space triangle. One placed+ /// moving ones, each its mesh's triangle as the instance places it. One placed/// without size is an instance no ray sees. No GPU.#[test]fn a_posed_skinned_models_emitters_are_its_instances() {@@ -3250,7 +2998,7 @@ mod instance_tests {w.set_transform(id, Vec3::new(id as f32 * 3.0, 0.5, -1.0), glam::Quat::from_rotation_y(0.4), Vec3::splat(scale)).unwrap();}let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();- assert_eq!((sc.tris.len(), sc.instances.len(), sc.retained.skinned.len()), (0, 2, 2), "an instance a model, of a mesh of its own");+ assert_eq!((sc.instances.len(), sc.retained.skinned.len()), (2, 2), "an instance a model, of a mesh of its own");assert!(sc.meshes.iter().all(|m| m.deforms) && sc.instances.iter().map(|i| (i.hidden, i.masked)).collect::<Vec<_>>() == [(false, false), (true, true)]);let power = |id: u32| sc.objects[sc.retained.proxies[&id].object.unwrap() as usize * object_stride(sc.tinted)][3];assert_eq!([power(1), power(2)], [1.0, 0.0], "the unseen one's object has no power");@@ -3286,7 +3034,7 @@ mod instance_tests {build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap()};let (with, without) = (scene("arm-glow-decal.glb"), scene("arm-glow.glb"));- assert_eq!((with.tris.len(), with.meshes.len(), with.instances.len()), (0, 1, 1));+ assert_eq!((with.meshes.len(), with.instances.len()), (1, 1));assert_eq!(with.pool_tris, without.pool_tris, "the mesh's triangles: the model's without the cutout's");let classes = |sc: &Scene| sc.rows.iter().map(|r| r[0] & (ROW_CUTOUT | ROW_GLASS)).collect::<Vec<_>>();assert_eq!((classes(&with), with.sections.clone()), (classes(&without), without.sections.clone()), "no section is a cutout's");@@ -3298,7 +3046,7 @@ mod instance_tests {/// A cutout on exactly an emitter's vertices leaves the mesh for the model's second one (`split_coincident`), in a/// model that stays and in a rigid model's moving node (tests/render/data/panel-decal.glb: panel.glb, a grey quad/// and an emitting one, with a masked quad on the emitting one's vertices): the emitter stays in its mesh, the- /// cutout is a mesh apart with an instance beside the first's, and nothing is a world-space triangle.+ /// cutout is a mesh apart with an instance beside the first's.#[test]fn a_cutout_on_an_emitter_is_the_models_second_mesh() {let mut w = World::default();@@ -3310,7 +3058,6 @@ mod instance_tests {w.set_transform(1, Vec3::new(3.0, 1.0, -2.0), glam::Quat::from_rotation_y(0.5), Vec3::splat(1.5)).unwrap();w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() })), true, false).unwrap();let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();- assert_eq!(sc.tris.len(), 0, "no world-space triangle");// An object's instances: (triangles of the mesh, whether it has a second mesh, the instance's emitters, its rows' classes).let of = |name: &str| {sc.instances@@ -3336,7 +3083,7 @@ mod instance_tests {/// A posed rigid model is its parts (tests/render/data/panel-slider.glb: a node its clip leaves alone, a grey quad/// and an emitting one, and a node it moves, a grey quad): the nodes left alone one mesh in the model's space,/// the moved node a mesh in its own, both shared by the placements of the model with the clip, whatever its time.- /// Nothing is flattened. The part left alone's emitters are still ones, movable object or not.+ /// The part left alone's emitters are still ones, movable object or not.#[test]fn a_posed_rigid_model_is_instances_of_its_parts_meshes() {let mut w = World::default();@@ -3351,7 +3098,7 @@ mod instance_tests {let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.over)).collect::<Vec<_>>(), [(4, 2, NO_OVER), (2, 1, NO_OVER)], "the part left alone (two materials), the moved node");assert_eq!((sc.meshes[0].lo.x, sc.meshes[0].hi.x, sc.meshes[1].lo.x, sc.meshes[1].hi.x), (1.0, 9.0, -1.0, 1.0), "the part left alone in the model's space (its node 5 m along x), the moved node in its own");- assert_eq!((sc.instances.len(), sc.tris.len()), (4, 0), "two instances a placement, nothing flattened");+ assert_eq!(sc.instances.len(), 4, "two instances a placement");let rigid = |sc: &Scene, id: u32| match &sc.retained.proxies[&id].draw {Draw::Rigid(r) => r.clone(),_ => panic!("a posed rigid model"),@@ -3372,14 +3119,6 @@ mod instance_tests {assert_eq!((of(1), of(2)), (vec![false; 2], vec![false; 2]));}- #[test]- fn node_ranges_returns_every_range() {- let nodes = vec![("lamp".to_string(), 10, 12), ("box".to_string(), 12, 20), ("lamp".to_string(), 40, 90)];- assert_eq!(node_ranges(&nodes, "lamp").collect::<Vec<_>>(), vec![10..12, 40..90]);- assert_eq!(node_ranges(&nodes, "box").collect::<Vec<_>>(), vec![12..20]);- assert_eq!(node_ranges(&nodes, "none").count(), 0);- }-/// More volumes shown than the kernel takes (32): the scene is refused, not drawn without the last ones; hidden/// volumes do not count.#[test]diff --git a/renderer/src/tables.rs b/renderer/src/tables.rsindex 428d7d8..581bdad 100644--- a/renderer/src/tables.rs+++ b/renderer/src/tables.rs@@ -46,14 +46,11 @@ pub struct Tables {/// Materials that have emitter triangles (others cannot start emitting without a rebuild).pub(crate) emissive: HashSet<u32>,/// A material that starts emitting gets emitter entries in place (the live view sets this up): it is queued in- /// `started_emitting` for live/edits.rs `add_material_emitters`, which gives them to its still world-space- /// triangles (`prepare`'s `mat_runs`) and to the instances with a row of it. Off: such a material rebuilds.+ /// `started_emitting` for live/edits.rs `add_material_emitters`, which gives them to the instances with a row of+ /// it. Off: such a material rebuilds.pub emit_in_place: bool,- /// Materials of still world-space triangles (what the build flattened): whether one is a cutout decides its- /// triangles' traversal group, so that changing is a rebuild's.- pub static_mats: HashSet<u32>,- /// Materials of dynamic world-space triangles (particles'): their class is the triangle's, and they get no- /// emitters in place. One that starts emitting, or whose class changes, rebuilds.+ /// The particle systems' materials: they get no emitters in place. One that starts emitting, or whose class+ /// changes, rebuilds.pub moving_mats: HashSet<u32>,pub started_emitting: Vec<u32>,/// Materials whose class changed in the last `apply` (`Dirty::reclassed`).@@ -84,7 +81,6 @@ impl Tables {emitter_tris,light_tree,emit_in_place: false,- static_mats: HashSet::new(),moving_mats: HashSet::new(),started_emitting: vec![],reclassed: vec![],@@ -174,12 +170,11 @@ impl Tables {}// A material whose class changes (it turns glass or stops being glass, becomes a cutout or stops being// one, gets a function or loses it): the instances with a row of it say so again, in place- // (`Dirty::reclassed`). Its world-space triangles cannot: still ones are in a traversal group by whether- // they are cutouts, dynamic ones carry their class.+ // (`Dirty::reclassed`). A particle system's cannot.let old = &self.materials[mi as usize];let cutout = (gm.uv2[3] > 0.0) != (old.uv2[3] > 0.0);let other = (gm.tex1[3] != 0) != (old.tex1[3] != 0) || (gm.layer[0] > 0.0) != (old.layer[0] > 0.0);- if (cutout && self.static_mats.contains(&mi)) || ((cutout || other) && self.moving_mats.contains(&mi)) {+ if (cutout || other) && self.moving_mats.contains(&mi) {return Ok(None);}if cutout || other {diff --git a/renderer/src/units.rs b/renderer/src/units.rsindex e76e253..f7058dd 100644--- a/renderer/src/units.rs+++ b/renderer/src/units.rs@@ -6,32 +6,28 @@//! and checks every tree before it is written: the kernel follows the indices it reads, and ends only if they are a//! tree's.//!-//! The node buffer: the still scene's tree (as before), then the mesh trees' range (trees side by side, room after-//! them), then the top tree's range. A mesh tree is relocatable: child indices count from its root, a leaf's+//! The node buffer: the mesh trees' range (trees side by side, room after them), then the top tree's range. A mesh tree is relocatable: child indices count from its root, a leaf's//! triangles from its mesh's first triangle. The top tree's child indices count from its root, and each of its leaves//! is one unit: `left_or_first` the unit's record, `count` 1. It is built by the surface-area heuristic (`build_sah`)//! and written whole whenever a unit changes, but seldom built over all the units: it is kept with its boxes brought//! up to date (`refit_top`) while units only move a little, and units that come, or travel, get a tree of their own//! beside the others' (`Kept`: the settled and the loose), which is what is built when they move.//!-//! Depths: one stack of `STACK` entries, the kernel module's (trace_units.wgsl says why not a walk's own): the still-//! walk uses it, leaves it empty, and both levels of the unit walk share it (a push past it is dropped: geometry-//! missed, never a hang). A walk's stack is never deeper than its tree, so the+//! Depths: one stack of `STACK` entries, the kernel module's (trace_units.wgsl says why not a walk's own): both+//! levels of the unit walk share it (a push past it is dropped: geometry missed, never a hang). A walk's stack is never deeper than its tree, so the//! top tree is held to `TOP_DEPTH` (its builder takes no split the levels left could not finish, and stops a level//! short of it: the top tree may be a root over two built trees) and a mesh tree to//! `MESH_DEPTH` (a tree deeper than that is built again by median splits, which halve), and the two fit. Binned SAH//! is not balanced: its tree over 5.86 M triangles (the catalog's largest model) is 42 deep, twice a balanced one's-//! 21, and over 30 k to 500 k triangles 17 to 22. The still scene's walk uses 48 entries for its one tree, as before.+//! 21, and over 30 k to 500 k triangles 17 to 22.use crate::bvh::{self, check_tree, GpuNode};use crate::scene::GpuInstance;use glam::{Mat4, Vec3A};/// The stack of a kernel with units (trace_units.wgsl `stack`, the module's): entries shared by the unit walk's two-/// levels, and used by the still walk before them.+/// levels.pub const STACK: usize = 64;-/// The still walk's stack in a kernel without units, and how much of the module's the still walk uses in one with.-pub const STILL_STACK: usize = bvh::STACK;/// The deepest top tree (levels below the root): a built tree is no deeper than 18, whatever its units' boxes/// (`build_sah`), and the top tree is one, or a root over two (`Kept`).pub const TOP_DEPTH: usize = 19;@@ -230,7 +226,7 @@ fn tri_boxes(tris: &[[Vec3A; 3]]) -> Vec<(Vec3A, Vec3A)> {tris.iter().map(|t| (t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2]))).collect()}-/// The tree of a mesh's model-space triangles: binned SAH as the still scene's (bvh.rs), or by median splits when+/// The tree of a mesh's model-space triangles: binned SAH (bvh.rs), or by median splits when/// that came out deeper than `MESH_DEPTH`. Checked. A mesh without triangles has no tree, and is no unit.pub fn mesh_tree(tris: &[[Vec3A; 3]]) -> Result<MeshTree, String> {if tris.is_empty() {@@ -534,8 +530,7 @@ pub fn join_tops(a: &[GpuNode], b: &[GpuNode]) -> Vec<GpuNode> {/// bytes.#[derive(Clone, Debug)]pub struct Layout {- /// The mesh trees' range: its first node and its length.- pub mesh_first: u32,+ /// The mesh trees' range, from node 0: its length.pub mesh_cap: u32,/// The top tree's range (its root is its first node) and the most units it has room for.pub top_first: u32,@@ -545,14 +540,14 @@ pub struct Layout {}impl Layout {- /// After a still tree of `still` nodes: room for `mesh_nodes` nodes of mesh trees and a top tree of `units` units.- pub fn new(still: usize, mesh_nodes: usize, units: usize) -> Layout {- let (mesh_first, mesh_cap) = (still as u32, mesh_nodes as u32);+ /// Room for `mesh_nodes` nodes of mesh trees and a top tree of `units` units.+ pub fn new(mesh_nodes: usize, units: usize) -> Layout {+ let mesh_cap = mesh_nodes as u32;let top_cap = (2 * units.clamp(1, MAX_UNITS) - 1) as u32;- Layout { mesh_first, mesh_cap, top_first: mesh_first + mesh_cap, top_cap, free: if mesh_cap > 0 { vec![(mesh_first, mesh_cap)] } else { vec![] } }+ Layout { mesh_cap, top_first: mesh_cap, top_cap, free: if mesh_cap > 0 { vec![(0, mesh_cap)] } else { vec![] } }}- /// Every node of the buffer after the still tree's: all room (`FILL`).+ /// Every node of the buffer: all room (`FILL`).pub fn nodes(&self) -> usize {(self.mesh_cap + self.top_cap) as usize}@@ -578,7 +573,7 @@ impl Layout {/// Gives a mesh tree's nodes back (its root and length, as `place` gave them).pub fn release(&mut self, root: u32, len: usize) {let len = len as u32;- debug_assert!(root >= self.mesh_first && root + len <= self.mesh_first + self.mesh_cap);+ debug_assert!(root + len <= self.mesh_cap);let k = self.free.partition_point(|f| f.0 < root);debug_assert!(k == 0 || self.free[k - 1].0 + self.free[k - 1].1 <= root, "released twice");debug_assert!(k == self.free.len() || root + len <= self.free[k].0, "released twice");@@ -921,19 +916,14 @@ pub(crate) mod cpu {pub(crate) reads: std::cell::Cell<Reads>,}- /// A walk's reads by kind: nodes of the still tree, of the top tree and of mesh trees, vertices (three a triangle- /// test) and unit records; `still_steps`: the loop iterations of the still scene's walk (the rest of `steps` are- /// the unit walk's). `in_units`: the still walk is over.+ /// A walk's reads by kind: nodes of the top tree and of mesh trees, vertices (three a triangle test) and unit+ /// records.#[derive(Clone, Copy, Debug, Default, PartialEq)]pub(crate) struct Reads {- pub(crate) still_nodes: u64,pub(crate) top_nodes: u64,pub(crate) mesh_nodes: u64,- pub(crate) still_verts: u64,pub(crate) mesh_verts: u64,pub(crate) records: u64,- pub(crate) still_steps: u64,- pub(crate) in_units: bool,}pub(crate) type Walk<T> = Result<T, String>;@@ -944,18 +934,15 @@ pub(crate) mod cpu {f(&mut r);self.reads.set(r);}- /// The still walk is over. (The top tree's nodes are the buffer's last: a node at `top` or after is the top- /// tree's, one before it a mesh tree's.)- fn still_done(&self) {- self.count(|r| r.in_units = true);- }+ /// (The top tree's nodes are the buffer's last: a node at `top` or after is the top tree's, one before it a+ /// mesh tree's.)pub(crate) fn node(&self, i: u32) -> Walk<GpuNode> {- 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.count(|r| *(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()))}/// 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.count(|r| r.mesh_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`.@@ -968,7 +955,6 @@ pub(crate) mod cpu {}pub(crate) fn step(&self) -> Walk<()> {self.steps.set(self.steps.get() + 1);- self.count(|r| r.still_steps += !r.in_units as u64);if self.steps.get() > self.budget {return Err("does not stop".into());}@@ -1028,66 +1014,11 @@ pub(crate) mod cpu {Self::proc_dir(r, p - Vec3A::new(r.m[0][3], r.m[1][3], r.m[2][3]))}- /// pathtrace.wgsl `trace`, the still scene's tree (no cutouts: the scenes here have none), then the units as- /// the kernel has them under `@if(units)`.+ /// pathtrace.wgsl `trace`: the units, as the kernel has them under `@if(units)` (no cutouts: the scenes here+ /// have none).pub(crate) fn trace(&self, o: Vec3A, d: Vec3A, tmax_in: f32, mode: u32) -> Walk<Hit> {- let mut hit = Hit { t: tmax_in, tri: 0xffff_ffff, inst: NO_INST };- let inv_d = Self::inv(d);- // (The stack is the module's in a kernel with units, 64 long, the still walk's own bound kept; in one- // without, the walk's own 48.)- let (mut stack, mut sp, mut node) = ([0u32; STACK], 0usize, 0u32);- loop {- self.step()?;- let n = self.node(node)?;- if n.count > 0 {- for k in 0..n.count {- self.step()?;- let ti = n.left_or_first + k;- 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);- }- }- }- if sp == 0 {- break;- }- sp -= 1;- node = stack[sp];- continue;- }- let l = n.left_or_first;- let r = l + 1;- let (nl, nr) = (self.node(l)?, self.node(r)?);- let mut tl = Self::ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);- let mut tr = Self::ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);- if tl == INF && tr == INF {- if sp == 0 {- break;- }- sp -= 1;- node = stack[sp];- continue;- }- let (mut near, mut far) = (l, r);- if tr < tl {- (near, far) = (r, l);- std::mem::swap(&mut tl, &mut tr);- }- node = near;- if tr != INF && sp < STILL_STACK {- stack[sp] = far;- sp += 1;- }- }- self.still_done();- self.trace_units(o, d, inv_d, hit, mode, &mut stack)+ let hit = Hit { t: tmax_in, tri: 0xffff_ffff, inst: NO_INST };+ self.trace_units(o, d, Self::inv(d), hit, mode, &mut [0u32; STACK])}/// shaders/trace_units.wgsl `row_flags`.@@ -1300,19 +1231,14 @@ pub(crate) mod tests {"let t = dot(e2, qv) * inv;","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>;",- "let r = intersect_tri(o, d, ti, hit.t);",- "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) {",+ "var hit = Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);",+ "@if(units) hit = trace_units(o, d, 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20)), hit, mode);","if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }",],);- // What the stack and the record's words are here is what they are there.- assert_eq!((STACK, STILL_STACK), (64, 48));- assert!(TOP_DEPTH + MESH_DEPTH <= STACK && STILL_STACK <= STACK, "one stack holds each walk");+ // What the stack is here is what it is there.+ assert_eq!(STACK, 64);+ assert!(TOP_DEPTH + MESH_DEPTH <= STACK, "one stack holds both levels");}/// A deterministic stream of numbers in [0, 1).@@ -1346,7 +1272,6 @@ pub(crate) mod tests {soup: Soup,instances: Vec<GpuInstance>,layout: Layout,- still_tris: usize,/// Meshes: first triangle, triangle count, root, node count, model bounds. None: removed.meshes: Vec<Option<(u32, u32, u32, usize, Vec3A, Vec3A)>>,/// Units by record: mesh, world, casts shadows. None: a free record.@@ -1373,19 +1298,9 @@ pub(crate) mod tests {}impl Scene {- fn new(still: &[[Vec3A; 3]], mesh_room: usize, units: usize) -> Scene {- let b = bvh::build(still);- 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() {- 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, soup, instances: vec![GpuInstance::default()], top: layout.top_first, layout, still_tris: still.len(), meshes: vec![], units: vec![], count: 0, kept: Kept::default() }+ fn new(mesh_room: usize, units: usize) -> Scene {+ let layout = Layout::new(mesh_room, units);+ Scene { nodes: vec![FILL; layout.nodes()], soup: Soup::default(), instances: vec![GpuInstance::default()], top: layout.top_first, layout, 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.@@ -1449,17 +1364,11 @@ pub(crate) mod tests {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- /// the world, a unit's in the unit's space, as the kernel does): the closest hit.+ /// Every triangle a ray could meet, tested one by one with the kernel's own triangle test (a unit's in the+ /// unit's space, as the kernel does): the closest hit.fn brute(&self, o: Vec3A, d: Vec3A, mode: u32) -> Hit {let k = self.kernel();let mut best = Hit { t: INF, tri: 0xffff_ffff, inst: NO_INST };- for ti in 0..self.still_tris as u32 {- let t = k.intersect_tri(o, d, ti, best.t).unwrap();- if t < best.t {- best = Hit { t, tri: ti, inst: NO_INST };- }- }for (rec, u) in self.units.iter().enumerate() {let Some((mesh, _, cast)) = u else { continue };if mode == TRACE_SHADOW && !cast {@@ -1497,7 +1406,8 @@ pub(crate) mod tests {if got.tri != want.tri || got.inst != want.inst {// Two triangles at one distance: both are closest.let again = Kernel { budget: u64::MAX, ..self.kernel() };- let t = if got.inst == NO_INST { again.intersect_tri(o, d, got.tri, INF).unwrap() } else { let r = &self.instances[got.inst as usize]; again.intersect_tri(Kernel::proc_point(r, o), Kernel::proc_dir(r, d), got.tri, INF).unwrap() };+ let r = &self.instances[got.inst as usize];+ let t = again.intersect_tri(Kernel::proc_point(r, o), Kernel::proc_dir(r, d), got.tri, INF).unwrap();assert_eq!(t.to_bits(), want.t.to_bits(), "{what}: ray {o} {d}: {got:?} is not at brute force's distance {want:?}");}on_units += (got.inst != NO_INST) as usize;@@ -1527,16 +1437,14 @@ pub(crate) mod tests {/// Random scenes under random edits: meshes added and removed, units added, moved (far, or a little: the top tree/// is then kept and refitted) and removed, the top tree made again after each, as an edit does. After every edit the kernel's two walks, on the CPU with every read checked,- /// agree with brute force. Scenes with and without a still part; units that overlap; a scene emptied of units.+ /// agree with brute force. Units that overlap; a scene emptied of units.#[test]fn the_walks_agree_with_brute_force_under_random_edits() {let (mut edits, mut unit_hits, mut rays, mut refits, mut changes, mut builds, mut short) = (0, 0, 0, 0, 0, 0, 0);for seed in 0..12u64 {let mut rng = Rng(seed * 7919 + 1);- let n = 50 + rng.below(400);- let still = if seed % 3 == 0 { vec![] } else { rng.tris(n, 40.0, 3.0) };// (Every other scene starts with more units than a small scene's: there the top tree is kept in parts.)- let mut sc = Scene::new(&still, 6000, if seed % 2 == 0 { 64 } else { 400 });+ let mut sc = Scene::new(6000, if seed % 2 == 0 { 64 } else { 400 });sc.check(&mut rng, 40, "no unit yet");if seed % 2 == 1 {let m = sc.add_mesh(&rng.tris(12, 3.0, 1.0)).unwrap();@@ -1751,22 +1659,22 @@ pub(crate) mod tests {/// Room and the place of trees: first fit, runs joined again when trees go, nothing lost.#[test]fn the_layout_places_and_takes_back() {- let mut l = Layout::new(100, 50, 8);- assert_eq!((l.mesh_first, l.top_first, l.top_cap, l.nodes(), l.max_units()), (100, 150, 15, 65, 8));+ let mut l = Layout::new(50, 8);+ assert_eq!((l.top_first, l.top_cap, l.nodes(), l.max_units()), (50, 15, 65, 8));let (a, b, c) = (l.place(10).unwrap(), l.place(20).unwrap(), l.place(20).unwrap());- assert_eq!((a, b, c), (100, 110, 130));+ assert_eq!((a, b, c), (0, 10, 30));assert!(l.place(1).is_none());l.release(b, 20);- assert_eq!(l.place(5), Some(110));+ assert_eq!(l.place(5), Some(10));l.release(a, 10);- l.release(110, 5);+ l.release(10, 5);assert_eq!(l.free_nodes(), 30);- assert_eq!(l.place(30), Some(100), "the runs are one again");+ assert_eq!(l.place(30), Some(0), "the runs are one again");l.release(c, 20);- l.release(100, 30);- assert_eq!((l.free_nodes(), l.place(50)), (50, Some(100)));+ l.release(0, 30);+ assert_eq!((l.free_nodes(), l.place(50)), (50, Some(0)));// No unit at all: a top range of one node, no mesh range.- let none = Layout::new(7, 0, 0);+ let none = Layout::new(0, 0);assert_eq!((none.nodes(), none.max_units()), (1, 1));}@@ -1779,14 +1687,14 @@ pub(crate) mod tests {let (small, large) = (mesh_tree(&rng.tris(40, 2.0, 0.3)).unwrap(), mesh_tree(&rng.tris(400, 2.0, 0.3)).unwrap());let (ns, nl) = (small.nodes.len(), large.nodes.len());assert!(nl > ns);- let mut u = Units { layout: Layout::new(10, ns + nl, 4), trees: vec![], slots: vec![], count: 0, records: 4, kept: Default::default() };+ let mut u = Units { layout: Layout::new(ns + nl, 4), trees: vec![], slots: vec![], count: 0, records: 4, kept: Default::default() };// A mesh without a tree is no unit's.assert!(u.unit(0, Mat4::IDENTITY, false).is_none());- assert_eq!(u.add_tree(0, &small), Some(10));- assert_eq!(u.add_tree(1, &large), Some(10 + ns as u32));+ assert_eq!(u.add_tree(0, &small), Some(0));+ assert_eq!(u.add_tree(1, &large), Some(ns as u32));assert_eq!(u.layout.free_nodes(), 0);let (a, b) = (u.unit(0, Mat4::IDENTITY, false).unwrap(), u.unit(1, Mat4::from_translation(glam::Vec3::X * 5.0), false).unwrap());- assert_eq!((a.root, b.root), (10, 10 + ns as u32));+ assert_eq!((a.root, b.root), (0, ns as u32));u.set(0, Some(a));u.set(2, Some(b));// (Clearing a record past the slots makes none.)@@ -1796,8 +1704,8 @@ pub(crate) mod tests {assert_eq!((top.len(), u.count), (3, 2));check_top(&top, |r| u.slots.get(r as usize).is_some_and(|s| s.is_some())).unwrap();- // Mesh 0's tree is freed: its unit's record still names node 10.- assert_eq!(u.drop_tree(0), Some((10, ns as u32)));+ // Mesh 0's tree is freed: its unit's record still names node 0.+ assert_eq!(u.drop_tree(0), Some((0, ns as u32)));assert_eq!(u.drop_tree(0), None);let e = u.top().unwrap_err();assert!(e.contains("record 0") && e.contains("mesh 0"), "{e}");@@ -1811,14 +1719,14 @@ pub(crate) mod tests {// Mesh 1's tree is made again: its own nodes are given back first, one run with mesh 0's, and the new tree// starts where that run does. Its unit's record names the old root until it is written again.u.set(0, None);- assert_eq!(u.add_tree(1, &large), Some(10));+ assert_eq!(u.add_tree(1, &large), Some(0));assert_eq!(u.layout.free_nodes(), ns);assert!(u.top().is_err());- assert_eq!(u.add_tree(1, &small), Some(10));+ assert_eq!(u.add_tree(1, &small), Some(0));let e = u.top().unwrap_err();assert!(e.contains("record 2") && e.contains("mesh 1"), "{e}");u.moved(2, Mat4::from_translation(glam::Vec3::Y), None);- assert_eq!(u.slots[2].unwrap().root, 10);+ assert_eq!(u.slots[2].unwrap().root, 0);assert_eq!((u.top().unwrap().len(), u.count), (1, 1));assert_eq!(u.layout.free_nodes(), nl);@@ -1850,7 +1758,7 @@ pub(crate) mod tests {let tri = |y: f32| [[Vec3A::new(0.0, y, 0.0), Vec3A::new(1.0, y, 0.0), Vec3A::new(0.0, y + 1.0, 0.0)]];let (first, fallen) = (mesh_tree(&tri(2.0)).unwrap(), mesh_tree(&tri(-3.0)).unwrap());assert_eq!((first.lo.y, first.hi.y, fallen.lo.y, fallen.hi.y), (2.0, 3.0, -3.0, -2.0));- let mut u = Units { layout: Layout::new(1, 8, 2), trees: vec![], slots: vec![], count: 0, records: 2, kept: Default::default() };+ let mut u = Units { layout: Layout::new(8, 2), trees: vec![], slots: vec![], count: 0, records: 2, kept: Default::default() };u.add_tree(0, &first).unwrap();u.set(0, u.unit(0, Mat4::IDENTITY, false));let top = u.top().unwrap();@@ -1900,7 +1808,7 @@ pub(crate) mod tests {assert_eq!((lo, hi), exact(&posed), "the bounds are the triangles'");assert!(lo.z > t.hi.z, "the bent mesh is out of its first bounds");// Its unit in the top tree: by the bounds it has, once they are set.- let mut u = Units { layout: Layout::new(1, t.nodes.len() + 8, 2), trees: vec![], slots: vec![], count: 0, records: 2, kept: Default::default() };+ let mut u = Units { layout: Layout::new(t.nodes.len() + 8, 2), trees: vec![], slots: vec![], count: 0, records: 2, kept: Default::default() };u.add_tree(0, &t).unwrap();u.set(0, u.unit(0, Mat4::IDENTITY, false));let top = u.top().unwrap();@@ -1931,7 +1839,7 @@ pub(crate) mod tests {let mut rng = Rng(21);let mesh = mesh_tree(&rng.tris(30, 1.0, 0.3)).unwrap();let n = 200;- let mut u = Units { layout: Layout::new(1, mesh.nodes.len(), n + 200), trees: vec![], slots: vec![], count: 0, records: n + 200, kept: Default::default() };+ let mut u = Units { layout: Layout::new(mesh.nodes.len(), n + 200), trees: vec![], slots: vec![], count: 0, records: n + 200, kept: Default::default() };u.add_tree(0, &mesh).unwrap();let mut at: Vec<Vec3> = (0..n).map(|_| Vec3::from(rng.v(40.0))).collect();for (k, p) in at.iter().enumerate() {@@ -1968,7 +1876,7 @@ pub(crate) mod tests {assert_eq!((u.kept.builds, u.kept.changes, u.kept.refits), (1, 0, 61));// Units close together, each grown to nearly twice its size where it is: none has gone astray, and the tree// costs too much: built.- let mut d = Units { layout: Layout::new(1, mesh.nodes.len(), 100), trees: vec![], slots: vec![], count: 0, records: 100, kept: Default::default() };+ let mut d = Units { layout: Layout::new(mesh.nodes.len(), 100), trees: vec![], slots: vec![], count: 0, records: 100, kept: Default::default() };d.add_tree(0, &mesh).unwrap();let close: Vec<Vec3> = (0..100).map(|_| Vec3::from(rng.v(2.0))).collect();for (k, p) in close.iter().enumerate() {diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rsindex 2537145..efe40b7 100644--- a/renderer/src/units_cost.rs+++ b/renderer/src/units_cost.rs@@ -7,7 +7,7 @@//! UNITS_COST=out/bundles/bistro.js cargo test --release --lib units_cost -- --ignored --nocapture//!//! `UNITS_COST_VIEW=WxH` (192x108). `UNITS_COST_ASSETS` (`.`).-use crate::units::cpu::{Kernel, Reads, INF, NO_INST, TRACE_CLOSEST, TRACE_SHADOW};+use crate::units::cpu::{Kernel, Reads, INF, TRACE_CLOSEST, TRACE_SHADOW};use crate::{bvh, default_presets_dir, prepare_as, scene, units};use glam::Vec3A;use std::time::Instant;@@ -21,12 +21,11 @@ struct Laid {units: u32,/// For the report.what: String,- /// The still scene's triangles (the first so many), and each unit's: its record, its first triangle, how many.- still: u32,+ /// Each unit's triangles: its record, its first triangle, how many.unit_tris: Vec<(u32, u32, u32)>,}-/// A ray and the flattened scene's answer to it (`t`: the hit's distance, INF for none).+/// A ray and the scene's answer to it (`t`: the hit's distance, INF for none).#[repr(C)]#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]struct Ray {@@ -41,7 +40,7 @@ struct Ray {fn lay(world: &crate::world::World, assets: &std::path::Path) -> (Laid, scene::Scene) {let mut sc = scene::build(world, assets, &default_presets_dir(), None).unwrap();- let (flat, placed) = (sc.tris.len(), sc.instances.iter().map(|i| sc.meshes[i.mesh as usize].count as usize).sum::<usize>());+ let placed = sc.instances.iter().map(|i| sc.meshes[i.mesh as usize].count as usize).sum::<usize>();let t = Instant::now();let p = prepare_as(false, &mut sc, &mut vec![]);let s = t.elapsed().as_secs_f64();@@ -49,21 +48,18 @@ fn lay(world: &crate::world::World, assets: &std::path::Path) -> (Laid, scene::Slet 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 what = format!("{} triangles stored ({:.1} MiB of vertices + attributes), {} nodes ({:.1} MiB), {} units; {} triangles placed; 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), 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, soup, 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, unit_tris }, sc)}impl Laid {- /// The closest hit by every triangle tested one by one, the still scene's in the world and each unit's in the- /// unit's space, as the walk tests them: what the walk must find, whatever its trees are.+ /// The closest hit by every triangle tested one by one, each unit's in the unit's space, as the walk tests them:+ /// what the walk must find, whatever its trees are.fn brute(&self, o: Vec3A, d: Vec3A, tmax: f32) -> f32 {let k = Kernel { budget: u64::MAX, ..self.kernel() };let mut best = tmax;- for ti in 0..self.still {- best = best.min(k.intersect_tri(o, d, ti, best).unwrap());- }for &(rec, first, count) in &self.unit_tris {let r = &self.instances[rec as usize];let (lo, ld) = (Kernel::proc_point(r, o), Kernel::proc_dir(r, d));@@ -87,7 +83,7 @@ impl Rng {}}-/// A frame's rays through the flattened scene `l`: the camera's over a `w` x `h` view; from each hit a shadow ray to+/// A frame's rays through the scene `l`: the camera's over a `w` x `h` view; from each hit a shadow ray to/// a far light (one direction for all: a sun), one to a point a few metres off (a lamp), and a bounce (cosine/// distributed); from the bounce's hit the two shadow rays again.fn rays(l: &Laid, cam: &scene::CameraData, w: usize, h: usize) -> Vec<Ray> {@@ -104,7 +100,8 @@ fn rays(l: &Laid, cam: &scene::CameraData, w: usize, h: usize) -> Vec<Ray> {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 r = &l.instances[hit.inst as usize];+ let n = 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 };(o + d * hit.t + n * 1e-3, n)})@@ -142,7 +139,7 @@ struct Sum {rays: u64,steps: u64,most: u64,- r: [u64; 7],+ r: [u64; 4],wrong: u64,deepest: usize,}@@ -154,23 +151,23 @@ fn count(l: &Laid, rays: &[Ray]) -> [Sum; 4] {let k = l.kernel();let hit = k.trace(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax, ray.mode).unwrap_or_else(|e| panic!("the kernel {e}"));let t = if hit.tri == 0xffff_ffff { INF } else { hit.t };- // A closest hit at the flattened scene's distance (to the rounding of a triangle tested in its own space); a+ // A closest hit at the kept answer's distance (to the rounding of a triangle tested in its own space); a// shadow ray blocked or not as there.let same = if ray.mode == TRACE_CLOSEST { (t == INF) == (ray.t == INF) && (t == INF || (t - ray.t).abs() <= 2e-4 * (1.0 + ray.t.min(1e4))) } else { (t == INF) == (ray.t == INF) };- let Reads { still_nodes, top_nodes, mesh_nodes, still_verts, mesh_verts, records, still_steps, .. } = k.reads.get();+ let Reads { top_nodes, mesh_nodes, mesh_verts, records } = k.reads.get();for which in [ray.kind as usize, 3] {let s = &mut sums[which];s.rays += 1;s.steps += k.steps.get();s.most = s.most.max(k.steps.get());- for (a, b) in s.r.iter_mut().zip([still_nodes, top_nodes, mesh_nodes, still_verts / 3, mesh_verts / 3, records, still_steps]) {+ for (a, b) in s.r.iter_mut().zip([top_nodes, mesh_nodes, mesh_verts / 3, records]) {*a += b;}s.wrong += !same as u64;s.deepest = s.deepest.max(k.deepest.get());}if !same && sums[3].wrong <= 8 {- println!(" differs: a ray of kind {} from {:?} along {:?}, mode {}: {} here (triangle {}, record {}), {} in the flattened scene; every triangle here tested one by one: {}", ray.kind, ray.o, ray.d, ray.mode, t, hit.tri, if hit.inst == NO_INST { -1 } else { hit.inst as i64 }, ray.t, l.brute(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax));+ println!(" differs: a ray of kind {} from {:?} along {:?}, mode {}: {} here (triangle {}, record {}), {} kept; every triangle here tested one by one: {}", ray.kind, ray.o, ray.d, ray.mode, t, hit.tri, hit.inst as i32, ray.t, l.brute(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax));}}sums@@ -180,17 +177,17 @@ fn report(name: &str, l: &Laid, rays: &[Ray], pixels: usize, base: Option<f64>)let t = Instant::now();let sums = count(l, rays);println!("{name}: {}", l.what);- println!(" {:<8} {:>8} {:>9} {:>8} | {:>9} {:>9} {:>9} | {:>9} {:>9} {:>8} | {:>9} {:>6}", "rays", "count", "steps", "most", "still nd", "top nd", "mesh nd", "still tri", "mesh tri", "records", "bytes", "wrong");+ println!(" {:<8} {:>8} {:>9} {:>8} | {:>9} {:>9} | {:>9} {:>8} | {:>9} {:>6}", "rays", "count", "steps", "most", "top nd", "mesh nd", "mesh tri", "records", "bytes", "wrong");let mut all = 0.0;for (kind, s) in ["camera", "shadow", "bounce", "all"].iter().zip(&sums) {let per = |v: u64| v as f64 / s.rays.max(1) as f64;// What a ray reads: 32 bytes a node, 48 a triangle, 112 a record's rows.- let bytes = 32.0 * per(s.r[0] + s.r[1] + s.r[2]) + 48.0 * per(s.r[3] + s.r[4]) + 112.0 * per(s.r[5]);- println!(" {kind:<8} {:>8} {:>9.2} {:>8} | {:>9.2} {:>9.2} {:>9.2} | {:>9.2} {:>9.2} {:>8.3} | {:>9.0} {:>6}", s.rays, per(s.steps), s.most, per(s.r[0]), per(s.r[1]), per(s.r[2]), per(s.r[3]), per(s.r[4]), per(s.r[5]), bytes, s.wrong);+ let bytes = 32.0 * per(s.r[0] + s.r[1]) + 48.0 * per(s.r[2]) + 112.0 * per(s.r[3]);+ println!(" {kind:<8} {:>8} {:>9.2} {:>8} | {:>9.2} {:>9.2} | {:>9.2} {:>8.3} | {:>9.0} {:>6}", s.rays, per(s.steps), s.most, per(s.r[0]), per(s.r[1]), per(s.r[2]), per(s.r[3]), bytes, s.wrong);all = bytes * s.rays as f64 / pixels as f64;}let s = &sums[3];- println!(" a pixel: {:.0} steps ({:.0} of them the still walk's), {:.0} bytes read{}; the stack's deepest {}; counted in {:.1} s", s.steps as f64 / pixels as f64, s.r[6] as f64 / pixels as f64, all, base.map_or(String::new(), |b| format!(" ({:+.1} % on the flattened scene's)", (all / b - 1.0) * 100.0)), s.deepest, t.elapsed().as_secs_f64());+ println!(" a pixel: {:.0} steps, {:.0} bytes read{}; the stack's deepest {}; counted in {:.1} s", s.steps as f64 / pixels as f64, all, base.map_or(String::new(), |b| format!(" ({:+.1} % on the first's)", (all / b - 1.0) * 100.0)), s.deepest, t.elapsed().as_secs_f64());all}diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex 67dc0d2..6a3608f 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -126,9 +126,9 @@ pub struct Texture {#[derive(Clone, Debug)]pub enum Kind {Group,- /// `own_blas` (scene code's `dynamicGeometry`): instanced with its own BLAS, so replacing its geometry, creating or- /// removing it is applied in place (live/edits.rs `edit_geometry`) instead of rebuilding the scene; otherwise its- /// triangles are flattened into the shared groups.+ /// `own_blas` (scene code's `dynamicGeometry`): a mesh of its own, so replacing its geometry, creating or removing+ /// it is applied in place (live/edits.rs `edit_geometry`) instead of rebuilding the scene; otherwise an instance+ /// of the mesh every object of its geometry shares./// `materials`: one per geometry group (three.js's material array; empty: `material` for every triangle).Mesh { geometry: u32, material: u32, own_blas: bool, materials: Vec<u32> },/// glTF asset (path relative to the asset root), optionally only some of its nodes (by name).@@ -201,8 +201,8 @@ pub struct Object {/// Per-instance data (UE PerInstanceCustomData): any four numbers scene code gives the object, read by material/// functions as `i.custom` (particle functions write one per particle).pub custom: [f32; 4],- /// UE Mobility "Movable": scripts move it (and everything under it) without rebuilding the scene; its triangles- /// are kept apart (dynamic BLASes) and re-transformed in place. Set by scene code, or by the first move.+ /// UE Mobility "Movable": scripts move it (and everything under it) without rebuilding the scene: its instances'+ /// transforms. Set by scene code, or by the first move.pub movable: bool,/// A rigid body drives it (renderer/src/physics.rs): movable, and a mesh among them is placed as an instance of its/// own BLAS, so a move is its TLAS transform and no triangle.