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.

Glass is a part of its mesh (#161)

Yujia17c8e10f2cf3
diff --git a/docs/PARITY.md b/docs/PARITY.md
index 863b5fb..0b4e30d 100644
--- a/docs/PARITY.md
+++ b/docs/PARITY.md
@@ -37,9 +37,9 @@ Engine (renderer + DSL; at the time also the scene IR and its UE adapter, both s
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.
Static glTF models are instanced (hardware RT; `scene::Instance`): each unique mesh's triangles once in model
- space with one BLAS (opaque geometry + cutout geometry), one TLAS instance per placement (transform, shadow mask,
- custom data = instance record), shading transforms the hit triangle; glass triangles are flattened per
- placement (shadow rays), skinned models entirely. A mirrored placement is an instance whose record says so. A model's
+ 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
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 6ed978a..b850900 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2730,6 +2730,23 @@ geometric normal through a function on a mirrored mesh, vertex colours on one (e
traversal); the flattening of an instance against the build's flattening, mirrored too; a mirrored model's build; a
copy mirrored in place; an emitting instanced object added, changed and removed in place against a build.
+**Glass is a part of its mesh (2026-11-18).** The last reason to flatten a material's triangles at every placement
+goes. A mesh's glass is a geometry of its BLAS beside the opaque and the cutout one, the only one not flagged opaque
+(`InstMesh::parts`; a hit's triangle from its geometry and primitive by two starts in the instance's record). A shadow
+ray passed glass by the still scene's masks, and passes an instance of a mesh that is all glass the same way
+(`InstMesh::casts`). Where a mesh mixes glass with other triangles it culls the geometry that is not opaque (kernel
+feature `F_IGLASS`; software traversal: a flag a triangle). `glass_tr` weighs what the glass lets through as before.
+Measured first on Metal with every geometry flagged opaque: the same pictures, at most 0.5 % of a frame's GPU time;
+the cull flag's old cost (Bistro +1.7 ms) was its use for cutouts. With the cull in every pane's own BLAS a scene of
+400 panes traced about 15 % slower under the loop guard; by the mask it does not. Which side of a surface a ray meets
+goes by the instance's sign (a mirrored glass instance). What still leaves a mesh: triangles on exactly the same
+vertices (`flatten_coincident`: a cutout on an emitter, glass on whatever lies under it), and the emitters of a mesh
+that deforms. A mesh that is all glass is added in place, the mask needing no kernel feature; a material of instances'
+triangles that turns glass, or stops being glass, rebuilds.
+Tests: a shadow through an instance's glass (a mesh of its own, offline and live; an instanced copy; a model whose
+one mesh has an opaque, a cutout and a glass part, with the other two parts' shadows, offline and live), a mirrored
+glass instance, the model's build, a glass mesh added in place.
+
**An emitter's probability is what the picker used (2026-11-18).** An emitter that changed size in place (a movable
model or mesh scaled, a skinned one) kept the weight it was loaded with, while the kernel took its probability from
formulas that assumed the weight was the triangle's: scaled three times larger as a scene's main light it read 3 to
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index d7ab77e..16ff5bd 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -90,6 +90,7 @@ const F_BACKGROUND: u32 = 2097152u; // scene.background (`sky_mis`)
const F_VCOLOR: u32 = 4194304u; // vertex colours (`vcolor`)
const F_GRID: u32 = 33554432u; // density grids (`vgrid`)
const F_IFUNC: u32 = 268435456u; // a material function on an instanced mesh: `mat_in_at` places the triangle by its instance
+const F_IGLASS: u32 = 536870912u; // glass among other triangles in an instanced mesh: shadow rays cull its geometry (trace_hw.wgsl), a unit's glass triangles by their flag
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; }
@@ -868,14 +869,16 @@ fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {
var a = attrs[h.tri];
var e1 = tri_verts[h.tri * 3u + 1u].xyz;
var e2 = tri_verts[h.tri * 3u + 2u].xyz;
+ var side = 1.0;
if (has(F_INST) && h.inst != NO_INST) {
let r = instance_at(h.inst);
e1 = inst_vec(r, e1);
e2 = inst_vec(r, e2);
a = inst_attr(r, a);
+ side = inst_sign(r);
}
let m = material_at(bitcast<u32>(a.uv.w));
- var g = GlassAt(normalize(cross(e1, e2)), 0.0, false, vec3<f32>(1.0));
+ var g = GlassAt(normalize(cross(e1, e2)) * side, 0.0, false, vec3<f32>(1.0));
var tr = clamp(m.layer.x, 0.0, 1.0) * (1.0 - clamp(m.params.x, 0.0, 1.0));
if (tr <= 0.0) { return g; }
g.tint = m.base_color.rgb;
diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgsl
index 98a90d7..cd70e69 100644
--- a/renderer/shaders/trace_hw.wgsl
+++ b/renderer/shaders/trace_hw.wgsl
@@ -1,5 +1,6 @@
// Hardware ray tracing (wgpu ray query). Up to four instances (see Prepared::groups): shadow casters mask 1, the rest
-// mask 2; opaque groups never report candidates, alpha-cutout groups are confirmed by `alpha_pass`.
+// mask 2 (glass among them; an instanced mesh's glass is a geometry of its BLAS that a shadow ray culls); opaque groups
+// never report candidates, alpha-cutout groups are 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;
@@ -22,7 +23,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) is slow on Metal (Bistro's trace +1.7 ms).
+ // 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`).
//
// 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
@@ -55,7 +57,12 @@
@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool) -> Hit {
@if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }
var rq: ray_query;
- let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_FORCE_OPAQUE | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);
+ // A shadow ray (mask 1) where an instanced 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. (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);
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;
@@ -108,8 +115,12 @@
// traversal group's.
@if(hwrt) fn hit_tri(custom: u32, geometry: u32, prim: u32) -> u32 {
if (has(F_INST) && (custom & INSTANCE_BIT) != 0u) {
- let r = instance_at(custom & (INSTANCE_BIT - 1u)).info;
- return r.x + select(0u, r.w, geometry == 1u) + prim;
+ // (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));
+ 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;
}
return group_tri(custom, prim);
}
diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgsl
index 6ad5396..ca52b5a 100644
--- a/renderer/shaders/trace_units.wgsl
+++ b/renderer/shaders/trace_units.wgsl
@@ -100,6 +100,7 @@ const UNIT_SHIFTED: u32 = 2u;
let x = intersect_tri(ro, rd, ti, hit.t);
if (x.x < hit.t) {
let flags = bitcast<u32>(tri_verts[ti * 3u].w);
+ if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }
if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, x.y, x.z, x.x)) { shadow_hole = true; continue; }
hit = Hit(x.x, ti, x.y, x.z, rec);
if (mode != TRACE_CLOSEST) { return hit; }
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 111adce..3dd4edb 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1677,6 +1677,11 @@ 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 other triangles in an instanced mesh: its BLAS geometry is not flagged opaque, and a shadow ray culls
+/// such geometry instead of forcing opacity (trace_hw.wgsl; software traversal skips a unit's glass triangles by
+/// their flag). Compiled out where no instanced mesh mixes the two: an instance of a mesh that is all glass is out of
+/// a shadow ray's way by its mask (`scene::InstMesh::casts`).
+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):
/// there the lights are resampled as in a scene of fewer, unguided (docs/RUNTIME.md "Android").
@@ -1741,7 +1746,7 @@ pub fn environment_features(fog: Option<&crate::desc::Fog>, background: bool, ae
/// Kernel features of the scene's structure, which parameter edits do not change: F_INST and F_MASKED for the
/// instanced meshes (cutout triangles among them), F_MEDIA for participating media (F_HMEDIA for homogeneous ones),
/// F_PEMIT for opaque particles, F_PROC for procedural geometry, F_TINT for instance colours, F_IFUNC for a material
-/// function on an instanced mesh.
+/// function on an instanced mesh, F_IGLASS for glass on one.
pub fn instance_features(scene: &Scene) -> u32 {
// (F_GRID also for a volume function that calls `vgrid` on a node without a grid: it reads zeros.)
let grid = !scene.grids.is_empty() || (!scene.media.is_empty() && scene.volume_fns.iter().any(|(_, code, helpers)| code.contains("vgrid(") || helpers.contains("vgrid(")));
@@ -1752,7 +1757,8 @@ pub fn instance_features(scene: &Scene) -> u32 {
}
let function = |a: &crate::scene::GpuTriAttr| scene.materials.get(a.uv[3].to_bits() as usize).is_some_and(|m| m.tex1[3] != 0);
let ifunc = if scene.pool_attrs.iter().any(function) { F_IFUNC } else { 0 };
- media | particles | ifunc | F_INST | if scene.meshes.iter().any(|m| m.opaque < m.count) { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
+ let iglass = if scene.meshes.iter().any(|m| m.glass > 0 && m.glass < m.count) { F_IGLASS } else { 0 };
+ media | particles | ifunc | iglass | F_INST | if scene.meshes.iter().any(|m| m.opaque + m.glass < m.count) { 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
@@ -2359,11 +2365,11 @@ impl Gpu {
let vbuf = buf_room("blas_verts", bytemuck::cast_slice(&verts), room.tris * 36, wgpu::BufferUsages::BLAS_INPUT | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::STORAGE);
let huge_scene = huge(groups, !scene.gpu_instances.is_empty());
let mut first = 0usize;
- let groups: Vec<(usize, usize, u8, bool)> = groups
+ let groups: Vec<(usize, usize, u8)> = groups
.iter()
.enumerate()
.map(|(g, &count)| {
- let r = (first, count, if g % 4 < 2 { 1u8 } else { 2u8 }, g % 2 == 0);
+ let r = (first, count, if g % 4 < 2 { 1u8 } else { 2u8 });
first += count;
r
})
@@ -2372,16 +2378,19 @@ impl Gpu {
let mut t = d.create_tlas(&wgpu::CreateTlasDescriptor { label: None, max_instances: (GROUPS + scene.instances.len() + scene.procs.len() + room.records) as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build });
let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = groups
.iter()
- .map(|&(_, count, _, opaque)| wgpu::BlasTriangleGeometrySizeDescriptor {
+ .map(|&(_, count, _)| wgpu::BlasTriangleGeometrySizeDescriptor {
vertex_format: wgpu::VertexFormat::Float32x3,
vertex_count: (count * 3) as u32,
index_format: None,
index_count: None,
- flags: if opaque { wgpu::AccelerationStructureGeometryFlags::OPAQUE } else { wgpu::AccelerationStructureGeometryFlags::empty() },
+ // (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.)
+ flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
})
.collect();
let mut blases = vec![];
- for (i, (first, count, mask, _)) in groups.iter().enumerate() {
+ for (i, (first, count, mask)) in groups.iter().enumerate() {
if *count == 0 {
continue;
}
@@ -2399,8 +2408,9 @@ 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, then the cutout part (any-hit).
- let mesh_parts: Vec<Vec<(u32, u32, bool)>> = scene.meshes.iter().map(|m| [(m.first, m.opaque, true), (m.first + m.opaque, m.count - m.opaque, false)].into_iter().filter(|p| p.1 > 0).collect()).collect();
+ // 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().into_iter().map(|(at, count, opaque)| (m.first + at, count, opaque)).collect()).collect();
let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts
.iter()
.map(|parts| {
@@ -2427,7 +2437,7 @@ 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, _, opaque)| vec![((first * 3) as u32, (count * 3) as u32, opaque)]);
+ 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 mut blas_per_tri = 0.0;
let parts: Vec<Vec<(u32, u32, bool)>> = group_parts.chain(mesh_vertex_parts).collect();
@@ -3221,15 +3231,15 @@ impl Gpu {
}
/// Mesh `k` (one an edit no longer draws) made again over `count` triangles from `first`: a new BLAS in its slot.
- pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, count: u32, opaque: u32) {
- let (blas, geo) = self.mesh_blas_for(accel, first, count, opaque);
+ pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, mesh: &crate::scene::InstMesh) {
+ let (blas, geo) = self.mesh_blas_for(accel, first, mesh);
accel.meshes[k as usize] = blas;
accel.mesh_geo[k as usize] = geo;
}
- fn mesh_blas_for(&self, accel: &Accel, first: usize, count: u32, opaque: u32) -> (wgpu::Blas, (Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {
+ fn mesh_blas_for(&self, accel: &Accel, first: usize, mesh: &crate::scene::InstMesh) -> (wgpu::Blas, (Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {
let rel = (first - accel.pool_first) as u32;
- let parts: Vec<(u32, u32, bool)> = [(rel, opaque, true), (rel + opaque, count - opaque, false)].into_iter().filter(|p| p.1 > 0).collect();
+ let parts: Vec<(u32, u32, bool)> = mesh.parts().into_iter().map(|(at, count, opaque)| (rel + at, count, opaque)).collect();
let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = parts
.iter()
.map(|&(_, c, opaque)| wgpu::BlasTriangleGeometrySizeDescriptor {
@@ -3247,10 +3257,10 @@ impl Gpu {
/// A new instanced mesh over `count` triangles from GPU-order index `first` (in the edit room; live/edits.rs
/// `edit_geometry`), its first `opaque` ones opaque: its BLAS, which the commit's build builds (`TopBuild::meshes`). Returns its index.
- pub fn add_mesh(&self, accel: &mut Accel, first: usize, count: u32, opaque: u32) -> u32 {
+ pub fn add_mesh(&self, accel: &mut Accel, first: usize, mesh: &crate::scene::InstMesh) -> u32 {
// Built fast rather than traced fast (edits come every frame under destruction; the batches of pieces are rebuilt
// every frame); THREERT_EDIT_BLAS=trace for the A/B (`mesh_blas_for`).
- let (blas, geo) = self.mesh_blas_for(accel, first, count, opaque);
+ let (blas, geo) = self.mesh_blas_for(accel, first, mesh);
accel.meshes.push(blas);
accel.mesh_geo.push(geo);
accel.meshes.len() as u32 - 1
@@ -3653,7 +3663,7 @@ mod tests {
("F_MASKED", F_MASKED), ("F_FOG", F_FOG), ("F_VOLUME", F_VOLUME), ("F_TEX", F_TEX), ("F_FUNC", F_FUNC),
("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),
("F_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_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 3054a81..2da75b5 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -594,15 +594,16 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
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 among the rest: each carries its own flag, as the still
- // scene's do. Hardware traversal has them apart, in a geometry of their own.)
- let cutout = trees.is_some() && sc.materials.get(a.uv[3].to_bits() as usize).is_some_and(|m| m.uv2[3] > 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 })]);
+ // (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());
+ 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 })]);
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, m.opaque) }).collect();
+ sc.gpu_instances = sc.instances.iter().map(|i| { let m = sc.meshes[i.mesh as usize]; i.gpu(pool_first as u32 + m.first, m.part_offsets()) }).collect();
// A scene whose triangles are all units': the still tree is then the leaf of one triangle, triangle 0 (bvh.rs
// `EMPTY`), which no ray meets while triangle 0 is the zeros of an empty buffer. Here triangle 0 is the pool's
// first, a mesh's in its model space, and the still walk would meet it standing in the world. The leaf gets a
@@ -959,7 +960,7 @@ fn flatten_instances(sc: &mut scene::Scene) {
sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
sc.attrs.push(a);
}
- // A second range for the node when its glass / function part was flattened at build: node_tris joins them.
+ // A second range for the node when a part of its mesh was flattened at build: node_tris joins them.
sc.tri_nodes.push((inst.name, first, sc.tris.len() as u32));
if let Some(i) = inst.sub {
sc.tri_instances.push((first, sc.tris.len() as u32, i));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index c967fca..b08cffe 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -761,7 +761,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]), inst.mesh, inst.cast_shadow);
+ let mut r = top.record(inst.gpu(old.info[0], [old.info[3], old.n[0][3].to_bits()]), inst.mesh, inst.cast_shadow);
r.p = old.m;
self.sc.gpu_instances[i as usize] = r;
if merged {
@@ -1083,7 +1083,7 @@ impl LiveCore {
for i in 0..cap {
let (wm, hidden) = scene::instance_world(m, t, i);
let old = sc.gpu_instances[rec0 + i];
- let mut emits = false;
+ let (mut emits, mut casts) = (false, n.cast_shadow);
let (mut rec, entry) = if procedural {
let p = &mut sc.procs[first + i];
(p.world, p.hidden) = (wm, hidden);
@@ -1096,6 +1096,7 @@ impl LiveCore {
(inst.world, inst.hidden) = (wm, hidden);
let im = sc.meshes[inst.mesh as usize];
emits = im.emitters > 0;
+ casts = im.casts(n.cast_shadow);
let (lo, hi) = im.placed_bounds(wm);
let row = scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i));
if emits {
@@ -1110,7 +1111,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]), inst.mesh, n.cast_shadow), scene::copy_row(row, emits && hidden))
+ (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))
};
rec.p = old.m;
sc.gpu_instances[rec0 + i] = rec;
@@ -1122,7 +1123,7 @@ impl LiveCore {
let edited = if e[0][3] != entry[0][3] { now } else { e[1][3] };
e.copy_from_slice(&entry[..st]);
e[1][3] = edited;
- top.moved(slot0 + i, wm, Some((n.cast_shadow, hidden)));
+ top.moved(slot0 + i, wm, Some((casts, hidden)));
}
let q = &self.g.queue;
sc.up.heap.write(q, Table::Instances, (rec0 * size) as u64, bytemuck::cast_slice(&sc.gpu_instances[rec0..rec0 + cap]));
@@ -1226,7 +1227,7 @@ impl LiveCore {
let inst = &mut self.sc.instances[i as usize];
let old = self.sc.gpu_instances[i as usize];
inst.world = w;
- let mut r = inst.gpu(old.info[0], old.info[3]);
+ let mut r = inst.gpu(old.info[0], [old.info[3], old.n[0][3].to_bits()]);
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));
@@ -1791,8 +1792,8 @@ impl LiveCore {
if let Some(k) = was {
drop_mesh_user(k, edit, tables, meshes);
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false, first_emitter: 0 };
- let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
+ 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, first_emitter: 0 };
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), 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)
@@ -1816,13 +1817,10 @@ impl LiveCore {
let gm = tables.materials[mat as usize];
// (It covers instances' triangles from here on: `Tables::fixed_mats`.)
tables.fixed_mats.insert(mat);
- // An emitting material (no glass, no function): a mesh as any other, each instance's emitters in
- // the light list (given below, where its record is known; scene.rs; ROADMAP § 6 step 3).
- let emits = scene::emits_only(&gm);
+ // An emitting material: a mesh as any other, each instance's emitters in the light list (given
+ // below, where its record is known; scene.rs; ROADMAP § 6 step 3).
+ let emits = scene::emissive(&gm);
let class = scene::mesh_class(&gm);
- if class == 2 {
- return Err("a glass material".into());
- }
if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {
return Err("the scene's first material function on an instance (kernel feature)".into());
}
@@ -1867,7 +1865,7 @@ impl LiveCore {
scene::number_emitters(&mut a, &tables.materials);
}
// (A unit's cutout triangles carry their flag; hardware traversal has them in a geometry apart.)
- let flags = f32::from_bits(if tree.is_some() && class == 1 { scene::TRI_MASKED } else { 0 });
+ let flags = f32::from_bits(if tree.is_none() { 0 } else { [0, scene::TRI_MASKED, scene::TRI_NO_SHADOW][class as usize] });
// As `prepare` lays the pool out: (a, flags), e1, e2; attributes; the BLAS's vertices.
let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, flags], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();
let blas_verts: Vec<[f32; 3]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]]).collect();
@@ -1911,10 +1909,10 @@ impl LiveCore {
let k = match &mut top {
gpu::Top::Hw(accel) => match dead {
Some(k) => {
- g.set_mesh(accel, k, first, im.count, im.opaque);
+ g.set_mesh(accel, k, first, &im);
k
}
- None => g.add_mesh(accel, first, im.count, im.opaque),
+ None => g.add_mesh(accel, first, &im),
},
// Its tree into the mesh trees' room (a freed mesh's slot gives its tree back first).
gpu::Top::Sw(units) => {
@@ -2017,7 +2015,7 @@ impl LiveCore {
tables.objects.resize((o0 + cap) * st, [0.0; 4]);
}
for (i, &(wm, hidden)) in placed.iter().enumerate() {
- let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 };
+ let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 };
// A copy of a mesh that emits: its emitters, a run at the light list's end; moving ones
// (`update_instanced` changes the copies in place), a hidden copy's at no weight.
if im.emitters > 0 {
@@ -2032,10 +2030,10 @@ impl LiveCore {
tables.emissive.insert(mat);
emitters_changed = true;
}
- let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
+ let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), 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, o.cast_shadow, hidden);
+ top.place(inst_base + r0 + i, mesh, wm, gpu::INSTANCE_BIT | (r0 + i) as u32, inst.cast_shadow, hidden);
let (lo, hi) = im.placed_bounds(wm);
let entry = scene::copy_row(scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i)), im.emitters > 0 && hidden);
w_objects.put(((o0 + i) * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));
@@ -2045,8 +2043,8 @@ impl LiveCore {
*tables.retained.proxy(id) = scene::Proxy { object: None, card: None, draw: scene::Draw::Instanced(scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, mesh: Some(mesh), drawn: t.count }) };
continue;
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false, first_emitter: 0 };
- let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
+ 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, first_emitter: 0 };
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), 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)
@@ -2111,7 +2109,7 @@ impl LiveCore {
scene::Draw::Procedural(j as u32)
}
Placed::Mesh(inst) => {
- top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, o.cast_shadow, false);
+ top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, false);
if instances.len() <= record {
instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() });
}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index ec93200..07ea96f 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -330,10 +330,10 @@ fn moves_in_place_leave_what_a_build_does() {
}
}
-/// An instanced object the build flattened (an emitting material: its copies are triangles of the static groups)
-/// is gone from the picture once it is removed: nothing takes it out in place, so the scene is rebuilt.
+/// An instanced object whose copies emit is gone from the picture once it is removed (its copies were flattened once,
+/// and nothing took them out).
#[test]
-fn a_flattened_instanced_object_removed_is_gone() {
+fn an_emitting_instanced_object_removed_is_gone() {
let presets = crate::default_presets_dir();
let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
let mut w = world();
@@ -440,6 +440,54 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
assert!(alive > 0, "{what}: the list has emitters");
}
+/// A glass mesh added in place is drawn as a build draws it, whether the scene had glass on an instance or not: a
+/// mesh that is all glass needs nothing of the kernel (its instances are out of a shadow ray's way by their mask).
+/// And a material of an instance's triangles that turns glass rebuilds.
+#[test]
+fn a_glass_mesh_added_is_drawn_as_a_build_draws_it() {
+ 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));
+ for has in [true, false] {
+ let mut w = world();
+ w.set_material(7, serde_json::from_value(serde_json::json!({ "name": "glass", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 0, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "transmission": 1, "ior": 1.5 })).unwrap());
+ let mesh = |geometry, material| Kind::Mesh { geometry, material, own_blas: true, materials: vec![] };
+ // (A mesh with its own BLAS: the scene has instances either way.)
+ w.set_object(14, "own".into(), None, mesh(3, 1), true, false).unwrap();
+ w.set_transform(14, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ if has {
+ w.set_object(18, "glass".into(), None, mesh(3, 7), true, false).unwrap();
+ w.set_transform(18, Vec3::new(0.8, -0.7, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ let mut live = match open(&w) {
+ Ok(c) if c.g.hwrt => c,
+ Ok(_) => return eprintln!("skipped: no hardware RT"),
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_eq!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "no mesh has glass among other triangles");
+ let before = picture(&mut live, 24);
+ // A pane before the wall, in the sun's and the lamp's light.
+ w.set_object(19, "pane".into(), None, mesh(2, 7), true, false).unwrap();
+ w.set_transform(19, Vec3::new(0.1, 0.0, 0.9), glam::Quat::from_rotation_y(0.4), Vec3::splat(0.5)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "glass on an instance already: {has}: in place ({:?})", live.fallback);
+ let pane = live.sc.instances.iter().find(|i| i.name == "pane").expect("the pane is an instance");
+ assert!(!pane.cast_shadow, "an instance of a mesh that is all glass casts no shadow");
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&before, &b) > 0.5, "the pane is in the picture ({:.2} steps)", apart(&before, &b));
+ assert!(apart(&a, &b) < 0.5, "glass on an instance already: {has}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ // A material of an instance's triangles that turns glass (the mesh of its own, and the wall): by a rebuild, its
+ // instances' masks and its mesh's geometries being the build's.
+ w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.8, 0.4, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 0, "doubleSided": true, "transmission": 1, "ior": 1.5 })).unwrap());
+ assert!(live.commit(&mut w).unwrap(), "a material of an instance's triangles turned glass: a rebuild");
+ 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, "a material turned glass: the picture is {:.2} steps from a build's", apart(&a, &b));
+ }
+}
+
/// An instanced object's copies that emit, changed in place, are lit as a build lights them: a copy moved, made
/// larger, shown by the count, hidden by a matrix scaled to 0 and by the count, the node's power changed, the object
/// removed; with and without a light tree. After each: no rebuild, the light list is its triangles, the emitters'
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 177960d..69911e1 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -994,7 +994,7 @@ impl LiveCore {
/// World-space triangles of a node (empty for lights without geometry, cameras, hidden nodes).
pub fn node_tris(&self, id: &str) -> Vec<[glam::Vec3A; 3]> {
- // World-space triangles (an instance's glass / function part among them), then its instanced mesh.
+ // World-space triangles (what the build flattened of an instance's mesh among them), then its instanced mesh.
let mut out: Vec<[glam::Vec3A; 3]> = scene::node_ranges(&self.sc.tri_nodes, id).flat_map(|r| self.sc.tris[r].iter().copied()).collect();
// A model's first instance; every drawn instance of an instanced object.
let mut of_node = self.sc.instances.iter().filter(|i| i.name == id && !i.hidden);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 837d37f..136c178 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -57,9 +57,13 @@ pub fn copy_row(mut row: ObjectRow, dark: bool) -> ObjectRow {
pub struct InstMesh {
pub first: u32,
pub count: u32,
- /// The first `opaque` pool triangles are opaque (BLAS geometry 0), the rest cutout (geometry 1, any-hit test).
+ /// The first `opaque` pool triangles are opaque, the last `glass` glass, those between cutout (alpha-tested):
+ /// a BLAS geometry each (`parts`).
pub opaque: u32,
- /// Triangles each placement flattens instead (glass), in the build's rest arrays.
+ /// 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,
/// Model-space bounds (object bounds of its instances, picking).
@@ -78,6 +82,28 @@ 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 (all but the glass: a query that forces opacity sees every one alike, a shadow ray culls the
+ /// glass).
+ pub fn parts(&self) -> Vec<(u32, u32, bool)> {
+ 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)]
+ }
+
+ /// 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));
@@ -123,15 +149,16 @@ pub struct GpuInstance {
}
impl Instance {
- /// Kernel record with its mesh's first triangle at `first` in the GPU order; `opaque` = where its cutout
- /// geometry starts.
- pub fn gpu(&self, first: u32, opaque: u32) -> GpuInstance {
+ /// 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 {
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(if mirrors(w) { INST_MIRRORED } else { 0 });
- GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, mirrored), nrow(2, f32::from_bits(self.first_emitter))], info: [first, self.object, lod_offset(w).to_bits(), opaque], p: [row(0), row(1), row(2)] }
+ 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)] }
}
/// Model-space triangle `t` of its mesh in world space (the same transform the flattening path applies).
pub fn tri(&self, t: &[Vec3A; 3]) -> [Vec3A; 3] {
@@ -361,12 +388,12 @@ pub fn proc_layout(procs: &[ProcObject], sw: bool) -> ProcLayout {
ProcLayout { head, headers, blobs, blob_of, blob_words, sw }
}
-/// Flags of an instance's pool triangle as a world-space triangle (software traversal): the placement's shadow flag and
-/// the material's cutout (the build's flag pass ran before the instances were flattened).
+/// Flags of an instance's pool triangle as a world-space triangle (software traversal): the placement's shadow flag,
+/// the material's cutout, and no shadow for glass (the build's flag pass ran before the instances were flattened).
pub fn instance_tri_flags(inst: &Instance, a: &GpuTriAttr, materials: &[GpuMaterial]) -> u32 {
- let shadow = if inst.cast_shadow { 0 } else { TRI_NO_SHADOW };
- let cutout = materials.get(a.uv[3].to_bits() as usize).is_some_and(|m| m.uv2[3] > 0.0);
- shadow | if cutout { TRI_MASKED } else { 0 }
+ let m = materials.get(a.uv[3].to_bits() as usize);
+ let shadow = if inst.cast_shadow && !m.is_some_and(|m| m.layer[0] > 0.0) { 0 } else { TRI_NO_SHADOW };
+ shadow | if m.is_some_and(|m| m.uv2[3] > 0.0) { TRI_MASKED } else { 0 }
}
/// Triangle ranges of node `id` in build order: one, or two for an instanced node flattened by software traversal (its
@@ -755,9 +782,8 @@ pub struct InstancedPlace {
/// A posed glTF model without skins whose clip moves some of its nodes (Zero Day's 551 moving objects): the nodes the
/// clip leaves alone are ordinary static triangles; each moving mesh node is an instance of its own mesh (its triangles
/// in the node's space, one BLAS built once), placed at object x node transform, so a new pose moves instances
-/// only (a node's emitters are its instance's in the light list, filled again when it moves). Their glass
-/// triangles are flattened (shadow rays), and what `flatten_coincident` takes with them: `rest`,
-/// re-transformed in place from `rest_local`.
+/// only (a node's emitters are its instance's in the light list, filled again when it moves). What
+/// `flatten_coincident` takes out of a node's mesh is flattened: `rest`, re-transformed in place from `rest_local`.
#[derive(Clone, Default)]
pub struct RigidModel {
/// (glTF node, instance index).
@@ -1304,14 +1330,14 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let grid_programs: Vec<(String, String, String)> = w.grid_programs.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();
let mut objects: Vec<[f32; 4]> = vec![];
// Static glTF models drawn more than once share their triangles (model space, one BLAS): opaque, shadow-casting
- // per node, no glass. THREERT_INSTANCING=0 flattens everything.
+ // per node. THREERT_INSTANCING=0 flattens everything.
let instancing = std::env::var("THREERT_INSTANCING").map_or(true, |v| v != "0");
let mut pool_tris: Vec<[Vec3A; 3]> = vec![];
let (mut vcolors, mut pool_vcolors): (Vec<[u32; 3]>, Vec<[u32; 3]>) = (vec![], vec![]);
// Whether a mesh's triangles carry its geometry's vertex colours: any of its materials asks for them.
let colored = |g: &world::Geometry, mats: &mut dyn Iterator<Item = &u32>| !g.colors.is_empty() && mats.filter(|k| w.materials.get(k).is_some_and(|m| m.vertex_colors)).count() > 0;
let mut pool_attrs: Vec<GpuTriAttr> = vec![];
- // Model-space triangles of instanced meshes that each placement flattens (glass).
+ // Model-space triangles of instanced meshes that each placement flattens (`flatten_coincident`'s pairs).
let mut rest_tris: Vec<[Vec3A; 3]> = vec![];
let mut rest_attrs: Vec<GpuTriAttr> = vec![];
let mut meshes: Vec<InstMesh> = vec![];
@@ -1357,21 +1383,21 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if shown && instancing && mesh_mats.len() <= 1 && m.determinant() != 0.0 && (n.driven || (*own_blas && !w.movable(*id))) => {
// Its own BLAS (scene code's `dynamicGeometry`, or a mesh a rigid body drives: its moves are the
// instance's transform, `InstanceRef::moves`): placed like a model instance, its geometry's triangles
- // in model space in the pool, shared by the objects of the same geometry and material. Glass is
- // flattened (as a model's would be), so it is never instanced. A material that emits is: each
- // instance has its emitters in the light list (`InstMesh::emitters`).
+ // in model space in the pool, shared by the objects of the same geometry and material, whatever the
+ // material (`mesh_class`: glass is its mesh's glass part; one that emits has each instance's
+ // emitters in the light list, `InstMesh::emitters`).
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
let class = mesh_class(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
- if class < 2 {
+ {
let mesh = match retained.own_mesh.get(&(*geometry, mat)) {
Some(&k) => Some(k),
None => {
let (t, a) = own_mesh_tris(g, mat);
(!t.is_empty()).then(|| {
let mut im = own_inst_mesh(&t, pool_tris.len() as u32, class);
- if emits_only(&materials[mat as usize]) {
+ if emissive(&materials[mat as usize]) {
im.emitters = t.len() as u32;
}
meshes.push(im);
@@ -1391,16 +1417,8 @@ 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) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven }) };
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
+ 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, first_emitter: 0 });
}
- continue;
- }
- put_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, false, None)));
- // (A driven mesh that cannot be an instance (glass): dynamic triangles,
- // re-transformed in place as any movable mesh's.)
- append_arrays(g, m, mat, if n.driven { flags | TRI_DYNAMIC } else { flags }, None, &mut tris, &mut tri_flags, &mut attrs);
- if n.driven {
- retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });
}
}
Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {
@@ -1408,8 +1426,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// copies' records and entries contiguous (live/edits.rs `update_instanced` rewrites them in place).
// A material that only emits is such a mesh too: each copy has its emitters in the light list
// (`InstMesh::emitters`), a hidden copy's at no weight (its object has no power). A copy may mirror
- // the mesh (`INST_MIRRORED`). Glass is flattened instead, each copy its own triangles, as `own_blas`
- // meshes are; changing its instances rebuilds.
+ // the mesh (`INST_MIRRORED`). Without instancing each copy is its own triangles, and changing the
+ // instances rebuilds.
let empty = world::InstanceTable::default();
let t = w.instanced.get(id).unwrap_or(&empty);
let placed: Vec<(Mat4, bool)> = (0..*capacity as usize).map(|i| instance_world(m, t, i)).collect();
@@ -1430,9 +1448,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let material = mats.first().ok_or_else(|| anyhow!("object {}: an instanced mesh needs a material", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
let class = mesh_class(&materials[mat as usize]);
- let emits = emits_only(&materials[mat as usize]);
+ let emits = emissive(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
- if instancing && class < 2 {
+ if instancing {
let mesh = match inst_mesh_of.get(&(*geometry, mat)) {
Some(&k) => Some(k),
None => {
@@ -1458,7 +1476,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
- instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 });
+ instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 });
}
}
continue;
@@ -1510,8 +1528,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let key = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };
// (Its meshes too: placements share a mesh only with the same functions.)
let mesh_key = (key.clone(), nodes.clone());
- // (material index, instancing class: 0 opaque, 1 cutout, 2 flattened per placement: glass (shadow rays
- // pass), emissive (emitter sampling), material function)
// A material of the file: its index, its class in a mesh (`mesh_class`), whether it only emits.
let mut resolve = |gm: Option<gltf::Material>| -> Result<(u32, u32, bool)> {
let idx = gm.as_ref().and_then(|g| g.index()).unwrap_or(usize::MAX);
@@ -1538,7 +1554,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
i
}
};
- Ok((i, mesh_class(&materials[i as usize]), emits_only(&materials[i as usize])))
+ Ok((i, mesh_class(&materials[i as usize]), emissive(&materials[i as usize])))
};
// A posed model's triangles are dynamic (re-skinned in place). A movable one is an instance whose
// transform moves (hardware RT), unless it has triangles flattened per placement: then they are dynamic
@@ -1580,7 +1596,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let rest_first = tris.len() as u32;
for (ni, list) in &by_node {
let w_n = m * globals[*ni];
- let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
+ let mut classed: [Vec<(usize, u32)>; 4] = Default::default();
let mut emitting: std::collections::HashSet<u32> = Default::default();
for &k in list {
let (mat, class, emits) = resolve(local[k].1.material.and_then(|i| doc.materials().nth(i)))?;
@@ -1591,10 +1607,10 @@ 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[0].len() + classed[1].len() > 0 {
+ 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[..2] {
+ for list in &classed[..FLAT] {
for &(k, mat) in list {
let t = &local[k].1;
for v in t.p {
@@ -1611,12 +1627,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
olo = olo.min(q);
ohi = ohi.max(q);
}
- let count = (classed[0].len() + classed[1].len()) as u32;
- meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters });
+ 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 });
rigid.instances.push((*ni, instances.len() as u32));
- instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
+ 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, first_emitter: 0 });
}
- for &(k, mat) in &classed[2] {
+ for &(k, mat) in &classed[FLAT] {
let t = &local[k].1;
let (p, nn, uv, tg) = placed_tri(w_n, &t.p, &t.n, &t.uv, t.tangent);
push_tri(&mut tris, &mut tri_flags, &mut attrs, p, nn, uv, tg, mat, base_flags | TRI_DYNAMIC);
@@ -1654,19 +1670,19 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
None => {
let a = animation.as_ref().unwrap();
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), Some(a))?;
- let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
+ let mut classed: [Vec<(usize, u32)>; 4] = Default::default();
for (k, t) in local.iter().enumerate() {
// (A mesh that deforms does not keep its emitters: the light list does not follow a
// pose yet.)
let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
- classed[if emits { 2 } else { class as usize }].push((k, mat));
+ classed[if emits { FLAT } else { class as usize }].push((k, mat));
}
- // Triangles flattened per placement (glass, emissive): each model skinned alone.
- let g = (classed[2].is_empty() && !local.is_empty()).then(|| {
+ // Triangles flattened per placement (emissive): each model skinned alone.
+ 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[..2] {
+ for list in &classed[..FLAT] {
for &(k, mat) in list {
let t = &local[k];
for v in t.p {
@@ -1680,7 +1696,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
// 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, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emitters: 0 });
+ 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 });
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
});
@@ -1696,7 +1712,7 @@ 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: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
+ 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, first_emitter: 0 });
*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;
@@ -1709,10 +1725,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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`); glass triangles are flattened per
- // placement (shadow-ray pass-through).
+ // emitters in the light list: `InstMesh::emitters`), its glass the mesh's glass part.
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), None)?;
- let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
+ let mut classed: [Vec<(usize, u32)>; 4] = Default::default();
let mut emitting: std::collections::HashSet<u32> = Default::default();
for (k, t) in local.iter().enumerate() {
let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
@@ -1722,7 +1737,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
}
flatten_coincident(&mut classed, &emitting, &|k| local[k].p);
- let k = (classed[0].len() + classed[1].len() > 0).then(|| {
+ let k = classed[..FLAT].iter().any(|l| !l.is_empty()).then(|| {
let (first, rest_first) = (pool_tris.len() as u32, rest_tris.len() as u32);
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
for t in &local {
@@ -1732,20 +1747,20 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
}
for (class, list) in classed.iter().enumerate() {
- let (pt, pa) = if class < 2 { (&mut pool_tris, &mut pool_attrs) } else { (&mut rest_tris, &mut rest_attrs) };
+ 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 count = (classed[0].len() + classed[1].len()) as u32;
+ 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, rest_first, rest_count: classed[2].len() as u32, lo, hi, deforms: false, emitters });
+ 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 });
meshes.len() as u32 - 1
});
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
- eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout instanced; {} flattened per placement", classed[0].len(), classed[1].len(), classed[2].len());
+ eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout, {} glass instanced; {} flattened per placement", classed[0].len(), classed[1].len(), classed[2].len(), classed[FLAT].len());
}
// (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.)
@@ -1765,7 +1780,7 @@ 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: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 };
+ 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, first_emitter: 0 };
// 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);
@@ -2185,39 +2200,41 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu
})
}
-/// A model's triangles by class (`classed`: opaque, cutout, flattened; each a triangle's index and material): those on
-/// exactly the same vertices leave the mesh together, a pool triangle with a flattened one and one that emits (a
-/// material of `emitting`) with a cutout over it (Zero Day: masked decals over emissive quads of the same shape). A
-/// cutout hit that its alpha lets through steps the ray on past it (trace_hw.wgsl), and past what lies at the same t:
-/// in one BLAS the emitter under the decal went with it (black through the decal). Flattened, the two are in BLASes
-/// apart and the opaque one is met first, as the software BVH has it.
-fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 3], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {
+/// A model's triangles by class (`classed`: opaque, cutout, glass, and `FLAT`: what leaves the mesh; each a triangle's
+/// index and material). Triangles on exactly the same vertices leave the mesh together in two cases: one that emits (a
+/// material of `emitting`) with a cutout over it (Zero Day: masked decals over emissive quads of the same shape), and
+/// glass with whatever lies under it. A cutout hit that its alpha lets through steps the ray on past it
+/// (trace_hw.wgsl), and past what lies at the same t: in one BLAS the emitter under the decal went with it (black
+/// through the decal); and which of two triangles at one distance a closest hit reports is not said. Flattened, the
+/// two are in BLASes apart and the opaque one is met first, as the software BVH has it.
+fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {
let key = |k: usize| {
let mut v = p(k).map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
v.sort_unstable();
v
};
- let mut flat: std::collections::HashSet<[[u32; 3]; 3]> = classed[2].iter().map(|&(k, _)| key(k)).collect();
- let cutouts: std::collections::HashSet<[[u32; 3]; 3]> = classed[1].iter().map(|&(k, _)| key(k)).collect();
+ let keys = |list: &[(usize, u32)]| -> std::collections::HashSet<[[u32; 3]; 3]> { list.iter().map(|&(k, _)| key(k)).collect() };
+ let (cutouts, glass) = (keys(&classed[1]), keys(&classed[2]));
+ let mut flat = keys(&classed[FLAT]);
flat.extend(classed[0].iter().filter(|(_, mat)| emitting.contains(mat)).map(|&(k, _)| key(k)).filter(|v| cutouts.contains(v)));
- for c in 0..2 {
+ flat.extend(classed[..2].iter().flatten().map(|&(k, _)| key(k)).filter(|v| glass.contains(v)));
+ for c in 0..FLAT {
let (stay, go): (Vec<_>, Vec<_>) = classed[c].iter().partition(|&&(k, _)| !flat.contains(&key(k)));
classed[c] = stay;
- classed[2].extend(go);
+ classed[FLAT].extend(go);
}
}
/// The emitting triangles a mesh keeps (`InstMesh::emitters`): those of `classed` that stay in the pool.
-fn pool_emitters(classed: &[Vec<(usize, u32)>; 3], emitting: &std::collections::HashSet<u32>) -> u32 {
- classed[..2].iter().flatten().filter(|(_, mat)| emitting.contains(mat)).count() as u32
+fn pool_emitters(classed: &[Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>) -> u32 {
+ classed[..FLAT].iter().flatten().filter(|(_, mat)| emitting.contains(mat)).count() as u32
}
-/// Instancing class of a GPU material: 0 opaque, 1 cutout (any-hit), 2 flattened per placement (glass: shadow rays pass;
-/// emissive, where the light list does not follow the mesh: one that deforms. Elsewhere `mesh_class`). A material
-/// function is no reason: the kernel gives it the triangle as its instance places it (`mat_in_at`).
+/// Whether a material created since the build can be drawn in place (tables.rs `add_materials`): 0 only when it is
+/// opaque, does not emit and is no glass (the build sorts triangles and lights by those).
pub fn material_class(g: &GpuMaterial) -> u32 {
- let flat = g.layer[0] > 0.0 || g.emissive[..3].iter().any(|e| *e > 0.0);
- if flat {
+ let other = g.layer[0] > 0.0 || g.emissive[..3].iter().any(|e| *e > 0.0);
+ if other {
2
} else if g.uv2[3] > 0.0 {
1
@@ -2268,31 +2285,40 @@ pub fn own_mesh_tris(g: &world::Geometry, mat: u32) -> (Vec<[Vec3A; 3]>, Vec<Gpu
(tris, attrs)
}
-/// A material that emits and is no glass: an `own_blas` mesh of it is a mesh as any other, its instances' emitters in
-/// the light list (`InstMesh::emitters`).
-pub fn emits_only(g: &GpuMaterial) -> bool {
- g.layer[0] <= 0.0 && g.emissive[..3].iter().any(|e| *e > 0.0)
+/// A material that emits: a mesh's triangles of it are its instances' emitters in the light list
+/// (`InstMesh::emitters`).
+pub fn emissive(g: &GpuMaterial) -> bool {
+ g.emissive[..3].iter().any(|e| *e > 0.0)
}
-/// `material_class` in a mesh whose instances have their emitters in the light list (an `own_blas` mesh, a model's
-/// that does not deform, an instanced object's): a material that only emits is opaque or cutout there, not flattened.
+/// 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
+/// 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 emits_only(g) { u32::from(g.uv2[3] > 0.0) } else { material_class(g) }
+ if g.layer[0] > 0.0 {
+ 2
+ } else {
+ u32::from(g.uv2[3] > 0.0)
+ }
}
+/// `classed`'s last list: what leaves a mesh and is flattened at each placement (`flatten_coincident`'s pairs; the
+/// 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(emits_only);
+ 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 an `own_blas` mesh's triangles at pool index `first` (class: `material_class`, 0 or 1).
+/// The `InstMesh` of an `own_blas` mesh's triangles at pool index `first`, all of one class (`mesh_class`).
pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
for t in tris {
@@ -2302,7 +2328,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 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0 }
+ 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 }
}
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
@@ -2490,7 +2516,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, first_emitter: 0 };
- assert_eq!(inst.gpu(0, 0).n[1][3].to_bits(), if mirrored { INST_MIRRORED } else { 0 }, "the record says whether it mirrors");
+ assert_eq!(inst.gpu(0, [0, 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] };
@@ -2530,8 +2556,8 @@ mod instance_tests {
assert_eq!(instance_tri_flags(&inst(false), &a(1), &mats), TRI_MASKED | TRI_NO_SHADOW);
}
- /// A node's triangles may come in two ranges (an instance's glass part flattened at build, its mesh appended by
- /// software traversal): selection outlines need both.
+ /// A node's triangles may come in two ranges (what the build flattened of an instance's mesh, the mesh appended
+ /// by software traversal): selection outlines need both.
/// An instanced object: one shared mesh, an instance and an object entry per copy (capacity, not count), hidden
/// past the count and where a matrix scales to 0; a copy may mirror the mesh.
#[test]
@@ -2556,7 +2582,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).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED, 0, 0, 0], "and its record says so");
+ assert_eq!(sc.instances.iter().map(|i| i.gpu(0, [0, 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,
@@ -2612,8 +2638,8 @@ mod instance_tests {
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).n[1][3].to_bits() == 0));
- assert!(mirrored.instances.iter().all(|i| i.gpu(0, 0).n[1][3].to_bits() == INST_MIRRORED), "every instance of a mirrored model mirrors");
+ 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");
// 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")] {
@@ -2624,6 +2650,34 @@ mod instance_tests {
}
}
+ /// 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.
+ #[test]
+ fn a_models_glass_is_a_part_of_its_mesh() {
+ 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();
+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
+ for id in [1, 2] {
+ w.set_object(id, format!("model{id}"), None, Kind::Model { uri: "tests/render/data/frame-pane.glb".into(), nodes: None, animation: None, functions: vec![] }, true, false).unwrap();
+ 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.instances.len(), sc.tris.len()), (2, 0));
+ assert_eq!((sc.meshes[0].parts(), sc.meshes[0].part_offsets()), (vec![(0, 2, true), (2, 2, true), (4, 2, false)], [2, 4]));
+ 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");
+ 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]));
+ }
+
/// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_coincident`), in a model that stays
/// and in a rigid model's moving node (tests/render/data/panel-decal.glb: panel.glb, a grey quad and an emitting
/// one, with a masked quad on the emitting one's vertices): each mesh keeps the grey quad alone.
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 1df8bf5..a30c821 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -147,8 +147,10 @@ impl Tables {
return Ok(None);
}
// (A material of instances' triangles that gets a function, or loses it: the kernel's variant goes by
- // whether there is one, `gpu::F_IFUNC`, which the build decides.)
- if (gm.tex1[3] != 0) != (self.materials[mi as usize].tex1[3] != 0) && self.fixed_mats.contains(&mi) {
+ // whether there is one, `gpu::F_IFUNC`, which the build decides. One that turns glass, or stops being
+ // glass: its triangles are a geometry of their mesh's BLAS by that, `scene::mesh_class`.)
+ let old = &self.materials[mi as usize];
+ if ((gm.tex1[3] != 0) != (old.tex1[3] != 0) || (gm.layer[0] > 0.0) != (old.layer[0] > 0.0)) && self.fixed_mats.contains(&mi) {
return Ok(None);
}
self.materials[mi as usize] = gm;
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index ef71d51..46221df 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -1106,6 +1106,11 @@ pub(crate) mod cpu {
let ti = first + n.left_or_first + k;
let x = self.intersect_tri(ro, rd, ti, hit.t)?;
if x < hit.t {
+ // (A unit's glass: shadow rays pass it.)
+ let flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();
+ if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {
+ continue;
+ }
hit = Hit { t: x, tri: ti, inst: rec };
if mode != TRACE_CLOSEST {
return Ok(hit);
@@ -1335,7 +1340,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, first_emitter: 0 };
- unit_record(inst.gpu(first, 0), root, cast)
+ unit_record(inst.gpu(first, [0, 0]), root, cast)
}
fn add_unit(&mut self, mesh: usize, world: Mat4, cast: bool) -> usize {
@@ -1948,7 +1953,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, first_emitter: 0 }.gpu(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, first_emitter: 0 }.gpu(0, [0, 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 53bd986..8ad86d0 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, first_emitter: 0 };
- l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, tris.len() as u32), root as u32, true);
+ l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, [tris.len() as u32, 0]), 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/frame-pane.glb b/tests/render/data/frame-pane.glb
new file mode 100644
index 0000000..31e135b
Binary files /dev/null and b/tests/render/data/frame-pane.glb differ
diff --git a/tests/render/glass-mirrored-instance.ts b/tests/render/glass-mirrored-instance.ts
new file mode 100644
index 0000000..c3cd50f
--- /dev/null
+++ b/tests/render/glass-mirrored-instance.ts
@@ -0,0 +1,33 @@
+// Glass on an instance that mirrors its mesh: which side of a surface a ray meets goes by the instance's sign
+// (pathtrace.wgsl `surface`, `inst_sign`). Two glass slabs of one mesh, each a mesh of its own, turned 50 degrees to
+// the camera's rays, mirror images of each other, the right one placed with a negative scale; behind them an
+// emitting wall of 1 nit, no sky. Each shows the wall through it, alike. A slab entered as if from inside reflects
+// the ray whole at that angle (past the critical one), and shows black.
+import { BoxGeometry, Color, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { glass } from "./shadow-glass-tint-instance.ts";
+
+export const test: TestMeta = {
+ id: "glass/mirrored-instance", features: ["transmission", "instancing", "mirrored"], reference: "analytic", temporal: false,
+ metric: { kind: "ratio", a: [0.61, 0.4, 0.66, 0.6], b: [0.34, 0.4, 0.39, 0.6], expected: 1, tolerance: 0.03 },
+ spp: 256,
+ note: "left slab as it is, right slab mirrored in x: the wall seen through each, right / left = 1",
+};
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const wall = new Mesh(new PlaneGeometry(40, 40), new MeshStandardMaterial({ name: "wall", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 1, roughness: 1 }));
+ wall.position.z = -3;
+ const geometry = new BoxGeometry(1.6, 1.6, 0.1);
+ const material = glass();
+ const slabs = [-1, 1].map((x) => {
+ const m = new Mesh(geometry, material);
+ m.name = x < 0 ? "left" : "right";
+ m.dynamicGeometry = true;
+ m.position.x = x;
+ m.rotation.y = (-x * 50 * Math.PI) / 180;
+ m.scale.x = x < 0 ? 1 : -1;
+ return m;
+ });
+ return result(scene, camera(scene, [0, 0, 8], [0, 0, 0]), [wall, ...slabs]);
+};
diff --git a/tests/render/shadow-glass-model-cutout.ts b/tests/render/shadow-glass-model-cutout.ts
new file mode 100644
index 0000000..6c68de0
--- /dev/null
+++ b/tests/render/shadow-glass-model-cutout.ts
@@ -0,0 +1,13 @@
+// shadow/glass-model, the plane in the cutout quad's shadow (its alpha is 1 all over): a shadow ray that culls the
+// mesh's glass still meets its cutout part, the mesh's second geometry of three. The point 1 m left of the light's
+// foot against the point 1 m right of it: nothing.
+import type { TestMeta } from "./lib.ts";
+import def, { at, test as base } from "./shadow-glass-model.ts";
+
+export const test: TestMeta = {
+ ...base, id: "shadow/glass-model-cutout", features: [...base.features, "cutout"],
+ metric: { kind: "ratio", a: at(-1), b: at(1), expected: 0, tolerance: 0.02 },
+ note: "the plane 1 m left of the light's foot (the cutout quad's shadow) over the plane 1 m right of it (lit)",
+};
+
+export default def;
diff --git a/tests/render/shadow-glass-model-frame.ts b/tests/render/shadow-glass-model-frame.ts
new file mode 100644
index 0000000..ed9f0d2
--- /dev/null
+++ b/tests/render/shadow-glass-model-frame.ts
@@ -0,0 +1,13 @@
+// shadow/glass-model, the plane in the opaque quad's shadow: a shadow ray that culls the mesh's glass still meets
+// its opaque part. The point 2 m left of the light's foot (its ray to the light meets the opaque quad's centre)
+// against the point 1 m right of it (its ray passes beside the model): nothing.
+import type { TestMeta } from "./lib.ts";
+import def, { at, test as base } from "./shadow-glass-model.ts";
+
+export const test: TestMeta = {
+ ...base, id: "shadow/glass-model-frame",
+ metric: { kind: "ratio", a: at(-2), b: at(1), expected: 0, tolerance: 0.02 },
+ note: "the plane 2 m left of the light's foot (the opaque quad's shadow) over the plane 1 m right of it (lit)",
+};
+
+export default def;
diff --git a/tests/render/shadow-glass-model-live-exact.ts b/tests/render/shadow-glass-model-live-exact.ts
new file mode 100644
index 0000000..284740a
--- /dev/null
+++ b/tests/render/shadow-glass-model-live-exact.ts
@@ -0,0 +1,8 @@
+// shadow/glass-model in the real-time renderer without `APPROX.glassShadows`: the offline value. (Under software
+// traversal the model is a unit, and a shadow ray skips its glass triangles by their flag.)
+import def, { test as base } from "./shadow-glass-model.ts";
+import { APPROX, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "shadow/glass-model-live-exact", metric: { ...base.metric, tolerance: 0.03 }, temporal: true, live: 120, approx: APPROX.all & ~APPROX.glassShadows };
+
+export default def;
diff --git a/tests/render/shadow-glass-model.ts b/tests/render/shadow-glass-model.ts
new file mode 100644
index 0000000..504a2b8
--- /dev/null
+++ b/tests/render/shadow-glass-model.ts
@@ -0,0 +1,37 @@
+// A model whose one mesh has an opaque part, a cutout part and a glass part (tests/render/data/frame-pane.glb: three
+// quads side by side, the first two dark, the cutout's alpha 1 all over, the glass's colour 0.5, ior 1.5), placed
+// twice so that it is instanced: the three are geometries of one BLAS. A point light (1000 cd) 2 m above an
+// albedo-0.5 Lambert plane, the glass quad half way, under the light. A shadow ray passes the glass and is weighed by
+// it, once (one surface): the plane below reads 0.5 I / 4 / pi x 0.96 x 0.5. shadow/glass-model-frame and
+// shadow/glass-model-cutout read the plane in the other two quads' shadows.
+import { GLTFModel, PointLight } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { CLEAR } from "./shadow-glass-tint.ts";
+
+export const test: TestMeta = {
+ id: "shadow/glass-model", features: ["point-light", "transmission", "shadows", "gltf", "instancing"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.485, 0.48, 0.515, 0.52], expected: CLEAR * 0.96 * 0.5, tolerance: 0.02 },
+ spp: 256,
+ requires: ["tests/render/data/frame-pane.glb"],
+ note: "the glass quad (0.5 x 0.5 m) at y = 1 under a light at y = 2; the camera's rays to the plane pass under the model",
+};
+
+/** Where the plane point `x` m along x is in the picture (the camera 3.06 m from the origin, 50 degrees). */
+export const at = (x: number): [number, number, number, number] => {
+ const u = 0.5 + x / (2 * Math.hypot(0.6, 3) * Math.tan((25 * Math.PI) / 180) * (16 / 9));
+ return [u - 0.0175, 0.48, u + 0.0175, 0.52];
+};
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const l = new PointLight(0xffffff, 1000, 0);
+ l.radius = 0.001;
+ l.position.set(0, 2, 0);
+ const models = [0, 300].map((x, k) => {
+ const m = new GLTFModel("tests/render/data/frame-pane.glb");
+ m.name = `model${k}`;
+ m.position.set(x, 1, 0);
+ return m;
+ });
+ return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0], 50), [l, ...models, plane(20, lambert(0.5))]);
+}
diff --git a/tests/render/shadow-glass-tint-instance-live-exact.ts b/tests/render/shadow-glass-tint-instance-live-exact.ts
new file mode 100644
index 0000000..b4a9f56
--- /dev/null
+++ b/tests/render/shadow-glass-tint-instance-live-exact.ts
@@ -0,0 +1,7 @@
+// shadow/glass-tint-instance in the real-time renderer without `APPROX.glassShadows`: the offline value.
+import def, { test as base } from "./shadow-glass-tint-instance.ts";
+import { APPROX, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "shadow/glass-tint-instance-live-exact", metric: { ...base.metric, tolerance: 0.03 }, temporal: true, live: 120, approx: APPROX.all & ~APPROX.glassShadows };
+
+export default def;
diff --git a/tests/render/shadow-glass-tint-instance-live.ts b/tests/render/shadow-glass-tint-instance-live.ts
new file mode 100644
index 0000000..6a34ddd
--- /dev/null
+++ b/tests/render/shadow-glass-tint-instance-live.ts
@@ -0,0 +1,12 @@
+// shadow/glass-tint-instance in the real-time renderer as it ships: its shadow rays pass glass in full
+// (`APPROX.glassShadows`), an instance's glass as any other: the plane reads what it would without the pane.
+import def, { test as base } from "./shadow-glass-tint-instance.ts";
+import { CLEAR } from "./shadow-glass-tint.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ ...base, id: "shadow/glass-tint-instance-live", metric: { ...base.metric, expected: CLEAR, tolerance: 0.03 }, temporal: true, live: 120,
+ note: "the live approximation's value: the light unattenuated",
+};
+
+export default def;
diff --git a/tests/render/shadow-glass-tint-instance.ts b/tests/render/shadow-glass-tint-instance.ts
new file mode 100644
index 0000000..5305910
--- /dev/null
+++ b/tests/render/shadow-glass-tint-instance.ts
@@ -0,0 +1,23 @@
+// shadow/glass-tint with the pane a mesh of its own (`dynamicGeometry`): an instance whose mesh is glass, a BLAS
+// geometry that is not flagged opaque. A shadow ray culls such geometry (trace_hw.wgsl) and `glass_tr` weighs what
+// the pane lets through: the plane under it reads the same 0.5 I / 4 / pi x (0.96 x 0.5)^2. Taken as opaque, the
+// pane would leave it black.
+import { BoxGeometry, Color, Mesh, MeshPhysicalMaterial, PointLight } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { test as base } from "./shadow-glass-tint.ts";
+
+export const test: TestMeta = { ...base, id: "shadow/glass-tint-instance", features: [...base.features, "instancing"] };
+
+export const glass = () => new MeshPhysicalMaterial({ name: "pane", color: new Color().setRGB(0.5, 0.5, 0.5), transmission: 1, ior: 1.5, roughness: 0, metalness: 0 });
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const l = new PointLight(0xffffff, 1000, 0);
+ l.radius = 0.001;
+ l.position.set(0, 2, 0);
+ const pane = new Mesh(new BoxGeometry(1, 0.05, 1), glass());
+ pane.name = "pane";
+ pane.dynamicGeometry = true;
+ pane.position.set(0, 1, 0);
+ return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0]), [l, pane, plane(20, lambert(0.5))]);
+}
diff --git a/tests/render/shadow-glass-tint-instanced.ts b/tests/render/shadow-glass-tint-instanced.ts
new file mode 100644
index 0000000..4e7eed0
--- /dev/null
+++ b/tests/render/shadow-glass-tint-instanced.ts
@@ -0,0 +1,20 @@
+// shadow/glass-tint with the pane a copy of an InstancedMesh (a second copy is hidden): the copies' mesh is glass, and
+// a shadow ray passes it as it passes any instance's glass.
+import { BoxGeometry, InstancedMesh, Matrix4, PointLight } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { test as base } from "./shadow-glass-tint.ts";
+import { glass } from "./shadow-glass-tint-instance.ts";
+
+export const test: TestMeta = { ...base, id: "shadow/glass-tint-instanced", features: [...base.features, "instancing", "instanced-mesh"] };
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const l = new PointLight(0xffffff, 1000, 0);
+ l.radius = 0.001;
+ l.position.set(0, 2, 0);
+ const panes = new InstancedMesh(new BoxGeometry(1, 0.05, 1), glass(), 2);
+ panes.name = "panes";
+ panes.setMatrixAt(0, new Matrix4().makeTranslation(0, 1, 0));
+ panes.setMatrixAt(1, new Matrix4().makeScale(0, 0, 0));
+ return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0]), [l, panes, plane(20, lambert(0.5))]);
+}