Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Every mesh has sections and rows: glTF models too (#171)

Yujiafe37721d54cc
diff --git a/docs/PARITY.md b/docs/PARITY.md
index cd8f6a1..8cce5a3 100644
--- a/docs/PARITY.md
+++ b/docs/PARITY.md
@@ -34,13 +34,16 @@ Engine (renderer + DSL; at the time also the scene IR and its UE adapter, both s
1. **Textures** (`renderer/src/texpack.rs`): any number and size of textures shelf-packed into 4096² array pages with
wrapped / clamped 16 px gutters and a 5-level box mip chain (rects aligned so mips never mix textures); a per-texture
table drives manual wrap / clamp; ray-cone LOD (Akenine-Möller 2019) picks the mip per hit; `texture.offset`;
- alpha-cutout materials (`alphaTest`) through four BLAS groups (opaque / cutout × shadow / no-shadow) with ray-query
- candidate confirmation, and the same test in the software BVH. Pages are cached across live re-uploads.
- Meshes and static glTF models are instances (`scene::Instance`; a mesh shared by the objects of the same geometry
- and materials, one that moves moved by its transform): each unique mesh's triangles once in model
- space with one BLAS (an opaque, a cutout and a glass geometry), one TLAS instance per placement (transform, shadow
- mask, custom data = instance record), shading transforms the hit triangle; a shadow ray passes a mesh that is all glass by the
- instance's mask and culls the glass geometry of a mixed mesh (the one not flagged opaque); `glass_tr` weighs what it lets through. A mirrored placement is an instance whose record says so. A model's
+ alpha-cutout materials (`alphaTest`) through four BLAS groups (opaque / cutout × shadow / no-shadow), every
+ geometry flagged opaque and a cutout hit that fails its alpha test stepped through, and the same test in the
+ software BVH. Pages are cached across live re-uploads.
+ Meshes and static glTF models are instances (`scene::Instance`; a mesh is its geometry's or its model's alone,
+ one that moves moved by its transform): each unique mesh's triangles once in model space, by section (a geometry
+ group, or a material of the file), with one BLAS (a geometry a section), one TLAS instance per placement
+ (transform, shadow mask, custom data = instance record) with a row a section (`scene::Row`: the material and its
+ class, the section's first triangle, its first emitter); shading transforms the hit triangle; a shadow ray passes
+ a mesh that is all glass by the instance's mask and steps through the glass among an instance's other sections;
+ `glass_tr` weighs what it lets through. A mirrored placement is an instance whose record says so. A model's
triangles that only emit stay in its mesh: each placement's are a run of the light list. `THREERT_INSTANCING=0` flattens everything, `=log` lists what each model instances.
`node tools/check-instancing.ts` renders instanced cutout props (scaled and not) instanced, flattened and through
software traversal, and fails when they differ (crops: `docs/img/bugbot-instanced-cutouts.jpg`).
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 3ab0e05..428650e 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2737,14 +2737,14 @@ keyed by its geometry (`Retained::own_mesh`, `scene::section_mesh`). Its triangl
or the whole geometry, each a geometry of the BLAS, all flagged opaque, and hold their section and their index in
it. An instance has a row a section in the words' heap (`scene::Row`, heap.rs `Stream::Rows`; its record has their
first): the material with its class, the section's first triangle, its first emitter. The kernel reads a hit's
-material, whether it is a cutout or glass, and its emitter through the row (`material_of`, `row_word`; kernel
-feature `F_ROWS`); the trace's test of a hit reads no attribute and no material. Whether an instance casts a shadow,
+material, whether it is a cutout or glass, and its emitter through the row (`material_of`, `row_word`); the
+trace's test of a hit reads no attribute and no material. Whether an instance casts a shadow,
has a cutout or glass, emits: its rows say (`rows_cast`, `rows_bits`, `rows_emitters`). Glass among an instance's
other sections is stepped through by a shadow ray, as a cutout that lets it pass is; an instance that is all glass
is out of its way by its mask, as before. Vertex colours are the geometry's, and a material says whether it reads
them, where they were baked white for one that did not. Software traversal: a unit's cutouts and glass by its rows,
asked only of a unit that has some.
-Models keep their layout until the next part (materials on triangles, a BLAS geometry a class). Edits place what
+Models kept their layout until the next part (materials on triangles, a BLAS geometry a class). Edits place what
they placed (one section; a row a record of the room). A material that starts emitting gives the instances with a
row of it their emitters, and writes no attribute. Still a rebuild: a several-material mesh edited, a material that
turns glass or cutout, vertex colours asked of a mesh made without them.
@@ -2753,6 +2753,29 @@ vertex colours, cutouts, glass, an emitter) against a geometry an object, at the
given another material; a pane and its frame as one mesh against a mesh each, under a sky sampled as a light; the
light list's emitters found through the rows.
+**Every mesh has sections and rows: models too (2026-11-19, the material on the instance, second part).** A glTF
+model's mesh kept the old layout: its materials on its triangles, a BLAS geometry a class. Now it lies by section
+as a scene mesh does, a section a material of the file (`scene::model_sections`): a still model's mesh, a posed
+rigid model's moving nodes, a shared pose's mesh (skinned again with each triangle in its section). Its instances
+have its rows (`Retained::mesh_rows`). With one layout left the kernel has no feature for it: an instance's hit
+reads its material, its class and its emitter through its row, and only world-space triangles hold their material
+(the still scene's, what is flattened).
+An instance's rows are a run of the rows' room, as many as its mesh's sections (`EditState::rows`, `take_rows`,
+`give_rows`): a model of several materials is placed and removed in place, and what is removed gives its rows back.
+As before: a model is one mesh with one BLAS; a posed rigid model's still nodes are flattened; a deforming mesh's
+emitters are flattened.
+Measured: the meshes and their memory as before (Bistro one mesh of 132 sections, its BLAS 390.3 MB). GPU time a
+frame on twelve scenes, four alternated pairs against main: Kabukichō -1.5 to -2.1 %, a crowd of skinned models
++0.1 to +1.5 %, the voxel level +0.1 to +0.6 %, the other nine within 0.8 %.
+Tried and dropped: a TLAS instance's custom data its rows' first, with the record in the row. About 1 % slower on
+two scenes, not explained. Not tried: the same with the record from the hit's instance index, which reads no row
+for it.
+Tests: a model's sections and rows at the build (`a_models_mesh_lies_by_section_a_material_of_the_file`); a model of
+three materials placed, removed and placed again in place, its rows on the GPU; rows apart from records in the
+in-place tests' world, rows given back; two models in a shared pose posed again in place
+(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting
+section that is not its first, the model a unit under software traversal).
+
**Meshes are edited in place (2026-11-18, scene step E, second part).** With every mesh an instance, what the
scene does to one is a change of its instance, not a rebuild. Hidden or shown (itself, or a group above it): the
instance's mask; a hidden mesh is built as an instance no ray sees, its row without power (`Instance::masked`,
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 8233ee4..ac09769 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -71,7 +71,6 @@ fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }
// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.
override FEAT: u32 = 0xffffffffu;
const F_MASKED: u32 = 1u;
-const F_ROWS: u32 = 2u; // an instance has rows (`row_word`): a section's material is its row's
const F_FOG: u32 = 64u;
const F_VOLUME: u32 = 128u;
const F_TEX: u32 = 256u;
@@ -91,7 +90,7 @@ const F_BACKGROUND: u32 = 2097152u; // scene.background (`sky_mis`)
const F_VCOLOR: u32 = 4194304u; // vertex colours (`vcolor`)
const F_GRID: u32 = 33554432u; // density grids (`vgrid`)
const F_IFUNC: u32 = 268435456u; // a material function on an instanced mesh: `mat_in_at` places the triangle by its instance
-const F_IGLASS: u32 = 536870912u; // glass among an instance's other triangles: shadow rays pass it by its row, or cull a model's glass geometry (trace_hw.wgsl); a unit's glass triangles by their flag
+const F_IGLASS: u32 = 536870912u; // glass among an instance's other sections: a shadow ray steps through it by its row (trace_hw.wgsl), a unit's walk skips it
const F_LISTS: u32 = 134217728u; // light tiles (`lt_list_start`): a scene whose shadow-casting local lights are resampled
fn has(f: u32) -> bool { return (FEAT & f) != 0u; }
@@ -159,7 +158,7 @@ fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }
@group(0) @binding(11) var<storage, read_write> accum: array<Pixel>;
// The dynamic triangles' vertices (kernel layout, from triangle P.group_first[1].x on) as they were the previous frame.
@group(0) @binding(6) var<storage, read> prev_verts: array<vec4<f32>>;
-// Model instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, LOD offset bits, -).
+// Instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, LOD offset bits, 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> };
// Bounded participating media (`VolumeMesh`, gpu.rs MediumGpu; F_MEDIA), P.time.w of them: world -> local affine rows,
// (volume function, shape: 0 box / 1 sphere / 2 none while its node is hidden, homogeneous, 1 = it changes with time: `VolumeFunction` `animated`, a
@@ -296,31 +295,26 @@ fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {
return vec4<f32>(x.x + bitcast<f32>(info.z), bitcast<f32>(info.y), x.z, x.w);
}
// An instance's rows (scene.rs `Row`): four words a section of its mesh, from the record's info.w on. The material
-// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). A record's
-// n1.w says whether it has rows (INST_ROWS: its mesh is its geometry's alone, and a triangle's attributes hold its
-// section in uv.w and its index in the section in x.w), and whether a row of it is a cutout's or glass.
-const INST_ROWS: u32 = 8u;
+// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). A triangle of
+// a mesh holds its section in its attributes' uv.w and its index in the section in x.w; a record's n1.w says whether
+// a row of it is a cutout's or glass.
const INST_CUTOUT: u32 = 16u;
const INST_GLASS: u32 = 32u;
const ROW_MATERIAL: u32 = 0xffffffu;
const ROW_CUTOUT: u32 = 0x1000000u;
const ROW_GLASS: u32 = 0x2000000u;
const NO_EMITTER: u32 = 0xffffffffu;
-fn has_rows(r: Instance) -> bool { return has(F_ROWS) && (bitcast<u32>(r.n1.w) & INST_ROWS) != 0u; }
fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first.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. On the triangle; with rows,
-// in the row of the triangle's section.
+// 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.
fn material_of(a: TriAttr, inst: u32) -> u32 {
let m = triangle_material(a);
- if (has(F_ROWS) && inst != NO_INST) {
- let r = instance_at(inst);
- if (has_rows(r)) { return row_word(r.info.w, m, 0u) & ROW_MATERIAL; }
- }
+ if (has(F_INST) && inst != NO_INST) { return row_word(instance_at(inst).info.w, m, 0u) & ROW_MATERIAL; }
return m;
}
-// The material a triangle itself holds: one that no instance with rows places.
+// The material a triangle itself holds: one that no instance places.
fn triangle_material(a: TriAttr) -> u32 { return bitcast<u32>(a.uv.w); }
// A model-space triangle's shading attributes placed by instance r (scene::instance_attr).
@@ -1889,22 +1883,14 @@ fn emitter_attrs(em: EmitterTri) -> TriAttr {
// surface) is the BSDF ray's alone.
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
if (is_proc(hit) || P.counts.y == 0u) { return 1.0; }
- // The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled), counted from its
- // instance's first entry (the record's n2.w) when an instance places it. With rows: x.w is the triangle's index
- // in its section, counted from the section's first entry (its row's).
+ // The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled). A triangle an
+ // instance places: x.w is its index in its section, counted from the section's first entry (its row's).
let a = attrs[hit.tri];
var entry = bitcast<u32>(a.x.w);
- var rows = false;
if (has(F_INST) && hit.inst != NO_INST) {
- let r = instance_at(hit.inst);
- rows = has_rows(r);
- if (rows) {
- let first = row_word(r.info.w, bitcast<u32>(a.uv.w), 2u);
- if (first == NO_EMITTER) { return 1.0; }
- entry += first + 1u;
- } else if (entry != 0u) {
- entry += bitcast<u32>(r.n2.w);
- }
+ let first = row_word(instance_at(hit.inst).info.w, bitcast<u32>(a.uv.w), 2u);
+ if (first == NO_EMITTER) { return 1.0; }
+ entry += first + 1u;
}
if (entry == 0u) { return 1.0; }
let em = emitter_tri_at(entry - 1u);
diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgsl
index d2df7e2..06d3eaf 100644
--- a/renderer/shaders/trace_hw.wgsl
+++ b/renderer/shaders/trace_hw.wgsl
@@ -1,7 +1,6 @@
// Hardware ray tracing (wgpu ray query). Up to four instances (see Prepared::groups): shadow casters mask 1, the rest
-// mask 2 (glass among them; a model's mesh's glass is a geometry of its BLAS that a shadow ray culls, an instance's
-// glass among its other sections is stepped through by its row); opaque groups
-// never report candidates, alpha-cutout groups are confirmed by `alpha_pass`.
+// 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.
@if(hwrt) @group(0) @binding(19) var acc: acceleration_structure;
@@ -13,7 +12,7 @@
let any = mode != TRACE_CLOSEST;
// (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both. Glass among an
// instance's other sections is stepped through as a cutout is: `passes`.)
- if (!has(F_MASKED) && !(has(F_IGLASS) && has(F_ROWS))) { return trace_opaque(o, d, tmax_in, mask, any); }
+ if (!has(F_MASKED) && !has(F_IGLASS)) { return trace_opaque(o, d, tmax_in, mask, any); }
// Whether a cutout stops this ray as any triangle does: A_CUTOUT_PATHS, A_CUTOUT_EMITTERS (TRACE_ANY_OPAQUE)
// (pathtrace.wgsl `cutouts_opaque`, `emitter_tr`).
@if(!cutout_lite) let solid = cutouts_opaque() || mode == TRACE_ANY_OPAQUE;
@@ -25,8 +24,8 @@
// renders of Kabukichō differed in 75 % of their pixels). Fewer whole-scene steps (the opaque instances once, then
// the cutout instances alone; or one candidate loop on them) came out within ±0.4 ms on Bistro: the leaves' alpha
// tests and the traversal past them cost it, however the queries are arranged. Culling the cutout geometry by its
- // non-opaque flag (RAY_FLAG_CULL_NO_OPAQUE) was slow on Metal (Bistro's trace +1.7 ms); every geometry but an
- // instanced mesh's glass is flagged opaque now (`trace_opaque`).
+ // non-opaque flag (RAY_FLAG_CULL_NO_OPAQUE) was slow on Metal (Bistro's trace +1.7 ms); every geometry is flagged
+ // opaque.
//
// In order, each query starting past the last cutout hit its alpha let through. Shadow rays take up to 64 of them
// and count as blocked past that: with 16, as closest hits take, the rest counted as unblocked (light through dense
@@ -51,7 +50,7 @@
let t = t0 + h.t;
// A shadow ray passes the glass among an instance's sections (its row says so; an instance that is all glass is
// out of its way by its mask).
- let passes = has(F_IGLASS) && has(F_ROWS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;
+ let passes = has(F_IGLASS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;
if (!passes) {
if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || alpha_pass(h.tri, h.inst, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst); }
hole = true;
@@ -67,13 +66,7 @@
hit_row = NO_ROW;
@if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }
var rq: ray_query;
- // A shadow ray (mask 1) where a model's mesh mixes glass with other triangles (F_IGLASS): it culls the geometry
- // that is not flagged opaque, the glass parts alone (gpu.rs), instead of forcing every geometry opaque. A mesh that
- // is all glass is out of its way by the instance's mask. (A mesh with sections has every geometry flagged opaque:
- // `trace` steps through its glass.) (Measured on Metal with every geometry opaque: the same
- // pictures, at most 0.5 % of a frame's GPU time.)
- let opacity = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_CULL_NO_OPAQUE, has(F_IGLASS) && mask == 1u);
- let flags = select(opacity, opacity | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);
+ let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_FORCE_OPAQUE | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);
rayQueryInitialize(&rq, acc, RayDesc(flags, mask, 0.0, tmax_in, o, d));
var pg = GOut(-1.0, vec3<f32>(0.0, 1.0, 0.0), 0u, vec2<f32>(0.0));
var pprim = 0u;
@@ -113,10 +106,10 @@
// 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 its triangle's material has an alpha test (as
-// the build flags TRI_MASKED; a model instance's pool triangles carry no flags, and its record is not asked again).
+// 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_ROWS) && hit_row != NO_ROW) { return (hit_row & ROW_CUTOUT) != 0u; }
+ if (has(F_INST) && hit_row != NO_ROW) { return (hit_row & ROW_CUTOUT) != 0u; }
return material_at(triangle_material(attrs[h.tri])).uv2.w > 0.0;
}
@@ -127,24 +120,16 @@
@if(hwrt) const INSTANCE_BIT: u32 = 0x800000u;
-// Global triangle of a hit: a model instance's pool triangle (its cutout geometry 1 after the opaque one), or a
-// traversal group's.
+// 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) {
- // (Its mesh's geometries: where the second and the third start, scene.rs `InstMesh::part_offsets`; a third
- // only with glass.)
let rec = instance_at(custom & (INSTANCE_BIT - 1u));
- // (With rows: a geometry is a section, and its row has where its 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 (has_rows(rec)) {
- 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;
- }
- var at = select(0u, rec.info.w, geometry == 1u);
- if (has(F_IGLASS) && geometry == 2u) { at = bitcast<u32>(rec.n0.w); }
- return rec.info.x + at + prim;
+ 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);
}
diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgsl
index ab7a8be..b3cc71f 100644
--- a/renderer/shaders/trace_units.wgsl
+++ b/renderer/shaders/trace_units.wgsl
@@ -112,7 +112,7 @@ const UNIT_SHIFTED: u32 = 2u;
let x = intersect_tri(ro, rd, ti, hit.t);
if (x.x < hit.t) {
var flags = bitcast<u32>(tri_verts[ti * 3u].w);
- if (has(F_ROWS) && (ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags |= row_flags(urows, ti); }
+ if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags |= row_flags(urows, ti); }
if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }
if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, x.y, x.z, x.x)) { shadow_hole = true; continue; }
hit = Hit(x.x, ti, x.y, x.z, rec);
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 0fcb52e..61a11ad 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -252,7 +252,7 @@ fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec<wgpu::BlasBuildEntr
sizes
.iter()
.zip(parts)
- .map(|(size, &(first, _, _))| wgpu::BlasTriangleGeometry {
+ .map(|(size, &(first, _))| wgpu::BlasTriangleGeometry {
size,
vertex_buffer: &accel.verts,
first_vertex: ((accel.pool_first + first as usize) * 3) as u32,
@@ -819,8 +819,8 @@ pub struct Accel {
blases: Vec<(wgpu::Blas, usize, usize, wgpu::BlasTriangleGeometrySizeDescriptor)>,
/// One per instanced mesh (model space), referenced by the TLAS's model instances.
meshes: Vec<wgpu::Blas>,
- /// Per mesh: its (first pool triangle, count, opaque) geometries and their sizes (`mesh_entries`).
- mesh_geo: Vec<(Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)>,
+ /// 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).
@@ -1631,8 +1631,6 @@ pub const A_LIVE: u32 = 31;
// Kernel features (`override FEAT` in pathtrace.wgsl).
pub const F_MASKED: u32 = 1;
-/// An instance has rows (scene.rs `Row`): its mesh is its geometry's alone, a section's material is its row's.
-pub const F_ROWS: u32 = 2;
pub const F_FOG: u32 = 64;
pub const F_VOLUME: u32 = 128;
pub const F_TEX: u32 = 256;
@@ -1680,11 +1678,9 @@ pub const F_LISTS: u32 = 1 << 27;
/// every call otherwise, taken or not (Kabukicho's 64,224 emitters with a function, none on an instance: frame GPU
/// +2.7 %).
pub const F_IFUNC: u32 = 1 << 28;
-/// Glass among an instance's other triangles. With rows: a shadow ray steps through a hit whose row says glass
-/// (trace_hw.wgsl). A model's mesh: its glass geometry is not flagged opaque, and a shadow ray culls such geometry
-/// instead of forcing opacity. (Software traversal skips a unit's glass triangles by their flag, a row's or their
-/// own.) Compiled out where no instance mixes the two: one that is all glass is out of a shadow ray's way by its mask
-/// (`scene::rows_cast`, `scene::InstMesh::casts`).
+/// Glass among an instance's other sections: a shadow ray steps through a hit whose row says glass (trace_hw.wgsl;
+/// software traversal skips such a triangle of a unit). Compiled out where no instance mixes the two: one that is all
+/// glass is out of a shadow ray's way by its mask (`scene::rows_cast`).
pub const F_IGLASS: u32 = 1 << 29;
/// Whether a scene with more such lights has the light tiles (`F_LISTS`): `THREERT_LIGHT_TILES=1|0`, else everywhere
/// but Android. On Adreno 740 they took OpenStrikeRT's Foundry from 31 to 48 ms a frame (249 x 140, one bounce):
@@ -1759,18 +1755,15 @@ pub fn instance_features(scene: &Scene) -> u32 {
if scene.gpu_instances.is_empty() {
return media | particles;
}
- // (A model's mesh has its materials on its triangles and its classes in its counts; a mesh with sections has
- // them in its instances' rows.)
+ // (An instance's rows say its materials and their classes.)
let function = |mat: u32| scene.materials.get(mat as usize).is_some_and(|m| m.tex1[3] != 0);
- let on_triangles = scene.meshes.iter().filter(|m| m.sect_count == 0).flat_map(|m| &scene.pool_attrs[m.first as usize..(m.first + m.count) as usize]).any(|a| function(a.uv[3].to_bits()));
let rows = |i: &crate::scene::Instance| &scene.rows[i.rows as usize..][..scene.meshes[i.mesh as usize].sect_count as usize];
let any_row = |bit: u32| scene.instances.iter().any(|i| rows(i).iter().any(|r| r[0] & bit != 0));
let mixed_glass = scene.instances.iter().any(|i| i.bits & crate::scene::INST_GLASS != 0 && i.cast_shadow);
- let ifunc = if on_triangles || scene.rows.iter().any(|r| function(crate::scene::row_material(r))) { F_IFUNC } else { 0 };
- let iglass = if mixed_glass || scene.meshes.iter().any(|m| m.glass > 0 && m.glass < m.count) { F_IGLASS } else { 0 };
- let masked = any_row(crate::scene::ROW_CUTOUT) || scene.meshes.iter().any(|m| m.opaque + m.glass < m.count);
- let with_rows = if scene.instances.iter().any(|i| i.bits & crate::scene::INST_ROWS != 0) { F_ROWS } else { 0 };
- media | particles | ifunc | iglass | with_rows | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
+ let ifunc = if scene.rows.iter().any(|r| function(crate::scene::row_material(r))) { F_IFUNC } else { 0 };
+ let iglass = if mixed_glass { F_IGLASS } else { 0 };
+ let masked = any_row(crate::scene::ROW_CUTOUT);
+ media | particles | ifunc | iglass | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
@@ -1802,7 +1795,7 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures:
}
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 | F_ROWS; // not optional: they say what the instances' custom data / the object table / the records hold
+ f &= mask | F_HUGE | F_INST | F_PROC | F_TINT; // not optional: they say what the instances' custom data / the object table holds
}
// 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()) {
@@ -2401,9 +2394,7 @@ impl Gpu {
vertex_count: (count * 3) as u32,
index_format: None,
index_count: None,
- // (Every group's geometry is flagged opaque, the cutout ones' too: a query that forces opacity sees
- // them alike, and a shadow ray that culls what is not opaque, an instanced mesh's glass, must
- // still meet a cutout: trace_hw.wgsl.)
+ // (Every geometry is flagged opaque, a cutout's too: every query forces opacity, trace_hw.wgsl.)
flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
})
.collect();
@@ -2426,20 +2417,19 @@ impl Gpu {
}
// Instanced meshes: one opaque model-space BLAS each, a TLAS instance per placement (custom data
// INSTANCE_BIT | record; shadow casters mask 1).
- // Per mesh: (first triangle, count, opaque) geometries: the opaque part, the cutout part, the glass part
- // (`InstMesh::parts`).
- let mesh_parts: Vec<Vec<(u32, u32, bool)>> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count, opaque)| (m.first + at, count, opaque)).collect()).collect();
+ // 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();
let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts
.iter()
.map(|parts| {
parts
.iter()
- .map(|&(_, count, opaque)| wgpu::BlasTriangleGeometrySizeDescriptor {
+ .map(|&(_, count)| wgpu::BlasTriangleGeometrySizeDescriptor {
vertex_format: wgpu::VertexFormat::Float32x3,
vertex_count: count * 3,
index_format: None,
index_count: None,
- flags: if opaque { wgpu::AccelerationStructureGeometryFlags::OPAQUE } else { wgpu::AccelerationStructureGeometryFlags::empty() },
+ flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
})
.collect()
})
@@ -2455,10 +2445,10 @@ impl Gpu {
})
.collect();
// What the triangle BLASes hold (Metal's own sizes; each instanced mesh once) and their vertex buffer.
- let group_parts = groups.iter().filter(|g| g.1 > 0).map(|&(first, count, _)| vec![((first * 3) as u32, (count * 3) as u32, true)]);
- let mesh_vertex_parts = mesh_parts.iter().map(|ps| ps.iter().map(|&(first, count, opaque)| ((pool_first as u32 + first) * 3, count * 3, opaque)).collect::<Vec<_>>());
+ let group_parts = groups.iter().filter(|g| g.1 > 0).map(|&(first, count, _)| vec![((first * 3) as u32, (count * 3) as u32)]);
+ let mesh_vertex_parts = mesh_parts.iter().map(|ps| ps.iter().map(|&(first, count)| ((pool_first as u32 + first) * 3, count * 3)).collect::<Vec<_>>());
let mut blas_per_tri = 0.0;
- let parts: Vec<Vec<(u32, u32, bool)>> = group_parts.chain(mesh_vertex_parts).collect();
+ let parts: Vec<Vec<(u32, u32)>> = group_parts.chain(mesh_vertex_parts).collect();
if let Some(bytes) = parts.iter().map(|ps| self.tri_blas_bytes(&vbuf, ps)).sum::<Option<u64>>() {
timings.push(("tri_blas_mb".into(), (bytes + vbuf.size()) as f64 / (1 << 20) as f64));
let tris: u64 = parts.iter().flatten().map(|p| p.1 as u64 / 3).sum();
@@ -2528,7 +2518,7 @@ impl Gpu {
sizes
.iter()
.zip(parts)
- .map(|(size, &(first, _, _))| wgpu::BlasTriangleGeometry {
+ .map(|(size, &(first, _))| wgpu::BlasTriangleGeometry {
size,
vertex_buffer: &vbuf,
first_vertex: ((pool_first + first as usize) * 3) as u32,
@@ -2705,9 +2695,9 @@ impl Gpu {
}
}
- /// Bytes Metal allocates for a triangle BLAS over the (first vertex, vertex count, opaque) geometries of `verts`
- /// (non-indexed Float32x3, as every triangle BLAS here; None on other backends).
- fn tri_blas_bytes(&self, verts: &wgpu::Buffer, parts: &[(u32, u32, bool)]) -> Option<u64> {
+ /// Bytes Metal allocates for a triangle BLAS over the (first vertex, vertex count) geometries of `verts`
+ /// (non-indexed Float32x3 flagged opaque, as every triangle BLAS here; None on other backends).
+ fn tri_blas_bytes(&self, verts: &wgpu::Buffer, parts: &[(u32, u32)]) -> Option<u64> {
#[cfg(target_vendor = "apple")]
{
use wgpu::hal::{api::Metal, Device as _};
@@ -2716,7 +2706,7 @@ impl Gpu {
let entries = wgpu::hal::AccelerationStructureEntries::Triangles(
parts
.iter()
- .map(|&(first_vertex, vertex_count, opaque)| wgpu::hal::AccelerationStructureTriangles {
+ .map(|&(first_vertex, vertex_count)| wgpu::hal::AccelerationStructureTriangles {
vertex_buffer: Some(&*b),
vertex_format: wgpu::VertexFormat::Float32x3,
first_vertex,
@@ -2724,7 +2714,7 @@ impl Gpu {
vertex_stride: 12,
indices: None,
transform: None,
- flags: if opaque { wgpu::hal::AccelerationStructureGeometryFlags::OPAQUE } else { wgpu::hal::AccelerationStructureGeometryFlags::empty() },
+ flags: wgpu::hal::AccelerationStructureGeometryFlags::OPAQUE,
})
.collect(),
);
@@ -3259,17 +3249,17 @@ impl Gpu {
accel.mesh_geo[k as usize] = geo;
}
- fn mesh_blas_for(&self, accel: &Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> (wgpu::Blas, (Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {
+ 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, bool)> = mesh.parts(sections).into_iter().map(|(at, count, opaque)| (rel + at, count, opaque)).collect();
+ let parts: Vec<(u32, u32)> = mesh.parts(sections).into_iter().map(|(at, count)| (rel + at, count)).collect();
let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = parts
.iter()
- .map(|&(_, c, opaque)| wgpu::BlasTriangleGeometrySizeDescriptor {
+ .map(|&(_, c)| wgpu::BlasTriangleGeometrySizeDescriptor {
vertex_format: wgpu::VertexFormat::Float32x3,
vertex_count: c * 3,
index_format: None,
index_count: None,
- flags: if opaque { wgpu::AccelerationStructureGeometryFlags::OPAQUE } else { wgpu::AccelerationStructureGeometryFlags::empty() },
+ flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
})
.collect();
let flags = if std::env::var("THREERT_EDIT_BLAS").is_ok_and(|v| v == "trace") { wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE } else { wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD };
@@ -3686,7 +3676,6 @@ mod tests {
("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),
("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),
("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),
- ("F_ROWS", F_ROWS),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index c3594ea..8e1e44e 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -593,24 +593,16 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
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);
- // (A mesh with sections has no material on its triangles: its instances' rows say which are cutouts or glass.)
- let mut on_triangle = vec![true; sc.pool_tris.len()];
- for m in sc.meshes.iter().filter(|m| m.sect_count > 0) {
- on_triangle[m.first as usize..(m.first + m.count) as usize].fill(false);
- }
for (k, (t, a)) in sc.pool_tris.iter().zip(&sc.pool_attrs).enumerate() {
let [a0, b, c] = *t;
let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);
- // (A unit's triangles are in its tree's order, cutouts and glass among the rest: each carries its own flag, as
- // the still scene's do. Hardware traversal has them apart, in geometries of their own.)
- let material = sc.materials.get(a.uv[3].to_bits() as usize).filter(|_| trees.is_some() && on_triangle[k]);
- let (cutout, glass) = (material.is_some_and(|m| m.uv2[3] > 0.0), material.is_some_and(|m| m.layer[0] > 0.0));
- tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(if k < deforming { scene::TRI_DYNAMIC } else { 0 } | if cutout { scene::TRI_MASKED } else { 0 } | if glass { scene::TRI_NO_SHADOW } else { 0 })]);
+ // (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([e1.x, e1.y, e1.z, 0.0]);
tri_verts.push([e2.x, e2.y, e2.z, 0.0]);
attrs.push(*a);
}
- sc.gpu_instances = sc.instances.iter().map(|i| { let m = sc.meshes[i.mesh as usize]; i.gpu(pool_first as u32 + m.first, i.parts(&m)) }).collect();
+ sc.gpu_instances = sc.instances.iter().map(|i| i.gpu(pool_first as u32 + sc.meshes[i.mesh as usize].first)).collect();
// A row's section starts here in the triangles' table (hardware traversal: a hit's geometry is its section, its
// primitive counts from there).
for i in &sc.instances {
@@ -724,11 +716,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
emitter_tris.push(e);
}
}
- // (A mesh that emits: its emitting triangles numbered as they lie here, for its instances' emitters.)
- for m in sc.meshes.iter().filter(|m| m.emitters > 0) {
- let n = scene::number_emitters(&mut sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize], &sc.materials);
- assert_eq!(n, m.emitters, "a mesh's emitters as the build counted them");
- }
// (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();
@@ -739,24 +726,18 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
let (sections, at) = (m.sections(&sc.sections), sc.instances[r].rows as usize);
let rows = sc.rows.get(at..at + sections.len()).unwrap_or(&[]).to_vec();
let starts = scene::section_emitters(sections, &rows, &sc.materials);
- let count = if sections.is_empty() { m.emitters } else { scene::rows_emitters(sections, &rows, &sc.materials) };
+ let count = scene::rows_emitters(sections, &rows, &sc.materials);
if count == 0 {
continue;
}
let first = emitter_tris.len() as u32;
sc.instances[r].first_emitter = first;
- if let Some(g) = sc.gpu_instances.get_mut(r) {
- g.n[2][3] = f32::from_bits(first);
- }
for (k, start) in starts.iter().enumerate() {
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 numbered = |k: usize| match sections.is_empty() {
- true => (attrs[k].x[3].to_bits() as usize).checked_sub(1).map(|n| (n, attrs[k].uv[3].to_bits())),
- false => scene::section_slot(&attrs[k], &rows, &starts),
- };
+ 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) {
gpu_emitter_tris.push(GpuEmitterTri::of(&e, w, 0));
emitter_tris.push(e);
@@ -769,15 +750,13 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// triangle has: each instance of such a mesh gets its emitters in place too (live/edits.rs
// `add_material_emitters`).
let mut mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>> = std::collections::HashMap::new();
- // (A model's mesh has its materials on its triangles; a mesh with sections has them in its instances' rows, and
- // an instanced object's copies are not a mesh's instance here.)
+ // (The materials are in the instances' rows; a model's instance and an instanced object's copies are not a
+ // mesh's instance here.)
+ let own: std::collections::HashSet<u32> = sc.retained.own_mesh.values().copied().collect();
let (mut mesh_mats, mut others): (std::collections::HashSet<u32>, std::collections::HashSet<u32>) = Default::default();
- for m in sc.meshes.iter().filter(|m| m.sect_count == 0) {
- others.extend(sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize].iter().map(|a| a.uv[3].to_bits()));
- }
for i in &sc.instances {
let mats = sc.rows[i.rows as usize..][..sc.meshes[i.mesh as usize].sect_count as usize].iter().map(scene::row_material);
- if i.sub.is_none() { mesh_mats.extend(mats) } else { others.extend(mats) }
+ if i.sub.is_none() && own.contains(&i.mesh) { mesh_mats.extend(mats) } else { others.extend(mats) }
}
let mut fixed_mats: std::collections::HashSet<u32> = mesh_mats.union(&others).copied().collect();
for (k, a) in sc.attrs[..pool_first].iter().enumerate() {
@@ -946,9 +925,7 @@ fn unit_trees(sc: &mut scene::Scene) -> Option<Vec<Option<units::MeshTree>>> {
let tris: Vec<_> = t.order.iter().map(|&i| sc.pool_tris[r.start + i as usize]).collect();
sc.pool_tris[r.clone()].copy_from_slice(&tris);
let mut attrs: Vec<_> = t.order.iter().map(|&i| sc.pool_attrs[r.start + i as usize]).collect();
- if m.sect_count > 0 {
- scene::rank_in_sections(&mut attrs);
- }
+ scene::rank_in_sections(&mut attrs);
sc.pool_attrs[r.clone()].copy_from_slice(&attrs);
if !sc.pool_vcolors.is_empty() {
let colors: Vec<_> = t.order.iter().map(|&i| sc.pool_vcolors[r.start + i as usize]).collect();
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index a7df821..2304593 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -107,8 +107,10 @@ pub(super) struct EditState {
pub(super) uniform_said: bool,
/// (triangles, records, objects, words, TLAS instances) the scene itself has: the room starts there.
pub(super) base: (usize, usize, usize, usize, usize),
- /// The rows the scene itself has: the room's follow, one a record of the room (`row_at`).
- pub(super) row_base: 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).
@@ -121,10 +123,32 @@ impl EditState {
record >= self.base.1
}
- /// The row of what an edit places at `record` (one section: one row): the room's own for a record of the room,
- /// else the first of the rows the build gave the instance there.
- pub(super) fn row_at(&self, instances: &[scene::Instance], record: usize) -> usize {
- if self.in_room(record) { self.row_base + record - self.base.1 } else { instances.get(record).map_or(0, |i| i.rows as usize) }
+ /// `n` rows for what an edit places at `record`: the run it placed there before, if as long; the rows the build
+ /// gave the instance there, if it has as many; else a hole or the room's end. None: no room (the caller grows it).
+ pub(super) fn take_rows(&mut self, instances: &[scene::Instance], meshes: &[scene::InstMesh], record: usize, n: usize) -> Option<usize> {
+ match self.row_runs.get(&record) {
+ Some(&(at, len)) if len == n => return Some(at),
+ Some(&(at, len)) => {
+ self.rows.give(at, len);
+ self.row_runs.remove(&record);
+ }
+ None => {
+ let built = instances.get(record).filter(|_| !self.in_room(record));
+ if let Some(i) = built.filter(|i| meshes.get(i.mesh as usize).is_some_and(|m| m.sect_count as usize >= n)) {
+ return Some(i.rows as usize);
+ }
+ }
+ }
+ let at = self.rows.take(n)?;
+ self.row_runs.insert(record, (at, n));
+ Some(at)
+ }
+
+ /// The rows an edit placed at `record` go back to the room.
+ pub(super) fn give_rows(&mut self, record: usize) {
+ if let Some((at, len)) = self.row_runs.remove(&record) {
+ self.rows.give(at, len);
+ }
}
}
@@ -254,18 +278,29 @@ impl Grow<'_> {
true
}
- /// Kernel records and the TLAS (a record's instance is `inst_base` + it), and the room's rows, one a record
- /// (`row_base`: the scene's own before them).
- pub(super) fn records(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, accel: &mut gpu::Accel, words: &mut Heap<Stream>, row_base: usize) -> bool {
+ /// The instances' rows.
+ pub(super) fn rows(&self, h: &mut Holes, extra: usize, words: &mut Heap<Stream>) -> bool {
+ if !self.ok {
+ return false;
+ }
+ let cap = Self::cap(h, extra);
+ if !self.fits(&[words.size_with(Stream::Rows, (cap * 16) as u64)]) {
+ return false;
+ }
+ words.grow(&self.g.device, &self.g.queue, Stream::Rows, (cap * 16) as u64);
+ h.cap = cap;
+ true
+ }
+
+ /// Kernel records and the TLAS (a record's instance is `inst_base` + 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;
}
let cap = Self::cap(h, extra);
- let row_bytes = ((row_base + cap - h.base) * 16) as u64;
- if !self.fits(&[words.size_with(Stream::Rows, row_bytes)]) || !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {
+ if !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {
return false;
}
- words.grow(&self.g.device, &self.g.queue, Stream::Rows, row_bytes);
self.g.grow_tlas(accel, accel.inst_base + cap);
h.cap = cap;
true
@@ -299,6 +334,20 @@ impl Grow<'_> {
}
}
+/// `n` rows for what an edit places at `record` (`EditState::take_rows`), their section grown where it has no room.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn rows_for(edit: &mut EditState, grow: &Grow, words: &mut Heap<Stream>, instances: &[scene::Instance], meshes: &[scene::InstMesh], record: usize, n: usize) -> Result<usize, String> {
+ if let Some(at) = edit.take_rows(instances, meshes, record, n) {
+ return Ok(at);
+ }
+ if !grow.rows(&mut edit.rows, n, words) {
+ return Err("edit room: rows (particles, or the device's limits)".into());
+ }
+ edit.grows += 1;
+ edit.rebind = true;
+ edit.take_rows(instances, meshes, record, n).ok_or_else(|| "edit room: rows".to_string())
+}
+
/// Whether an object's instance is all of it, so that an edit can hide, move or take out the object by it: a mesh's,
/// or a still model's whose mesh has nothing flattened at each placement beside.
pub(super) fn whole(i: &scene::InstanceRef, instances: &[scene::Instance], meshes: &[scene::InstMesh]) -> bool {
@@ -802,7 +851,7 @@ impl LiveCore {
if !sub.iter().all(held) {
return false;
}
- let LoadedScene { tables, instances, gpu_instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;
+ let LoadedScene { tables, instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;
for k in sub {
let Some(scene::Draw::Instance(i)) = tables.retained.proxies.get_mut(&k).map(|p| &mut p.draw) else { continue };
if std::mem::replace(&mut i.moves, true) {
@@ -825,9 +874,6 @@ impl LiveCore {
tables.emitter_tris.push(e);
}
inst.first_emitter = first;
- if let Some(rec) = gpu_instances.get_mut(r as usize) {
- rec.n[2][3] = f32::from_bits(first);
- }
// (Its rows say where its sections' emitters start: where the run is now.)
let at = inst.rows as usize..inst.rows as usize + meshes[inst.mesh as usize].sect_count as usize;
for row in rows[at.clone()].iter_mut().filter(|row| row[2] != scene::NO_EMITTER) {
@@ -901,7 +947,7 @@ impl LiveCore {
}
let old = self.sc.gpu_instances[i as usize];
inst.world = w;
- let mut r = top.record(inst.gpu(old.info[0], [old.info[3], old.n[0][3].to_bits()]), inst.mesh, inst.cast_shadow);
+ let mut r = top.record(inst.gpu(old.info[0]), inst.mesh, inst.cast_shadow);
r.p = old.m;
self.sc.gpu_instances[i as usize] = r;
if merged {
@@ -1002,7 +1048,7 @@ impl LiveCore {
// 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, gpu_instances, meshes, pool_tris, sections, rows, edit, up, .. } = sc;
+ let LoadedScene { tables, instances, meshes, pool_tris, sections, rows, edit, up, .. } = sc;
let moving = tables.retained.moving_records();
// Each mesh's triangles as the pool has them: their section and their index in it (`rank_in_sections`).
let mut places: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
@@ -1046,10 +1092,6 @@ impl LiveCore {
}
let first = tables.emitter_tris.len() as u32;
instances[r].first_emitter = first;
- if let Some(rec) = gpu_instances.get_mut(r) {
- rec.n[2][3] = f32::from_bits(first);
- up.heap.write(q, Table::Instances, (r * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(rec));
- }
for (s, start) in starts.iter().enumerate() {
rows[at + s][2] = start.map_or(scene::NO_EMITTER, |x| first + x);
}
@@ -1334,7 +1376,7 @@ impl LiveCore {
emitting.push((rec0 + i) as u32);
}
let inst = &sc.instances[first + i];
- (top.record(inst.gpu(old.info[0], [old.info[3], old.n[0][3].to_bits()]), inst.mesh, casts), scene::copy_row(row, emits && hidden))
+ (top.record(inst.gpu(old.info[0]), inst.mesh, casts), scene::copy_row(row, emits && hidden))
};
rec.p = old.m;
sc.gpu_instances[rec0 + i] = rec;
@@ -1452,7 +1494,7 @@ impl LiveCore {
// (A node its clip scales to nothing: at a point, where no ray sees it.)
let (w, gone) = scene::placed_world(w, inst.world.w_axis.truncate());
inst.world = w;
- let mut r = inst.gpu(old.info[0], [old.info[3], old.n[0][3].to_bits()]);
+ let mut r = inst.gpu(old.info[0]);
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));
@@ -1542,12 +1584,12 @@ impl LiveCore {
}
let n = pg.order.len();
let (mut v, mut at, mut b, mut t) = (Vec::with_capacity(n * 3), Vec::with_capacity(n), Vec::with_capacity(n * 3), Vec::with_capacity(n));
- for &(k, mat) in &pg.order {
+ for &(k, section, rank) in &pg.order {
let q = &tris[k as usize];
let (e1, e2) = (q.p[1] - q.p[0], q.p[2] - q.p[0]);
// The flag word keeps TRI_DYNAMIC: the kernel takes a deforming mesh's motion from `prev_verts`.
v.extend_from_slice(&[[q.p[0].x, q.p[0].y, q.p[0].z, f32::from_bits(scene::TRI_DYNAMIC)], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
- at.push(scene::tri_attr(q.p, q.n, q.uv, q.tangent, mat));
+ at.push(scene::section_attr(q.p, q.n, q.uv, q.tangent, section, rank));
b.extend(scene::blas_tri(q.p.map(|p| p.to_array())));
t.push(q.p.map(glam::Vec3A::from));
}
@@ -1866,6 +1908,7 @@ impl LiveCore {
}
if edit.in_room(r0) {
edit.records.give(r0, cap);
+ edit.give_rows(r0);
edit.objects.give(place.object as usize, cap);
drop_mesh_user(mesh, edit, tables, meshes);
}
@@ -1889,6 +1932,7 @@ impl LiveCore {
// What it held goes back to the room (the build's records and entries stay until the next rebuild).
if edit.in_room(record) {
edit.records.give(record, 1);
+ edit.give_rows(record);
}
}
if let Some(k) = proxy.and_then(|p| p.object).filter(|&k| k as usize >= edit.base.2) {
@@ -2015,12 +2059,20 @@ impl LiveCore {
if !top.has_mesh(mesh) {
return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into());
}
+ // (Shadow rays pass the glass among a caster's other sections under a kernel feature: a scene where
+ // no instance of the model cast a shadow was built without it.)
+ let its = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?;
+ if scene::rows_bits(its) & scene::INST_GLASS != 0 && scene::rows_cast(its, o.cast_shadow) && features & gpu::F_IGLASS == 0 {
+ return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());
+ }
*edit.users.entry(mesh).or_default() += 1;
if let Some(k) = was {
drop_mesh_user(k, edit, tables, meshes);
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
- let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), mesh, inst.cast_shadow);
+ // (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")?;
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(mine) };
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
(at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)
@@ -2033,7 +2085,7 @@ impl LiveCore {
_ => unreachable!(),
};
let (geometry, material) = (&geometry, &material);
- if features & gpu::F_INST == 0 || features & gpu::F_ROWS == 0 {
+ if features & gpu::F_INST == 0 {
return Err("the scene's first instanced mesh (kernel feature)".into());
}
// A placement without size (a build places it, unseen at a point), or instancing off (it flattens).
@@ -2148,7 +2200,7 @@ impl LiveCore {
}
};
sections[sect_first as usize] = scene::Section { first: 0, count: t.len() as u32, slot: 0 };
- let im = scene::InstMesh { sect_first, sect_count: 1, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32, 0) };
+ let im = scene::InstMesh { sect_first, sect_count: 1, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };
let k = match &mut top {
gpu::Top::Hw(accel) => match dead {
Some(k) => {
@@ -2231,7 +2283,7 @@ impl LiveCore {
edit.objects.give(object, 1);
let r0 = match edit.records.take(cap) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel, &mut up.words, edit.row_base), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(cap).ok_or("edit room: records")?
@@ -2258,9 +2310,10 @@ impl LiveCore {
if tables.objects.len() < (o0 + cap) * st {
tables.objects.resize((o0 + cap) * st, [0.0; 4]);
}
+ // (A row a copy, the copies' in a run as their records are.)
+ let run = rows_for(edit, &grow, &mut up.words, instances, meshes, r0, cap)?;
for (i, &(wm, hidden)) in placed.iter().enumerate() {
- // (Its row: the room's, as its record is.)
- let row_at = edit.row_at(instances, r0 + i);
+ let row_at = run + i;
let mut row = scene::row_of(mat, &tables.materials);
row[1] = edit.pool_first as u32 + im.first;
let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: scene::rows_cast(&[row], o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: row_at as u32, bits: scene::rows_bits(&[row]) };
@@ -2283,7 +2336,7 @@ 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, inst.parts(&im)), mesh, inst.cast_shadow);
+ let rec = top.record(inst.gpu((edit.pool_first as u32) + 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);
@@ -2300,7 +2353,7 @@ impl LiveCore {
// casts are the row's.)
let row = [scene::row_of(mat, &tables.materials)];
let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&row, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&row) };
- let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, inst.parts(&im)), mesh, inst.cast_shadow);
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
(at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)
@@ -2313,7 +2366,7 @@ impl LiveCore {
_ => {
let r = match edit.records.take(1) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel, &mut up.words, edit.row_base), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(1).ok_or("edit room: records")?
@@ -2327,19 +2380,30 @@ impl LiveCore {
// has as many and none is the light tree's (those keep their place there, at no weight); else a new one at
// the list's end. Its first goes in its record.
let (mut gpu, mut blas) = (gpu, blas);
- if let (Placed::Mesh(inst), Kind::Mesh { material, .. }) = (&mut blas, &o.kind) {
+ if let Placed::Mesh(inst) = &mut blas {
let im = meshes[inst.mesh as usize];
- let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
- // Its row (one section: the geometry whole), where its record's is.
- let row_at = edit.row_at(instances, record);
- let mut row = scene::row_of(mat, &tables.materials);
- row[1] = edit.pool_first as u32 + im.first;
+ // Its rows: a mesh's one (the geometry whole, with the object's material), a model's as its mesh has
+ // them; each with where its section's triangles start.
+ let material = match &o.kind {
+ Kind::Mesh { material, .. } => Some(*tables.retained.materials.get(material).ok_or("unknown material")?),
+ _ => None,
+ };
+ let mut mine: Vec<scene::Row> = match material {
+ Some(mat) => vec![scene::row_of(mat, &tables.materials)],
+ None => tables.retained.mesh_rows.get(&inst.mesh).cloned().ok_or("a model's mesh without its rows")?,
+ };
+ for (s, row) in im.sections(sections).iter().zip(&mut mine) {
+ row[1] = edit.pool_first as u32 + im.first + s.first;
+ }
+ let row_at = rows_for(edit, &grow, &mut up.words, instances, meshes, record, mine.len())?;
(inst.rows, gpu.info[3]) = (row_at as u32, row_at as u32);
- if tables.materials.get(mat as usize).is_some_and(scene::emissive) {
+ // A mesh whose material emits: its emitters, a run of the light list. The run its record had, if that
+ // has as many and none is the light tree's (those keep their place there, at no weight); else a new
+ // one at the list's end. Its first goes in its row. (A model placed here has none: `model_mesh`.)
+ if let Some(mat) = material.filter(|&mat| tables.materials.get(mat as usize).is_some_and(scene::emissive)) {
let old = emitter_run(&tables.emitter_tris, instances, record as u32);
let first = if old.len() == im.count as usize && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
- (inst.first_emitter, row[2]) = (first as u32, first as u32);
- gpu.n[2][3] = f32::from_bits(first as u32);
+ (inst.first_emitter, mine[0][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, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.count as usize, &tables.materials, o.driven || world.movable(id));
for (j, (e, w)) in made.into_iter().enumerate() {
@@ -2352,11 +2416,11 @@ impl LiveCore {
tables.emissive.insert(mat);
emitters_changed = true;
}
- w_rows.put((row_at * 16) as u64, bytemuck::bytes_of(&row));
- if rows.len() <= row_at {
- rows.resize(row_at + 1, [0; 4]);
+ w_rows.put((row_at * 16) as u64, bytemuck::cast_slice(&mine));
+ if rows.len() < row_at + mine.len() {
+ rows.resize(row_at + mine.len(), [0; 4]);
}
- rows[row_at] = row;
+ rows[row_at..row_at + mine.len()].copy_from_slice(&mine);
}
w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));
if record >= gpu_instances.len() {
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 8a85db4..41bf2d9 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -20,6 +20,11 @@ fn world() -> World {
w.set_transform(11, Vec3::new(-0.4, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_object(12, "lamp".into(), None, mesh(3, 5), true, false).unwrap();
w.set_transform(12, Vec3::new(0.6, 0.3, 1.5), glam::Quat::from_rotation_y(2.6), Vec3::ONE).unwrap();
+ // (A mesh of two sections behind the camera: an instance's rows are not at its record's index, here and for
+ // everything an edit places after.)
+ w.set_geometry(9, Geometry { groups: vec![[0, 3, 0], [3, 3, 1]], ..quad(0.05) }).unwrap();
+ w.set_object(9, "two".into(), None, Kind::Mesh { geometry: 9, material: 1, own_blas: false, materials: vec![1, 1] }, true, false).unwrap();
+ w.set_transform(9, Vec3::new(0.0, 0.0, 9.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
let sun = serde_json::from_value(serde_json::json!({ "type": "directional", "color": [1.0, 0.9, 0.8], "castShadow": true, "intensity": 2.0, "angularDiameter": 0.5 })).unwrap();
w.set_object(20, "sun".into(), None, Kind::Light(sun), true, false).unwrap();
w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.5) * glam::Quat::from_rotation_y(0.4), Vec3::ONE).unwrap();
@@ -95,6 +100,13 @@ fn picture(core: &mut LiveCore, frames: u32) -> Vec<u8> {
bytes
}
+/// Whether rows `at .. at + n` are the room's to give again (a hole holds them, or they are past what is in use): what
+/// an object an edit placed gives back when it goes.
+fn rows_free(c: &LiveCore, at: u32, n: u32) -> bool {
+ let rows = &c.sc.edit.rows;
+ at as usize >= rows.end || rows.free.iter().any(|(&start, &len)| start <= at as usize && (at + n) as usize <= start + len)
+}
+
/// The view without its histories (the radiance cache emptied, the frames' histories reset), as a new view is.
fn forget(core: &mut LiveCore) {
if let Some(c) = &core.cache {
@@ -441,17 +453,13 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
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:?}");
}
- if record.n[1][3].to_bits() & scene::INST_ROWS == 0 {
- assert_eq!((record.n[2][3].to_bits(), record.n[2][3].to_bits() + a.x[3].to_bits()), (inst.first_emitter, i as u32 + 1), "{what}: triangle {} of instance {} finds its emitter", e.tri, e.inst);
- alive += 1;
- continue;
- }
- // An instance with rows: 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 section's row as the GPU has it says the material and where the section's emitters start, the
+ // triangle its index among them.
let at = (record.info[3] + a.uv[3].to_bits()) as usize;
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], record.n[2][3].to_bits()), (inst.rows, inst.first_emitter), "{what}: instance {}'s record has its rows and its first emitter", e.inst);
+ assert_eq!(record.info[3], inst.rows, "{what}: instance {}'s record has its rows", e.inst);
+ assert!(inst.first_emitter <= i as u32, "{what}: emitter {i} is of instance {}'s run, from {}", e.inst, inst.first_emitter);
assert_eq!((row[2].wrapping_add(a.x[3].to_bits()), scene::row_material(&row)), (i as u32, e.mat), "{what}: triangle {} of instance {} finds its emitter, of its row's material", e.tri, e.inst);
}
alive += 1;
@@ -649,6 +657,7 @@ fn an_emitting_instanced_object_added_in_place_is_lit_as_a_build_lights_it() {
}),
),
];
+ let mut run = 0;
for (what, edit) in &edits {
let what = format!("an emitting instanced object {what} in place, {} a light tree", if tree { "with" } else { "without" });
// (Its material covers instances' triangles once it is added: `Tables::fixed_mats`.)
@@ -657,6 +666,14 @@ fn an_emitting_instanced_object_added_in_place_is_lit_as_a_build_lights_it() {
edit(&mut w);
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
assert!(covers(&live) && (before || what.contains("added")), "{what}: its material is among those of instances' triangles");
+ // Its copies' rows: a run of the room's, the room's again once it is removed.
+ match live.sc.tables.retained.instanced(15) {
+ Some(place) => {
+ run = live.sc.instances[place.first as usize].rows;
+ assert!((0..3).all(|i| live.sc.instances[place.first as usize + i].rows == run + i as u32) && !rows_free(&live, run, 3), "{what}: a row a copy, in a run");
+ }
+ None => assert!(rows_free(&live, run, 3), "{what}: its rows are the room's again"),
+ }
if live.sc.tables.emitter_tris.iter().any(|e| e.area > 0.0) {
list_is_its_triangles(&what, &live);
}
@@ -1363,7 +1380,7 @@ fn objects_of_one_geometry_share_its_mesh_whatever_their_materials() {
assert!((41..46).all(|id| mesh_of(&live, id) == shared), "the six objects of one geometry share its mesh");
assert!(live.sc.meshes[shared as usize].colored && live.sc.meshes[shared as usize].sect_count == 1);
let features = live.sc.up.kernel.features;
- assert_eq!(features & (gpu::F_ROWS | gpu::F_MASKED | gpu::F_VCOLOR), gpu::F_ROWS | gpu::F_MASKED | gpu::F_VCOLOR);
+ assert_eq!(features & (gpu::F_MASKED | gpu::F_VCOLOR), gpu::F_MASKED | gpu::F_VCOLOR);
let placed = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).unwrap().instance as usize].clone();
assert!(!placed(&live, 44).cast_shadow && placed(&live, 43).cast_shadow, "glass alone casts no shadow");
list_is_its_triangles("objects of one geometry, at the build", &live);
@@ -1391,13 +1408,16 @@ fn objects_of_one_geometry_share_its_mesh_whatever_their_materials() {
assert!(!live.commit(&mut w).unwrap(), "an object of the geometry placed: in place ({:?})", live.fallback);
assert_eq!((mesh_of(&live, 46), live.sc.meshes.len(), live.sc.pool_tris.len()), (shared, meshes, triangles), "it shares the mesh: none made");
against_a_build("an object of the geometry placed in place", &mut live, &w);
- // Another material for an object: its row. The plain one emits now, the one that emitted is a cutout.
- for (id, material, at) in [(41, 5, Vec3::new(-1.35, 0.55, 0.6)), (45, 64, Vec3::new(2.25, 0.55, 0.6))] {
+ // Another material for an object: its row, the one it had (the build's, or the room's for the one placed above).
+ // The plain one emits now, the one that emitted is a cutout, the glass one placed in place is plain.
+ for (id, material, at) in [(41, 5, Vec3::new(-1.35, 0.55, 0.6)), (45, 64, Vec3::new(2.25, 0.55, 0.6)), (46, 62, Vec3::new(0.2, -0.5, 0.9))] {
+ let row = placed(&live, id).rows;
place(&mut w, id, material, at);
let what = format!("object {id} given material {material}");
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
assert_eq!((mesh_of(&live, id), live.sc.meshes.len(), live.sc.pool_tris.len()), (shared, meshes, triangles), "{what}: it keeps the mesh, none made");
- assert_eq!(scene::row_material(&live.sc.rows[placed(&live, id).rows as usize]), live.sc.tables.retained.materials[&material], "{what}: its row names it");
+ assert_eq!(placed(&live, id).rows, row, "{what}: it keeps its row");
+ assert_eq!(scene::row_material(&live.sc.rows[row as usize]), live.sc.tables.retained.materials[&material], "{what}: its row names it");
against_a_build(&what, &mut live, &w);
}
// A geometry with colours that no object read at the build: its mesh was made without them, and an object that
@@ -1480,8 +1500,8 @@ fn glass_among_an_instances_sections_is_lit_through_as_glass_alone() {
Err(e) => return eprintln!("skipped: {e}"),
};
let window = one.sc.instances.iter().find(|i| i.name == "window").expect("the window is an instance").clone();
- assert_eq!((window.bits, window.cast_shadow, one.sc.meshes[window.mesh as usize].sect_count), (scene::INST_ROWS | scene::INST_GLASS, true, 2), "glass and a frame: one mesh, which casts");
- let wanted = gpu::F_ROWS | gpu::F_IGLASS | if cutout { gpu::F_MASKED } else { 0 };
+ assert_eq!((window.bits, window.cast_shadow, one.sc.meshes[window.mesh as usize].sect_count), (scene::INST_GLASS, true, 2), "glass and a frame: one mesh, which casts");
+ let wanted = gpu::F_IGLASS | if cutout { gpu::F_MASKED } else { 0 };
assert_eq!(one.sc.up.kernel.features & (wanted | gpu::F_MASKED), wanted);
assert_eq!(one.sc.base.counts2[1], 1, "the sky is sampled as a light");
let mut two = open(&scene(1, cutout)).unwrap();
@@ -1493,6 +1513,134 @@ fn glass_among_an_instances_sections_is_lit_through_as_glass_alone() {
}
}
+/// A model of several materials placed in place has its rows from the room: as many as its mesh's sections, the
+/// file's materials, each where its section's triangles start, on the GPU as here, its record naming their first.
+/// It is drawn as a build draws it. Removed, it gives the rows back, and the next one placed takes them.
+#[test]
+fn a_model_of_several_materials_placed_in_place_has_its_rows() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
+ // (An opaque, a cutout and a glass quad: three sections.)
+ let model = || Kind::Model { uri: "tests/render/data/frame-pane.glb".into(), nodes: None, animation: None, functions: vec![] };
+ let mut w = world();
+ w.set_object(30, "first".into(), None, model(), true, false).unwrap();
+ w.set_transform(30, Vec3::new(-0.5, 0.3, 0.8), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ // (A mesh the scene says it edits: room for what is placed.)
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(0.9, -0.1, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let built = live.sc.rows.len();
+ let placed = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).expect("a model is an instance").instance as usize].clone();
+ let read = |c: &LiveCore, b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {
+ let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut e = c.g.device.create_command_encoder(&Default::default());
+ e.copy_buffer_to_buffer(b, at, &to, 0, bytes);
+ c.g.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ c.g.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let bytes = to.slice(..).get_mapped_range().unwrap().to_vec();
+ bytes
+ };
+ let mut check = |live: &mut LiveCore, w: &World, id: u32, what: &str| -> u32 {
+ let (first, it) = (placed(live, 30), placed(live, id));
+ let im = live.sc.meshes[it.mesh as usize];
+ assert_eq!((it.mesh, im.sect_count), (first.mesh, 3), "{what}: an instance of the model's mesh, of three sections");
+ assert!(it.rows as usize >= built, "{what}: its rows are the room's");
+ let rows = |i: &scene::Instance| live.sc.rows[i.rows as usize..][..3].to_vec();
+ assert_eq!((rows(&it), it.bits, it.cast_shadow), (rows(&first), first.bits, first.cast_shadow), "{what}: the mesh's rows, as the first has them");
+ let up = &live.sc.up;
+ let on_gpu: Vec<scene::Row> = bytemuck::pod_collect_to_vec(&read(live, &up.words.buffer, up.words.at(crate::heap::Stream::Rows) + it.rows as u64 * 16, 48));
+ assert_eq!(on_gpu, rows(&it), "{what}: its rows on the GPU");
+ let record = live.sc.tables.retained.instance(id).unwrap().instance as u64;
+ let size = std::mem::size_of::<scene::GpuInstance>() as u64;
+ let rec: scene::GpuInstance = bytemuck::pod_read_unaligned(&read(live, &up.heap.buffer, up.heap.at(Table::Instances) + record * size, size));
+ assert_eq!(rec.info[3], it.rows, "{what}: its record names its rows");
+ let mut fresh = open(w).unwrap();
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ it.rows
+ };
+ let place = |w: &mut World, id: u32, at: Vec3| {
+ w.set_object(id, format!("m{id}"), None, model(), true, false).unwrap();
+ w.set_transform(id, at, glam::Quat::from_rotation_y(0.3), Vec3::splat(0.5)).unwrap();
+ };
+ place(&mut w, 31, Vec3::new(0.5, -0.3, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "a model placed: in place ({:?})", live.fallback);
+ let rows = check(&mut live, &w, 31, "a model placed in place");
+ w.remove(31);
+ assert!(!live.commit(&mut w).unwrap(), "the model removed: in place ({:?})", live.fallback);
+ assert!(rows_free(&live, rows, 3), "the model removed: its rows are the room's again");
+ place(&mut w, 32, Vec3::new(0.2, 0.5, 1.0));
+ assert!(!live.commit(&mut w).unwrap(), "another placed: in place ({:?})", live.fallback);
+ assert_eq!(check(&mut live, &w, 32, "another placed after the first was removed"), rows, "it takes the rows the first gave back");
+}
+
+/// A model with glass among its sections, in a scene where no instance of it casts a shadow: the kernel was built
+/// without what has a shadow ray pass such glass, so the first instance that casts is placed by a rebuild.
+#[test]
+fn the_first_caster_with_glass_among_its_sections_is_a_rebuilds() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
+ let model = || Kind::Model { uri: "tests/render/data/frame-pane.glb".into(), nodes: None, animation: None, functions: vec![] };
+ let mut w = world();
+ w.set_object(30, "first".into(), None, model(), false, false).unwrap();
+ w.set_transform(30, Vec3::new(-0.5, 0.3, 0.8), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ // (A mesh the scene says it edits: room for what is placed.)
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(0.9, -0.1, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_eq!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "no caster has glass among its sections");
+ // (Upright before the wall, its pane 1 m wide: the pane's shadow is the sun's light through it.)
+ w.set_object(31, "caster".into(), None, model(), true, false).unwrap();
+ w.set_transform(31, Vec3::new(0.5, 0.0, 0.5), glam::Quat::from_rotation_x(std::f32::consts::FRAC_PI_2), Vec3::splat(2.0)).unwrap();
+ live.commit(&mut w).unwrap();
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert_ne!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "the kernel passes its glass");
+}
+
+/// Models in a shared pose posed again in place (tests/render/data/arm.glb: a skinned strip, a dark half and a light
+/// half that a joint swings): their mesh is skinned where it lies, each triangle still in its section. The picture is
+/// a build's.
+#[test]
+fn models_in_a_shared_pose_posed_again_keep_their_sections() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
+ let bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true });
+ let mut w = world();
+ for (id, x) in [(30, -0.7), (31, 0.7)] {
+ w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: bend(0.0), functions: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(x, -1.0, 0.8), glam::Quat::IDENTITY, Vec3::splat(2.0)).unwrap();
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let groups = &live.sc.tables.retained.pose_groups;
+ assert_eq!((groups.len(), live.sc.meshes[groups[0].mesh as usize].sect_count), (1, 2), "the two share a pose's mesh, of two sections");
+ for id in [30, 31] {
+ w.set_animation(id, bend(0.75)).unwrap();
+ }
+ let rebuilt = live.commit(&mut w).unwrap();
+ assert!(!(rebuilt && live.g.hwrt), "the pose changed in place ({:?})", live.fallback);
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));
+}
+
/// A scene whose only volume is hidden has its media passes made when it is loaded: the frame that shows the volume
/// compiles nothing (an idle fireball's first fire).
#[test]
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 212157a..0fcb945 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -15,8 +15,8 @@ pub(super) struct LoadedScene {
pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,
pub(super) meshes: Vec<scene::InstMesh>,
pub(super) instances: Vec<scene::Instance>,
- /// The meshes' sections and the instances' rows as the GPU has them (`scene::Scene::sections`, `rows`); a record
- /// an edit places has its row at `EditState::row_at`.
+ /// The meshes' sections and the instances' rows as the GPU has them (`scene::Scene::sections`, `rows`); what an
+ /// edit places takes its rows from the room (`EditState::take_rows`).
pub(super) sections: Vec<scene::Section>,
pub(super) rows: Vec<scene::Row>,
/// The instances' kernel records as uploaded (movable ones are rewritten when they move), then the procedural
@@ -293,7 +293,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
rebind: false,
uniform_said: false,
base: room_base,
- row_base: rows.len(),
+ rows: Holes::new(rows.len(), rows.len() + room.records),
+ row_runs: Default::default(),
pool_first: prep.groups.iter().sum(),
blobs,
};
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 68636b2..65ad9e1 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -552,7 +552,7 @@ 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(), "pool_triangles": sc.pool_tris.len(),
+ "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(),
"adapter": g.adapter_info.name, "backend": format!("{:?}", g.adapter_info.backend), "hwrt": g.hwrt,
"ev100": ev100, "denoise": denoiser, "preset": preset.name,
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 26c59b1..0076ff1 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -52,17 +52,12 @@ pub fn copy_row(mut row: ObjectRow, dark: bool) -> ObjectRow {
}
/// A mesh its instances place: its triangles once, in model space, in the `pool_*` arrays; one BLAS, one TLAS
-/// instance per placement. A geometry's (`section_mesh`: its materials are its instances'), or a model's.
+/// instance per placement. A geometry's (`section_mesh`) or a model's (`model_sections`); its materials are its
+/// instances' (`Instance::rows`).
#[derive(Clone, Copy, Debug)]
pub struct InstMesh {
pub first: u32,
pub count: u32,
- /// The first `opaque` pool triangles are opaque, the last `glass` glass, those between cutout (alpha-tested):
- /// a BLAS geometry each (`parts`).
- pub opaque: u32,
- /// Its last `glass` triangles are of a glass material: shadow rays pass them (their geometry is not flagged
- /// opaque, and a shadow ray culls such, trace_hw.wgsl), `glass_tr` weighs what they let through.
- pub glass: u32,
/// Triangles each placement flattens instead (`flatten_coincident`'s pairs), in the build's rest arrays.
pub rest_first: u32,
pub rest_count: u32,
@@ -71,13 +66,7 @@ pub struct InstMesh {
pub hi: Vec3A,
/// Its triangles change (a shared pose, `PoseGroup`): its BLAS is rebuilt with them.
pub deforms: bool,
- /// A model's mesh: how many emitters an instance of it has in the light list, its triangles of an emitting
- /// material, numbered in their attributes as they lie in the triangles' table (x.w - 1; `number_emitters`). 0: it
- /// does not emit. (A mesh with sections: `rows_emitters`, an instance's.)
- pub emitters: u32,
- /// Its sections (`Section`), in `Scene::sections`: a mesh of a geometry alone, whose materials are its instances'
- /// (`Instance::rows`). None (`sect_count` 0): a model's mesh, its materials on its triangles and its triangles
- /// by class (`opaque`, `glass`, `emitters`; a mesh with sections says all opaque there, and no emitters).
+ /// Its sections (`Section`), in `Scene::sections`: a geometry of its BLAS each, a row of its instances each.
pub sect_first: u32,
pub sect_count: u32,
/// Its triangles carry its geometry's vertex colours (a material says whether it reads them).
@@ -123,10 +112,10 @@ pub fn rows_cast(rows: &[Row], cast_shadow: bool) -> bool {
cast_shadow && !rows.iter().all(|r| r[0] & ROW_GLASS != 0)
}
-/// The bits of an instance's record for its rows (`INST_ROWS`, and which classes are among them).
+/// The bits of an instance's record for its rows: which classes are among them.
pub fn rows_bits(rows: &[Row]) -> u32 {
let any = |bit: u32| rows.iter().any(|r| r[0] & bit != 0);
- INST_ROWS | if any(ROW_CUTOUT) { INST_CUTOUT } else { 0 } | if any(ROW_GLASS) { INST_GLASS } else { 0 }
+ (if any(ROW_CUTOUT) { INST_CUTOUT } else { 0 }) | if any(ROW_GLASS) { INST_GLASS } else { 0 }
}
/// How many emitters an instance with these rows has in the light list: every triangle of its sections whose
@@ -164,37 +153,18 @@ pub fn deforming_pool(meshes: &[InstMesh]) -> usize {
}
impl InstMesh {
- /// Its BLAS geometries, those with triangles: each one's first triangle in the mesh, how many, and whether it is
- /// flagged opaque. A mesh with sections (`sections`: the scene's): one a section, all flagged opaque, whatever
- /// an instance's materials are. A model's mesh: one a class, all flagged opaque but the glass (a query that forces
- /// opacity sees every one alike, a shadow ray culls the glass).
- pub fn parts(&self, sections: &[Section]) -> Vec<(u32, u32, bool)> {
- if self.sect_count > 0 {
- return self.sections(sections).iter().map(|s| (s.first, s.count, true)).collect();
- }
- let cutout = self.count - self.opaque - self.glass;
- [(0, self.opaque, true), (self.opaque, cutout, true), (self.opaque + cutout, self.glass, false)].into_iter().filter(|p| p.1 > 0).collect()
- }
-
- /// Where its second and its third geometry start in the mesh (0: there is none): the record has them, for a hit's
- /// triangle from its geometry and primitive (trace_hw.wgsl `hit_tri`).
- pub fn part_offsets(&self) -> [u32; 2] {
- let p = self.parts(&[]);
- [p.get(1).map_or(0, |p| p.0), p.get(2).map_or(0, |p| p.0)]
+ /// 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
+ /// glass's hits are told by the instance's rows).
+ pub fn parts(&self, sections: &[Section]) -> Vec<(u32, u32)> {
+ self.sections(sections).iter().map(|s| (s.first, s.count)).collect()
}
- /// Its sections among the scene's (none: a model's mesh).
+ /// Its sections among the scene's.
pub fn sections<'a>(&self, sections: &'a [Section]) -> &'a [Section] {
&sections[self.sect_first as usize..(self.sect_first + self.sect_count) as usize]
}
- /// Whether an instance of it casts shadows: as its object says, and never when the mesh is all glass. Such an
- /// instance is out of a shadow ray's way by its mask, as one that casts none is; a mesh with glass among other
- /// triangles has it culled by its geometry's flag (`parts`, gpu.rs `F_IGLASS`).
- pub fn casts(&self, cast_shadow: bool) -> bool {
- cast_shadow && self.glass < self.count
- }
-
/// World bounds of a placement: the box of the transformed model-space box.
pub fn placed_bounds(&self, m: Mat4) -> (Vec3A, Vec3A) {
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
@@ -226,19 +196,17 @@ pub struct Instance {
/// keep its mesh and its place above the triangles: it comes back in place. (One that an edit took out is hidden
/// and not this: a rebuild draws it again.)
pub masked: bool,
- /// Its first emitter in the light list, if it has emitters (`InstMesh::emitters`; with sections,
- /// `rows_emitters`): set where the list is made (lib.rs `prepare`, the live edits); the record carries it (n2.w),
- /// for the rays that hit an emitter of a model's mesh, and a section's row has where the section's start.
+ /// Its first emitter in the light list, if it has emitters (`rows_emitters`): set where the list is made (lib.rs
+ /// `prepare`, the live edits). A section's row has where the section's start, for the rays that hit one.
pub first_emitter: u32,
/// Its rows in `Scene::rows`, one a section of its mesh (`InstMesh::sect_count`), and the record's bits for them
- /// (`rows_bits`; 0: a model's instance, without rows).
+ /// (`rows_bits`).
pub rows: u32,
pub bits: u32,
}
/// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose),
-/// (first triangle in the GPU order, object index, texture-LOD offset bits, its rows' first or, without rows, first
-/// cutout triangle - first), and the
+/// (first triangle in the GPU order, object index, texture-LOD offset bits, its rows' first), and the
/// world matrix rows of the previous frame (a movable instance's motion vectors; the same rows when it did not move).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
@@ -250,28 +218,19 @@ pub struct GpuInstance {
}
impl Instance {
- /// Kernel record with its mesh's first triangle at `first` in the GPU order; `parts` = where its mesh's second
- /// and third geometry start (`InstMesh::part_offsets`; the third's in n0.w, which hardware traversal leaves
- /// free and a unit's record takes for its tree's root).
- pub fn gpu(&self, first: u32, parts: [u32; 2]) -> GpuInstance {
+ /// Kernel record with its mesh's first triangle at `first` in the GPU order. (n0.w is left free: a unit's record
+ /// takes it for its tree's root, units.rs `unit_record`.)
+ pub fn gpu(&self, first: u32) -> GpuInstance {
let w = self.world;
let nm = glam::Mat3::from_mat4(w).inverse().transpose();
let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];
let nrow = |r: usize, w: f32| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], w];
- let mirrored = f32::from_bits(self.bits | if mirrors(w) { INST_MIRRORED } else { 0 });
- GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, f32::from_bits(parts[1])), nrow(1, mirrored), nrow(2, f32::from_bits(self.first_emitter))], info: [first, self.object, lod_offset(w).to_bits(), parts[0]], p: [row(0), row(1), row(2)] }
+ let bits = f32::from_bits(self.bits | if mirrors(w) { INST_MIRRORED } else { 0 });
+ GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, bits), nrow(2, 0.0)], info: [first, self.object, lod_offset(w).to_bits(), self.rows], p: [row(0), row(1), row(2)] }
}
- /// What `gpu` takes as `parts` for an instance of `m`: its rows' first with sections, else the mesh's part
- /// offsets.
- pub fn parts(&self, m: &InstMesh) -> [u32; 2] {
- if m.sect_count > 0 { [self.rows, 0] } else { m.part_offsets() }
- }
- /// A triangle's attributes as a flattened triangle has them: with sections, the material its row names in place
- /// of the section, and no index in it (`rows`: the instance's).
+ /// 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 {
- if self.bits & INST_ROWS == 0 {
- return *a;
- }
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 }
}
@@ -307,13 +266,12 @@ pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent
/// 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;
-/// More bits there: the instance has rows (its record's info.w is their first; `Instance::rows`), and a row of it is
-/// a cutout's, a glass's (what a walk of a unit asks before it reads a triangle's row).
-pub const INST_ROWS: u32 = 8;
+/// More bits there: a row of the instance is a cutout's, a glass's (what a walk of a unit asks before it reads a
+/// triangle's row).
pub const INST_CUTOUT: u32 = 16;
pub const INST_GLASS: u32 = 32;
/// Every bit of n1.w that is the instance's own, not a unit's.
-pub const INST_BITS: u32 = INST_MIRRORED | INST_ROWS | INST_CUTOUT | INST_GLASS;
+pub const INST_BITS: u32 = INST_MIRRORED | INST_CUTOUT | INST_GLASS;
/// Whether a placement mirrors what it places (a negative determinant).
pub fn mirrors(w: Mat4) -> bool {
@@ -795,6 +753,9 @@ pub struct Retained {
/// Static models' instanced meshes by (uri, nodes), those with nothing flattened per placement: a model added in
/// place is another instance of one (live/edits.rs `edit_geometry`).
pub model_mesh: HashMap<(String, Option<Vec<String>>), u32>,
+ /// A model's mesh's rows as every instance of it has them (the file's materials, `model_sections`; where a
+ /// section's triangles and emitters are is each instance's to fill).
+ pub mesh_rows: HashMap<u32, Vec<Row>>,
}
/// Where what one object of the world draws landed in the GPU's tables: its entry in the objects table and how its
@@ -959,8 +920,8 @@ pub struct PoseGroup {
pub nodes: Option<Vec<String>>,
/// The pose the mesh holds.
pub animation: desc::Animation,
- /// Per pool triangle of the mesh, in order: its index in the model's triangles and its material.
- pub order: Vec<(u32, u32)>,
+ /// Per pool triangle of the mesh, in order: its index in the model's triangles, its section and its index in it.
+ pub order: Vec<(u32, u32, u32)>,
/// (object, instance) of each member.
pub members: Vec<(u32, u32)>,
}
@@ -1778,20 +1739,18 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
}
flatten_coincident(&mut classed, &emitting, &|k| local[k].1.p);
- let emitters = pool_emitters(&classed, &emitting);
if classed[..FLAT].iter().any(|l| !l.is_empty()) {
let first_pool = pool_tris.len() as u32;
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
- for list in &classed[..FLAT] {
- for &(k, mat) in list {
- let t = &local[k].1;
- for v in t.p {
- lo = lo.min(v.into());
- hi = hi.max(v.into());
- }
- pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(tri_attr(t.p, t.n, t.uv, t.tangent, mat));
+ let (order, sects, mine) = model_sections(&kept(&classed));
+ for &(k, section, rank) in &order {
+ let t = &local[k].1;
+ for v in t.p {
+ lo = lo.min(v.into());
+ hi = hi.max(v.into());
}
+ pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
+ pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
}
for c in 0..8 {
let p = Vec3A::new(if c & 1 == 0 { lo.x } else { hi.x }, if c & 2 == 0 { lo.y } else { hi.y }, if c & 4 == 0 { lo.z } else { hi.z });
@@ -1799,10 +1758,11 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
olo = olo.min(q);
ohi = ohi.max(q);
}
- let count = classed[..FLAT].iter().map(Vec::len).sum::<usize>() as u32;
- meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters, sect_first: 0, sect_count: 0, colored: false });
+ meshes.push(InstMesh { sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first_pool as usize..], first_pool) });
+ sections.extend(sects);
rigid.instances.push((*ni, instances.len() as u32));
- instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: meshes[meshes.len() - 1].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 });
+ instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ rows.extend(mine);
}
for &(k, mat) in &classed[FLAT] {
let t = &local[k].1;
@@ -1853,22 +1813,22 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let g = (classed[FLAT].is_empty() && !local.is_empty()).then(|| {
let first = pool_tris.len() as u32;
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
- let mut tri_order = Vec::with_capacity(local.len());
- for list in &classed[..FLAT] {
- for &(k, mat) in list {
- let t = &local[k];
- for v in t.p {
- lo = lo.min(v.into());
- hi = hi.max(v.into());
- }
- pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(tri_attr(t.p, t.n, t.uv, t.tangent, mat));
- tri_order.push((k as u32, mat));
+ let (order, sects, mine) = model_sections(&kept(&classed));
+ for &(k, section, rank) in &order {
+ let t = &local[k];
+ for v in t.p {
+ lo = lo.min(v.into());
+ hi = hi.max(v.into());
}
+ pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
+ pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
}
+ let tri_order: Vec<(u32, u32, u32)> = order.iter().map(|&(k, section, rank)| (k as u32, section, rank)).collect();
// Other poses reach further (a stride, a swing): object bounds a quarter wider each way.
let pad = (hi - lo) * 0.25;
- meshes.push(InstMesh { first, count: tri_order.len() as u32, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emitters: 0, sect_first: 0, sect_count: 0, colored: false });
+ meshes.push(InstMesh { lo: lo - pad, hi: hi + pad, deforms: true, sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first as usize..], first) });
+ sections.extend(sects);
+ retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);
retained.pose_groups.push(PoseGroup { mesh: meshes.len() as u32 - 1, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order: tri_order, members: vec![] });
retained.pose_groups.len() as u32 - 1
});
@@ -1884,7 +1844,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
let i = instances.len() as u32;
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 });
+ let mine = retained.mesh_rows[&mesh].clone();
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ rows.extend(mine);
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Pose(g), moves: true }) };
retained.pose_groups[g as usize].members.push((*id, i));
continue;
@@ -1895,9 +1857,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mesh = match mesh_of.get(&key) {
Some(k) => *k,
None => {
- // Model-space triangles by class: opaque and cutout ones go to the pool (one BLAS, opaque
- // geometry then cutout geometry), those that only emit among them (each instance has its
- // emitters in the light list: `InstMesh::emitters`), its glass the mesh's glass part.
+ // Model-space triangles go to the pool by section, a material of the file (one BLAS),
+ // those that only emit among them (each instance has its emitters in the light list).
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), None)?;
let mut classed: [Vec<(usize, u32)>; 4] = Default::default();
let mut emitting: std::collections::HashSet<u32> = Default::default();
@@ -1918,17 +1879,21 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
hi = hi.max(v.into());
}
}
- for (class, list) in classed.iter().enumerate() {
- let (pt, pa) = if class < FLAT { (&mut pool_tris, &mut pool_attrs) } else { (&mut rest_tris, &mut rest_attrs) };
- for &(k, mat) in list {
- let t = &local[k];
- pt.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pa.push(tri_attr(t.p, t.n, t.uv, t.tangent, mat));
- }
+ let (order, sects, mine) = model_sections(&kept(&classed));
+ for &(k, section, rank) in &order {
+ let t = &local[k];
+ pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
+ pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
+ }
+ // (What leaves the mesh keeps its material on the triangle: each placement flattens it.)
+ for &(k, mat) in &classed[FLAT] {
+ let t = &local[k];
+ rest_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
+ rest_attrs.push(tri_attr(t.p, t.n, t.uv, t.tangent, mat));
}
- let count = classed[..FLAT].iter().map(Vec::len).sum::<usize>() as u32;
- let emitters = pool_emitters(&classed, &emitting);
- meshes.push(InstMesh { first, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, deforms: false, emitters, sect_first: 0, sect_count: 0, colored: false });
+ meshes.push(InstMesh { rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first as usize..], first) });
+ sections.extend(sects);
+ retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);
meshes.len() as u32 - 1
});
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
@@ -1936,7 +1901,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
// (What an edit can place another instance of: a mesh whole in the pool. One with emitters is
// not: an edit does not make a model's instance its emitters yet.)
- if let Some(k) = k.filter(|&k| meshes[k as usize].rest_count == 0 && meshes[k as usize].emitters == 0) {
+ if let Some(k) = k.filter(|&k| meshes[k as usize].rest_count == 0 && pool_emitters(&classed, &emitting) == 0) {
retained.model_mesh.insert(key.clone(), k);
}
mesh_of.insert(key, k);
@@ -1952,7 +1917,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
retained.proxy(*id).object = Some(oi);
- let inst = Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
+ let mine = retained.mesh_rows[&mesh].clone();
+ let inst = Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) };
+ rows.extend(mine);
// Its glass / function triangles as ordinary world-space ones (same object).
for k in im.rest_first..im.rest_first + im.rest_count {
let (t, a, _) = inst.flat(&rest_tris[k as usize], &rest_attrs[k as usize], None);
@@ -2509,7 +2476,7 @@ pub fn section_mesh(g: &world::Geometry, grouped: bool, first: u32, sect_first:
let c = tri_colors(g, false, Some(&group.iter().map(|x| x.map(|_| 1)).collect::<Vec<_>>()));
order.iter().map(|&k| c[k]).collect()
});
- let mesh = InstMesh { sect_first, sect_count: sections.len() as u32, colored, ..own_inst_mesh(&tris, first, 0) };
+ let mesh = InstMesh { sect_first, sect_count: sections.len() as u32, colored, ..own_inst_mesh(&tris, first) };
MeshData { tris, attrs, colors, mesh, sections }
}
@@ -2528,6 +2495,45 @@ pub fn rank_in_sections(attrs: &mut [GpuTriAttr]) {
}
}
+/// A model's mesh laid out by section, a section a material in the order the materials first appear among the
+/// triangles that stay in the mesh (`kept`: each one's index in the model's list, its GPU material and that
+/// material's class, `mesh_class`), a section's triangles in the list's order. Returns the pool's order (the index
+/// in the model's list, the triangle's section and its index in it), the sections, and an instance's rows for them
+/// (`Retained::mesh_rows`: every instance of the mesh has the file's materials).
+#[allow(clippy::type_complexity)]
+pub fn model_sections(kept: &[(usize, u32, u32)]) -> (Vec<(usize, u32, u32)>, Vec<Section>, Vec<Row>) {
+ let mut sorted = kept.to_vec();
+ sorted.sort_unstable_by_key(|k| k.0);
+ let mut section_of: HashMap<u32, u32> = HashMap::new();
+ let (mut lists, mut rows): (Vec<Vec<usize>>, Vec<Row>) = (vec![], vec![]);
+ for &(k, mat, class) in &sorted {
+ let at = *section_of.entry(mat).or_insert_with(|| {
+ lists.push(vec![]);
+ rows.push([mat | [0, ROW_CUTOUT, ROW_GLASS][class as usize], 0, NO_EMITTER, 0]);
+ lists.len() as u32 - 1
+ });
+ lists[at as usize].push(k);
+ }
+ let (mut order, mut sections) = (Vec::with_capacity(sorted.len()), Vec::with_capacity(lists.len()));
+ for (at, list) in lists.iter().enumerate() {
+ sections.push(Section { first: order.len() as u32, count: list.len() as u32, slot: at as u32 });
+ order.extend(list.iter().enumerate().map(|(rank, &k)| (k, at as u32, rank as u32)));
+ }
+ (order, sections, rows)
+}
+
+/// A model's triangle as its mesh holds it: its attributes with its section and its index in it.
+pub fn section_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3, f32)>, section: u32, rank: u32) -> GpuTriAttr {
+ let mut a = tri_attr(p, n, uv, tangent, section);
+ a.x[3] = f32::from_bits(rank);
+ a
+}
+
+/// The triangles of `classed` that stay in a mesh (`FLAT`'s leave it), for `model_sections`.
+fn kept(classed: &[Vec<(usize, u32)>; 4]) -> Vec<(usize, u32, u32)> {
+ classed[..FLAT].iter().enumerate().flat_map(|(class, list)| list.iter().map(move |&(k, mat)| (k, mat, class as u32))).collect()
+}
+
/// An instance's rows for `sections`, drawn with the object's materials `mats` (GPU indices; a slot past the last is
/// the last, as three.js clamps).
pub fn section_rows(sections: &[Section], mats: &[u32], materials: &[GpuMaterial]) -> Vec<Row> {
@@ -2540,8 +2546,8 @@ pub fn emissive(g: &GpuMaterial) -> bool {
g.emissive[..3].iter().any(|e| *e > 0.0)
}
-/// The class of a material's triangles in a mesh, a BLAS geometry each (`InstMesh::parts`): 0 opaque, 1 cutout
-/// (alpha-tested), 2 glass (shadow rays pass). A material function or emission is no class: the kernel places a
+/// The class of a material, which an instance's row of it says (`row_of`): 0 opaque, 1 cutout (alpha-tested),
+/// 2 glass (shadow rays pass). A material function or emission is no class: the kernel places a
/// function's inputs by the instance (`mat_in_at`), and the light list has an instance's emitters.
pub fn mesh_class(g: &GpuMaterial) -> u32 {
if g.layer[0] > 0.0 {
@@ -2555,20 +2561,8 @@ pub fn mesh_class(g: &GpuMaterial) -> u32 {
/// emitters of a mesh that deforms).
pub const FLAT: usize = 3;
-/// Numbers a mesh's triangles that emit (those of a material that only emits; their attributes' x.w = the number +
-/// 1, the others' 0): an instance's emitter of a triangle is its first plus the number. Returns how many.
-pub fn number_emitters(attrs: &mut [GpuTriAttr], materials: &[GpuMaterial]) -> u32 {
- let mut n = 0;
- for a in attrs.iter_mut() {
- let emits = materials.get(a.uv[3].to_bits() as usize).is_some_and(emissive);
- n += u32::from(emits);
- a.x[3] = f32::from_bits(if emits { n } else { 0 });
- }
- n
-}
-
-/// The `InstMesh` of triangles at pool index `first`, all of one class (`mesh_class`), without sections.
-pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
+/// The `InstMesh` of triangles at pool index `first`, with their bounds; its sections are the caller's to set.
+pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32) -> InstMesh {
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
for t in tris {
for v in t {
@@ -2577,7 +2571,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
}
}
let count = tris.len() as u32;
- InstMesh { first, count, opaque: if class == 0 { count } else { 0 }, glass: if class == 2 { count } else { 0 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0, sect_first: 0, sect_count: 0, colored: false }
+ InstMesh { first, count, rest_first: 0, rest_count: 0, lo, hi, deforms: false, sect_first: 0, sect_count: 0, colored: false }
}
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
@@ -2765,7 +2759,7 @@ mod instance_tests {
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 };
- assert_eq!(inst.gpu(0, [0, 0]).n[1][3].to_bits(), if mirrored { INST_MIRRORED } else { 0 }, "the record says whether it mirrors");
+ 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] };
@@ -2831,7 +2825,7 @@ mod instance_tests {
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.iter().map(|i| i.gpu(0, [0, 0]).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED | INST_ROWS, INST_ROWS, INST_ROWS, INST_ROWS], "and its record says so, beside that it has rows");
+ 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");
}
/// An instanced object whose material only emits is placed as any other: one shared mesh, which has the emitters,
@@ -2852,7 +2846,7 @@ mod instance_tests {
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.instances.iter().map(|i| (i.rows, i.bits)).collect::<Vec<_>>(), [(0, INST_ROWS), (1, INST_ROWS), (2, INST_ROWS), (3, INST_ROWS)], "a row a copy");
+ 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");
let prep = crate::prepare_as(true, false, &mut sc, &mut vec![]);
@@ -2884,12 +2878,13 @@ mod instance_tests {
build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap()
};
let (straight, mirrored) = (scene(1.0), scene(-1.0));
- let meshes = |sc: &Scene| sc.meshes.iter().map(|m| (m.first, m.count, m.opaque, m.rest_count, m.emitters)).collect::<Vec<_>>();
+ let meshes = |sc: &Scene| sc.meshes.iter().map(|m| (m.first, m.count, m.sect_count, m.rest_count)).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!(straight.instances.len() >= 2 && straight.instances.iter().all(|i| i.gpu(0, [0, 0]).n[1][3].to_bits() == 0));
- assert!(mirrored.instances.iter().all(|i| i.gpu(0, [0, 0]).n[1][3].to_bits() == INST_MIRRORED), "every instance of a mirrored model mirrors");
+ 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");
// What is flattened of them (the cutout on an emitter with its emitter: a still model's, a moving node's) faces
// as its normals do, mirrored too.
for (sc, what) in [(&straight, "straight"), (&mirrored, "mirrored")] {
@@ -2924,11 +2919,11 @@ mod instance_tests {
assert_eq!(d.tris.iter().map(|t| t[0].x.min(t[1].x).min(t[2].x)).collect::<Vec<_>>(), [0.0, 1.0, 1.0, 3.0, 3.0, 4.0, 4.0, 0.0], "each triangle in its last group's section");
assert_eq!(d.attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0)]);
let im = d.mesh;
- assert_eq!((im.first, im.count, im.opaque, im.glass, im.emitters, im.sect_first, im.sect_count, im.colored), (10, 8, 8, 0, 0, 7, 5, false), "no colours: the geometry has none");
+ assert_eq!((im.first, im.count, im.sect_first, im.sect_count, im.colored), (10, 8, 7, 5, false), "no colours: the geometry has none");
assert_eq!((im.lo, im.hi), (Vec3A::new(0.0, 0.0, 0.0), Vec3A::new(5.0, 1.0, 0.0)), "bounds of what is drawn");
let mut all = vec![sect(9, 9, 9); 7];
all.extend(&d.sections);
- assert_eq!(im.parts(&all), [(0, 1, true), (1, 2, true), (3, 2, true), (5, 2, true), (7, 1, true)], "a geometry a section, all flagged opaque");
+ assert_eq!(im.parts(&all), [(0, 1), (1, 2), (3, 2), (5, 2), (7, 1)], "a geometry a section");
assert!(d.colors.is_none());
// Its geometry's colours, where it has them and they are asked for: the drawn triangles', as they lie.
let tinted = section_mesh(&world::Geometry { colors, ..g.clone() }, true, 0, 0, true);
@@ -2940,19 +2935,19 @@ mod instance_tests {
let rows = section_rows(&d.sections, &[0, 1, 2, 3], &materials);
assert_eq!(rows, [[ROW_GLASS, 0, NO_EMITTER, 0], [1 | ROW_CUTOUT, 0, NO_EMITTER, 0], [2, 0, NO_EMITTER, 0], [3, 0, NO_EMITTER, 0], [1 | ROW_CUTOUT, 0, NO_EMITTER, 0]]);
assert_eq!(rows.iter().map(row_material).collect::<Vec<_>>(), [0, 1, 2, 3, 1]);
- assert_eq!((rows_cast(&rows, true), rows_cast(&rows, false), rows_bits(&rows)), (true, false, INST_ROWS | INST_CUTOUT | INST_GLASS));
+ assert_eq!((rows_cast(&rows, true), rows_cast(&rows, false), rows_bits(&rows)), (true, false, INST_CUTOUT | INST_GLASS));
let starts = section_emitters(&d.sections, &rows, &materials);
assert_eq!((rows_emitters(&d.sections, &rows, &materials), &starts[..]), (2, &[None, None, Some(0), None, None][..]));
assert_eq!((section_slot(&d.attrs[4], &rows, &starts), section_slot(&d.attrs[5], &rows, &starts)), (Some((1, 2)), None), "an emitter's place: its section's start and its index");
// Two materials for four slots: a slot past the last is the last. Emitters in two sections, one after another.
let two = section_rows(&d.sections, &[2, 0], &materials);
assert_eq!(two.iter().map(row_material).collect::<Vec<_>>(), [2, 0, 0, 0, 0]);
- assert_eq!((rows_emitters(&d.sections, &two, &materials), rows_bits(&two), rows_cast(&two, true)), (1, INST_ROWS | INST_GLASS, true));
+ assert_eq!((rows_emitters(&d.sections, &two, &materials), rows_bits(&two), rows_cast(&two, true)), (1, INST_GLASS, true));
let lit = section_rows(&d.sections, &[2, 3, 3, 2], &materials);
assert_eq!((rows_emitters(&d.sections, &lit, &materials), section_emitters(&d.sections, &lit, &materials)), (3, vec![Some(0), None, None, Some(1), None]));
// All glass: it casts no shadow, whatever its object says.
let glass = section_rows(&d.sections, &[0, 0], &materials);
- assert_eq!((rows_cast(&glass, true), rows_bits(&glass)), (false, INST_ROWS | INST_GLASS));
+ assert_eq!((rows_cast(&glass, true), rows_bits(&glass)), (false, INST_GLASS));
// Put in another order (a unit's tree's), the triangles are numbered again in their sections.
let mut back: Vec<GpuTriAttr> = d.attrs.iter().rev().copied().collect();
rank_in_sections(&mut back);
@@ -2964,11 +2959,12 @@ mod instance_tests {
assert_eq!(section_rows(&one.sections, &[1], &materials), [[1 | ROW_CUTOUT, 0, NO_EMITTER, 0]]);
}
- /// A model's glass is a part of its mesh (tests/render/data/frame-pane.glb: an opaque, a cutout and a glass quad;
- /// placed twice): one mesh of three geometries, the glass the one not flagged opaque, nothing flattened; the
- /// instances' records say where the second and the third start, and the kernel's feature for it is set.
+ /// 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
+ /// 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]
- fn a_models_glass_is_a_part_of_its_mesh() {
+ fn a_models_mesh_lies_by_section_a_material_of_the_file() {
let mut w = World::default();
let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
@@ -2978,19 +2974,30 @@ mod instance_tests {
w.set_transform(id, Vec3::new(id as f32 * 5.0, 0.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
}
let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
- assert_eq!(sc.meshes.iter().map(|m| (m.count, m.opaque, m.glass, m.rest_count)).collect::<Vec<_>>(), [(6, 2, 2, 0)]);
+ assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.rest_count)).collect::<Vec<_>>(), [(6, 3, 0)]);
assert_eq!((sc.instances.len(), sc.tris.len()), (2, 0));
- assert_eq!((sc.meshes[0].parts(&sc.sections), sc.meshes[0].part_offsets()), (vec![(0, 2, true), (2, 2, true), (4, 2, false)], [2, 4]));
- assert!(sc.rows.is_empty() && sc.instances.iter().all(|i| i.bits == 0), "a model's instance has no rows");
+ 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");
+ for i in &sc.instances {
+ let mine = &sc.rows[i.rows as usize..][..3];
+ let mut classes: Vec<u32> = mine.iter().map(|r| r[0] & (ROW_CUTOUT | ROW_GLASS)).collect();
+ classes.sort_unstable();
+ assert_eq!(classes, [0, ROW_CUTOUT, ROW_GLASS], "an opaque, a cutout and a glass section");
+ assert_eq!(mine, &sc.retained.mesh_rows[&i.mesh][..], "the mesh's rows, the file's materials");
+ }
crate::prepare_as(true, false, &mut sc, &mut vec![]);
- assert!(sc.gpu_instances.iter().all(|r| (r.info[3], r.n[0][3].to_bits()) == (2, 4)), "the records have the two starts");
+ for (r, i) in sc.gpu_instances.iter().zip(&sc.instances) {
+ assert_eq!(r.info[3], i.rows, "the record has its rows' first");
+ assert_eq!(sc.rows[i.rows as usize..][..3].iter().map(|row| row[1] - r.info[0]).collect::<Vec<_>>(), [0, 2, 4], "a row has where its section starts");
+ }
let f = crate::gpu::instance_features(&sc);
assert_eq!(f & (crate::gpu::F_IGLASS | crate::gpu::F_MASKED), crate::gpu::F_IGLASS | crate::gpu::F_MASKED);
- // A mesh of one kind, or of two: the geometries it has, in the same order.
- let t = [[Vec3A::ZERO, Vec3A::X, Vec3A::Y]; 3];
- assert_eq!((own_inst_mesh(&t, 0, 2).parts(&[]), own_inst_mesh(&t, 0, 2).part_offsets()), (vec![(0, 3, false)], [0, 0]));
- let two = InstMesh { opaque: 0, glass: 1, ..own_inst_mesh(&t, 0, 1) };
- assert_eq!((two.parts(&[]), two.part_offsets()), (vec![(0, 2, true), (2, 1, false)], [2, 0]));
+ // The sections of a list of triangles: a material after another as they first appear, the list's order in each.
+ let (order, sections, rows) = model_sections(&[(5, 9, 2), (0, 7, 0), (3, 9, 2), (1, 8, 1), (4, 7, 0)]);
+ assert_eq!(order, [(0, 0, 0), (4, 0, 1), (1, 1, 0), (3, 2, 0), (5, 2, 1)]);
+ assert_eq!(sections, [Section { first: 0, count: 2, slot: 0 }, Section { first: 2, count: 1, slot: 1 }, Section { first: 3, count: 2, slot: 2 }]);
+ assert_eq!(rows, [[7, 0, NO_EMITTER, 0], [8 | ROW_CUTOUT, 0, NO_EMITTER, 0], [9 | ROW_GLASS, 0, NO_EMITTER, 0]]);
}
/// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_coincident`), in a model that stays
@@ -3007,10 +3014,11 @@ mod instance_tests {
w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true })), true, false).unwrap();
let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
let mesh = |name: &str| {
- let m = &sc.meshes[sc.instances.iter().find(|i| i.name == name).unwrap().mesh as usize];
- (m.count, m.rest_count, m.emitters)
+ let i = sc.instances.iter().find(|i| i.name == name).unwrap();
+ let m = &sc.meshes[i.mesh as usize];
+ (m.count, m.rest_count, rows_emitters(m.sections(&sc.sections), &sc.rows[i.rows as usize..][..m.sect_count as usize], &sc.materials))
};
- assert_eq!((mesh("still"), mesh("posed")), ((2, 4, 0), (2, 0, 0)), "(triangles in the mesh, flattened a placement, emitters in the mesh)");
+ assert_eq!((mesh("still"), mesh("posed")), ((2, 4, 0), (2, 0, 0)), "(triangles in the mesh, flattened a placement, emitters of the instance)");
let count = |f: &dyn Fn(usize) -> bool| (0..sc.tris.len()).filter(|&k| f(k)).count();
let emits = |k: usize| sc.materials[sc.attrs[k].uv[3].to_bits() as usize].emissive[..3].iter().any(|e| *e > 0.0);
let flattened = (sc.tris.len(), count(&emits), count(&|k| sc.tri_flags[k] & TRI_MASKED != 0), count(&|k| sc.tri_flags[k] & TRI_DYNAMIC != 0));
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index b889e46..a9237e5 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -1356,7 +1356,7 @@ mod tests {
fn record(&self, mesh: usize, world: Mat4, cast: bool) -> GpuInstance {
let (first, _, root, ..) = self.meshes[mesh].unwrap();
let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
- unit_record(inst.gpu(first, [0, 0]), root, cast)
+ unit_record(inst.gpu(first), root, cast)
}
fn add_unit(&mut self, mesh: usize, world: Mat4, cast: bool) -> usize {
@@ -1969,7 +1969,7 @@ mod tests {
// A built tree is a level short of the bound: two of them joined are at it.
assert!(check_tree(&build_sah(&(0..1 << 12).map(|k| (Vec3A::splat(k as f32), Vec3A::splat(k as f32 + 1.0))).collect::<Vec<_>>(), 12).0, 64, |_, _| Ok(())).unwrap() <= 12);
// The record's word for a placement by a translation alone.
- let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 }.gpu(0, [0, 0]), 9, true);
+ let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 }.gpu(0), 9, true);
let shifted = |m: Mat4| rec(m).n[1][3].to_bits() & UNIT_SHIFTED != 0;
assert!(shifted(Mat4::IDENTITY));
assert!(shifted(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))));
diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rs
index 1d274a4..fc2fc43 100644
--- a/renderer/src/units_cost.rs
+++ b/renderer/src/units_cost.rs
@@ -410,7 +410,7 @@ fn units_pile() {
// At rest: the kernel's buffers as a session would have written them.
for (j, p) in pieces.iter().enumerate() {
let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
- l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, [tris.len() as u32, 0]), root as u32, true);
+ l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri), root as u32, true);
}
let at = u.layout.top_first as usize;
l.nodes[at..at + top.len()].copy_from_slice(&top);
diff --git a/tests/render/data/arm.glb b/tests/render/data/arm.glb
new file mode 100644
index 0000000..6570b0f
Binary files /dev/null and b/tests/render/data/arm.glb differ
diff --git a/tests/render/geometry-emitter-model-live.ts b/tests/render/geometry-emitter-model-live.ts
new file mode 100644
index 0000000..ddd14ad
--- /dev/null
+++ b/tests/render/geometry-emitter-model-live.ts
@@ -0,0 +1,8 @@
+// geometry/emitter-model in the real-time renderer: the emitters of a model's section that is not its mesh's first,
+// found through its instance's rows (under software traversal the model is a unit).
+import def, { test as base } from "./geometry-emitter-model.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "geometry/emitter-model-live", temporal: true, live: 240 };
+
+export default def;