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.

Material functions and mirrored placements on instances (#160)

Yujiac03fdefda57a
diff --git a/docs/PARITY.md b/docs/PARITY.md
index 2ebbc00..863b5fb 100644
--- a/docs/PARITY.md
+++ b/docs/PARITY.md
@@ -38,8 +38,8 @@ Engine (renderer + DSL; at the time also the scene IR and its UE adapter, both s
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 and material-function triangles
- are flattened per placement (shadow rays, a function's inputs), skinned and mirrored models entirely. A model's
+ 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
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 d51c8b3..6ed978a 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2714,6 +2714,22 @@ Tests: `geometry/emitter-instanced` (analytic), `geometry/emitter-instanced-live
shown in place), the build's, and the edits in place against a build (a copy moved, larger, shown, hidden two ways,
the node's power, the object removed; with and without a light tree).
+**Material functions and mirrored placements on instances (2026-11-18).** Two more reasons to flatten a mesh at
+every placement are gone. A material function's inputs outside full shading (the alpha test of a candidate hit, an
+emitter's radiance in light sampling: `mat_in_at`) read the triangle as world space; they now place it by its
+instance, as full shading does. A placement with a negative scale (a mesh, a model, an instanced object's copy, a
+rigid model's node, whose mesh was built with its winding swapped instead) is an instance whose record says that it
+mirrors (`INST_MIRRORED`): the kernel's placement takes the sign for the geometric normal's side and the tangent
+frame's hand. The flattening path (software traversal without units, a model's glass part) swaps the second and
+third vertex of such an instance's triangles, with their attributes and vertex colours. A copy may become mirrored
+in place. An emitting instanced object added in place now gets its emitters there (a run a copy at the list's end,
+by power share where a tree has no place for them, as a driven mesh added in place). What the build still flattens
+at a placement: glass (the next part).
+Tests: a function's emission and a function's alpha on a mesh far from the origin, the tangent frame's hand and the
+geometric normal through a function on a mirrored mesh, vertex colours on one (each natively and under software
+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.
+
**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 feea075..d7ab77e 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -89,6 +89,7 @@ const F_UNLIT: u32 = 1048576u; // MeshBasicMaterial (MAT_UNLIT)
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_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; }
@@ -279,6 +280,10 @@ fn vcolor(t: u32, u: f32, v: f32) -> vec3<f32> {
fn inst_vec(r: Instance, v: vec3<f32>) -> vec3<f32> { return vec3<f32>(dot(r.m0.xyz, v), dot(r.m1.xyz, v), dot(r.m2.xyz, v)); }
+// An instance that mirrors its mesh (scene.rs `INST_MIRRORED`, a bit of the record's n1.w): -1, else 1. The placed
+// edges' cross product then points to the mesh's inner side, and the tangent frame changes hand.
+const INST_MIRRORED: u32 = 4u;
+fn inst_sign(r: Instance) -> f32 { return select(1.0, -1.0, (bitcast<u32>(r.n1.w) & INST_MIRRORED) != 0u); }
fn inst_normal(r: Instance, n: vec4<f32>) -> vec4<f32> {
return vec4<f32>(normalize(vec3<f32>(dot(r.n0.xyz, n.xyz), dot(r.n1.xyz, n.xyz), dot(r.n2.xyz, n.xyz))), n.w);
}
@@ -293,7 +298,7 @@ fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
b.n0 = inst_normal(r, a.n0);
b.n1 = inst_normal(r, a.n1);
b.n2 = inst_normal(r, a.n2);
- b.t = vec4<f32>(normalize(inst_vec(r, a.t.xyz)), a.t.w);
+ b.t = vec4<f32>(normalize(inst_vec(r, a.t.xyz)), a.t.w * inst_sign(r));
b.x = inst_x(r.info, a.x);
return b;
}
@@ -1134,12 +1139,26 @@ fn obj_tint(oi: u32) -> vec3<f32> { return object_at(oi * OBJECT_STRIDE + 3u).rg
fn obj_power(a: TriAttr) -> f32 { return object_at(object_of(a) * OBJECT_STRIDE).w; }
// Inputs at a point of triangle ti (barycentrics u, v) for material functions outside full shading (alpha, NEE).
-fn mat_in_at(ti: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {
- let a = attrs[ti];
+// `inst`: the instance a mesh's triangle is placed by (as `surface` places it), or NO_INST. (By F_IFUNC, not by
+// F_INST: where no instanced mesh has a function the placement is not compiled in.)
+fn mat_in_at(ti: u32, inst: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {
+ var a = attrs[ti];
+ var v0 = tri_verts[ti * 3u].xyz;
+ var e1 = tri_verts[ti * 3u + 1u].xyz;
+ var e2 = tri_verts[ti * 3u + 2u].xyz;
+ var side = 1.0;
+ if (has(F_IFUNC) && inst != NO_INST) {
+ let r = instance_at(inst);
+ v0 = inst_vec(r, v0) + vec3<f32>(r.m0.w, r.m1.w, r.m2.w);
+ 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));
let w = 1.0 - u - v;
- let p = tri_verts[ti * 3u].xyz + tri_verts[ti * 3u + 1u].xyz * u + tri_verts[ti * 3u + 2u].xyz * v;
- let ng = normalize(cross(tri_verts[ti * 3u + 1u].xyz, tri_verts[ti * 3u + 2u].xyz));
+ let p = v0 + e1 * u + e2 * v;
+ let ng = normalize(cross(e1, e2)) * side;
var n = normalize(a.n0.xyz * w + a.n1.xyz * u + a.n2.xyz * v);
let t = normalize(a.t.xyz - n * dot(n, a.t.xyz) + vec3<f32>(1e-9));
let oi = object_of(a);
@@ -1189,7 +1208,7 @@ fn alpha_pass(ti: u32, inst: u32, u: f32, v: f32, t: f32) -> bool {
alpha *= tex(m.tex0.x, mesh_uv(a, m, u, v), lod).a;
}
if (has(F_FUNC) && m.tex1.w > 0) {
- let i = mat_in_at(ti, u, v, vec3<f32>(0.0, 1.0, 0.0), log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)));
+ let i = mat_in_at(ti, inst, u, v, vec3<f32>(0.0, 1.0, 0.0), log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)));
var b = mat_base(m);
b.opacity = alpha;
alpha = alpha_material_function(m.tex1.w - 1, i, m, b).opacity;
@@ -1212,14 +1231,16 @@ fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
var e1 = tri_verts[i * 3u + 1u].xyz;
var e2 = tri_verts[i * 3u + 2u].xyz;
var a = attrs[i];
+ 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 w = 1.0 - h.u - h.v;
- var ng = normalize(cross(e1, e2));
+ var ng = normalize(cross(e1, e2)) * side;
var n = normalize(a.n0.xyz * w + a.n1.xyz * h.u + a.n2.xyz * h.v);
let mi = bitcast<u32>(a.uv.w);
let m = material_at(mi);
@@ -2096,7 +2117,7 @@ fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32>
if (has(F_FUNC) && m.tex1.w > 0) {
var mb = mat_base(m);
mb.emissive *= pw;
- le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, b1, b2, -l, log2(0.05)), m, mb).emissive;
+ le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, em.inst, b1, b2, -l, log2(0.05)), m, mb).emissive;
}
return le;
}
diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgsl
index 3c47d32..693f0f2 100644
--- a/renderer/shaders/translucent.wgsl
+++ b/renderer/shaders/translucent.wgsl
@@ -69,7 +69,7 @@
}
r.emissive = emission(m, uv, tl) * obj_power(a);
if (has(F_FUNC) && m.tex1.w > 0) {
- r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, b.x, b.y, view, lod), m, r);
+ r = translucent_material_function(m.tex1.w - 1, mat_in_at(ti, NO_INST, b.x, b.y, view, lod), m, r);
}
return r;
}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 75e8820..111adce 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1672,6 +1672,11 @@ pub const F_GRID: u32 = 1 << 25;
/// guided live by the light tiles (pathtrace.wgsl "Light tiles"; the live view's `light_tiles` pass runs for such a
/// scene).
pub const F_LISTS: u32 = 1 << 27;
+/// A material function on an instanced mesh: its inputs outside full shading (pathtrace.wgsl `mat_in_at`) place the
+/// triangle by its instance. Compiled out where no scene has one: the kernel's compiler works the placement out for
+/// 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;
/// 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").
@@ -1735,7 +1740,8 @@ 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_PEMIT for opaque particles, F_PROC for procedural geometry, F_TINT for instance colours, F_IFUNC for a material
+/// function on an instanced mesh.
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(")));
@@ -1744,7 +1750,9 @@ pub fn instance_features(scene: &Scene) -> u32 {
if scene.gpu_instances.is_empty() {
return media | particles;
}
- media | particles | 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 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 }
}
/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
@@ -3645,7 +3653,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_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index afac931..3054a81 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -928,12 +928,13 @@ fn flatten_deforming(sc: &mut scene::Scene) {
}
let first = sc.tris.len() as u32;
for k in m.first..m.first + m.count {
- if let Some(&c) = sc.pool_vcolors.get(k as usize) {
+ let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &sc.pool_attrs[k as usize], sc.pool_vcolors.get(k as usize).copied());
+ if let Some(c) = c {
scene::put_colors(&mut sc.vcolors, sc.tris.len(), Some(vec![c]));
}
- sc.tris.push(inst.tri(&sc.pool_tris[k as usize]));
+ sc.tris.push(t);
sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
- sc.attrs.push(scene::instance_attr(&sc.pool_attrs[k as usize], inst.world, inst.object));
+ sc.attrs.push(a);
}
sc.tri_nodes.push((inst.name.clone(), first, sc.tris.len() as u32));
if let Some(i) = inst.sub {
@@ -950,12 +951,13 @@ fn flatten_instances(sc: &mut scene::Scene) {
let m = sc.meshes[inst.mesh as usize];
let first = sc.tris.len() as u32;
for k in m.first..m.first + m.count {
- if let Some(&c) = sc.pool_vcolors.get(k as usize) {
+ let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &sc.pool_attrs[k as usize], sc.pool_vcolors.get(k as usize).copied());
+ if let Some(c) = c {
scene::put_colors(&mut sc.vcolors, sc.tris.len(), Some(vec![c]));
}
- sc.tris.push(inst.tri(&sc.pool_tris[k as usize]));
+ sc.tris.push(t);
sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
- sc.attrs.push(scene::instance_attr(&sc.pool_attrs[k as usize], inst.world, inst.object));
+ sc.attrs.push(a);
}
// A second range for the node when its glass / function part was flattened at build: node_tris joins them.
sc.tri_nodes.push((inst.name, first, sc.tris.len() as u32));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 43c1f41..c967fca 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1046,7 +1046,7 @@ impl LiveCore {
/// BLASes change. Copies that emit: their emitters in the light list follow (`fill_moved`), a hidden copy's object
/// without power, and the emitters are weighed again when a copy's size or power changed (`emitters_reweigh`).
/// Returns how many objects it updated; Err: why it cannot (software traversal, an object the build
- /// flattened or did not place this way, an instance now mirrored), and the caller rebuilds.
+ /// flattened or did not place this way), and the caller rebuilds.
/// `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
pub(super) fn update_instanced(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> std::result::Result<usize, String> {
use crate::world::Kind;
@@ -1082,9 +1082,6 @@ impl LiveCore {
let slot0 = top.inst_base() + rec0;
for i in 0..cap {
let (wm, hidden) = scene::instance_world(m, t, i);
- if !procedural && !hidden && wm.determinant() < 0.0 {
- return Err("an instance is mirrored".into());
- }
let old = sc.gpu_instances[rec0 + i];
let mut emits = false;
let (mut rec, entry) = if procedural {
@@ -1207,12 +1204,8 @@ impl LiveCore {
}
let (first, verts, attrs, blas) = &mut self.sc.dynamic;
for (j, (node, p, n, uv, tg)) in r.rest_local.iter().enumerate() {
- let w = m * globals[*node];
- let nm = glam::Mat3::from_mat4(w).inverse().transpose();
- let pw = p.map(|v| w.transform_point3(v));
- let nw = n.map(|v| (nm * v).normalize_or_zero());
- let tw = tg.map(|(v, s)| (w.transform_vector3(v).normalize_or_zero(), s));
- let a = scene::tri_attr(pw, nw, *uv, tw, d.mats[j]);
+ let (pw, nw, uvw, tw) = scene::placed_tri(m * globals[*node], p, n, uv, *tg);
+ let a = scene::tri_attr(pw, nw, uvw, tw, d.mats[j]);
let k = d.finals[j] as usize - *first;
let (e1, e2) = (pw[1] - pw[0], pw[2] - pw[0]);
verts[k * 3..k * 3 + 3].copy_from_slice(&[[pw[0].x, pw[0].y, pw[0].z, f32::from_bits(d.flags[j])], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
@@ -1786,8 +1779,8 @@ impl LiveCore {
if !functions.is_empty() {
return Err("a model with material functions (its materials load with a rebuild)".into());
}
- if features & gpu::F_INST == 0 || m.determinant() <= 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
- return Err("a model the build would flatten (mirrored, instancing off, or the scene's first instance)".into());
+ if features & gpu::F_INST == 0 || m.determinant() == 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
+ return Err("a model the build would flatten (no size, instancing off, or the scene's first instance)".into());
}
let mesh = *tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).ok_or("a model not in the scene (its materials and textures load with a rebuild)")?;
let im = meshes[mesh as usize];
@@ -1815,18 +1808,23 @@ impl LiveCore {
if features & gpu::F_INST == 0 {
return Err("the scene's first instanced mesh (kernel feature)".into());
}
- // What the build flattens instead (scene.rs: mirrored, or instancing off).
- if m.determinant() <= 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
- return Err("a mirrored mesh, or instancing off (the build flattens it)".into());
+ // What the build flattens instead (scene.rs: a placement without size, or instancing off).
+ if m.determinant() == 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
+ return Err("a mesh without size, or instancing off (the build flattens it)".into());
}
let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
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);
let class = scene::mesh_class(&gm);
- if class == 2 || (emits && capacity.is_some()) {
- return Err("a glass or function material (an instanced mesh: emitting too)".into());
+ 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());
}
if class == 1 && features & gpu::F_MASKED == 0 {
return Err("the scene's first cutout (kernel feature)".into());
@@ -1987,9 +1985,6 @@ impl LiveCore {
return Err("the scene's first instance colours (kernel feature)".into());
}
let placed: Vec<(glam::Mat4, bool)> = (0..cap).map(|i| scene::instance_world(m, t, i)).collect();
- if placed.iter().any(|(wm, hidden)| !hidden && wm.determinant() < 0.0) {
- return Err("a mirrored instance (the build flattens them)".into());
- }
// (An entry a copy, below: not the one an object has.)
edit.objects.give(object, 1);
let r0 = match edit.records.take(cap) {
@@ -2022,13 +2017,27 @@ impl LiveCore {
tables.objects.resize((o0 + cap) * st, [0.0; 4]);
}
for (i, &(wm, hidden)) in placed.iter().enumerate() {
- let 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: 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 {
+ let first = tables.emitter_tris.len();
+ inst.first_emitter = first as u32;
+ let (a, b) = (im.first as usize, (im.first + im.count) as usize);
+ let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.emitters as usize, &tables.materials, true);
+ for (j, (e, w)) in made.into_iter().enumerate() {
+ new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));
+ tables.emitter_tris.push(e);
+ }
+ 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);
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);
let (lo, hi) = im.placed_bounds(wm);
- let entry = scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i));
+ 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]));
tables.objects[(o0 + i) * st..(o0 + i + 1) * st].copy_from_slice(&entry[..st]);
instances[r0 + i] = inst;
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 3d0eac8..ec93200 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -284,6 +284,13 @@ fn moves_in_place_leave_what_a_build_does() {
("a movable mesh moved", Box::new(move |w| w.set_transform(13, at(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap())),
("a driven mesh moved", Box::new(move |w| assert!(w.place_driven(14, at(-0.2, 0.3, 1.0), glam::Quat::from_rotation_z(-0.4))))),
("an instanced object's copy moved", Box::new(move |w| w.set_instances(15, 2, Some(copies(-0.2)), None, None).unwrap())),
+ (
+ "an instanced object's copy mirrored",
+ Box::new(move |w| {
+ let mirror = glam::Mat4::from_translation(Vec3::new(-0.2, -0.5, 0.4)) * glam::Mat4::from_scale(Vec3::new(-1.0, 1.5, 1.0));
+ w.set_instances(15, 2, Some([mirror.to_cols_array(), glam::Mat4::from_translation(Vec3::new(0.6, 0.6, 0.8)).to_cols_array()].concat()), None, None).unwrap()
+ }),
+ ),
(
"all three moved at once",
Box::new(move |w| {
@@ -490,13 +497,6 @@ fn emitting_copies_changed_in_place_are_lit_as_a_build_lights_them() {
}),
),
];
- // The emitters that weigh something: each one's weight and where it is.
- let weights = |c: &LiveCore| {
- let t = &c.sc.tables;
- let mut v: Vec<(f32, [f32; 3])> = t.emitter_tris.iter().map(|e| (crate::emitter_power(e, &t.materials, &t.objects, t.stride), e.c)).filter(|(p, _)| *p > 0.0).collect();
- v.sort_by(|a, b| a.partial_cmp(b).unwrap());
- v
- };
for (what, edit) in &edits {
let what = format!("{what}, {} a light tree", if tree { "with" } else { "without" });
edit(&mut w);
@@ -510,17 +510,90 @@ fn emitting_copies_changed_in_place_are_lit_as_a_build_lights_them() {
let alone = what.starts_with("the object removed");
assert!(reach(&live) < if alone { 0.3 } else { 10.0 } && (alone || reach(&live) > 0.3), "{what}: the moving subtree reaches {} m", reach(&live));
}
- let mut fresh = open(&w).unwrap();
- let (wl, wf) = (weights(&live), weights(&fresh));
- assert_eq!(wl.len(), wf.len(), "{what}: as many emitters weigh something as in a build");
- for (l, f) in wl.iter().zip(&wf) {
- assert!((l.0 - f.0).abs() <= 1e-5 * f.0 && (Vec3::from(l.1) - Vec3::from(f.1)).length() <= 1e-4, "{what}: an emitter weighs {l:?}, a build's {f:?}");
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ }
+ }
+}
+
+/// A view that took edits in place against one built from the edited world: the emitters that weigh something are as
+/// many, each weighs what a build's does where a build's is, the kernel's total weight is a build's, and so is the
+/// picture after 64 frames.
+fn lit_as_a_build(what: &str, live: &mut LiveCore, fresh: &mut LiveCore) {
+ let weights = |c: &LiveCore| {
+ let t = &c.sc.tables;
+ let mut v: Vec<(f32, [f32; 3])> = t.emitter_tris.iter().map(|e| (crate::emitter_power(e, &t.materials, &t.objects, t.stride), e.c)).filter(|(p, _)| *p > 0.0).collect();
+ v.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ v
+ };
+ let (wl, wf) = (weights(live), weights(fresh));
+ assert_eq!(wl.len(), wf.len(), "{what}: as many emitters weigh something as in a build");
+ for (l, f) in wl.iter().zip(&wf) {
+ assert!((l.0 - f.0).abs() <= 1e-5 * f.0 && (Vec3::from(l.1) - Vec3::from(f.1)).length() <= 1e-4, "{what}: an emitter weighs {l:?}, a build's {f:?}");
+ }
+ let (tl, tf) = (live.sc.base.misc[1], fresh.sc.base.misc[1]);
+ assert!((tl - tf).abs() <= 1e-4 * tf.abs(), "{what}: the kernel's total weight {tl}, a build's {tf}");
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+}
+
+/// An instanced object whose copies emit, added in place, is lit as a build lights it; so it is after its copies
+/// changed in place (one moved, one more shown) and after it was removed. With and without a light tree. After each:
+/// no rebuild, the light list is its triangles, the weights and the picture are a build's.
+#[test]
+fn an_emitting_instanced_object_added_in_place_is_lit_as_a_build_lights_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 tree in [false, true] {
+ let mut w = world();
+ // (The sun and the lamp away: the copies will light the scene. A mesh with its own BLAS: the scene has
+ // instances, so an instanced mesh is added in place.)
+ w.set_visible(20, false).unwrap();
+ w.set_visible(12, false).unwrap();
+ w.set_object(14, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(14, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ if tree {
+ strip(&mut w);
+ }
+ 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();
+ picture(&mut live, 4);
+ let at = |x: f32, y: f32, z: f32, s: f32| glam::Mat4::from_scale_rotation_translation(Vec3::splat(s), glam::Quat::from_rotation_y(0.3), Vec3::new(x, y, z)).to_cols_array();
+ let set = |w: &mut World, count: u32, m: [[f32; 16]; 3]| w.set_instances(15, count, Some(m.concat()), None, None).unwrap();
+ let (b, c) = (at(0.5, 0.5, 1.0, 0.4), at(0.0, 0.0, 1.4, 0.4));
+ type Edit = (&'static str, Box<dyn Fn(&mut World)>);
+ let edits: Vec<Edit> = vec![
+ (
+ "added",
+ Box::new(move |w| {
+ w.set_object(15, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![5], capacity: 3 }, true, false).unwrap();
+ set(w, 2, [at(-0.6, -0.4, 0.8, 0.4), b, c]);
+ }),
+ ),
+ ("a copy moved, a third shown", Box::new(move |w| set(w, 3, [at(-0.2, -0.5, 1.1, 0.8), b, c]))),
+ (
+ "removed",
+ Box::new(move |w| {
+ w.remove(15);
+ }),
+ ),
+ ];
+ 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`.)
+ let covers = |c: &LiveCore| c.sc.tables.fixed_mats.contains(&c.sc.tables.retained.materials[&5]);
+ let before = covers(&live);
+ 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");
+ if live.sc.tables.emitter_tris.iter().any(|e| e.area > 0.0) {
+ list_is_its_triangles(&what, &live);
}
- let (tl, tf) = (live.sc.base.misc[1], fresh.sc.base.misc[1]);
- assert!((tl - tf).abs() <= 1e-4 * tf.abs(), "{what}: the kernel's total weight {tl}, a build's {tf}");
- forget(&mut live);
- let (a, b) = (picture(&mut 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));
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
}
}
}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index eda7657..837d37f 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -59,7 +59,7 @@ pub struct InstMesh {
pub count: u32,
/// The first `opaque` pool triangles are opaque (BLAS geometry 0), the rest cutout (geometry 1, any-hit test).
pub opaque: u32,
- /// Triangles each placement flattens instead (glass, material functions), in the build's rest arrays.
+ /// Triangles each placement flattens instead (glass), in the build's rest arrays.
pub rest_first: u32,
pub rest_count: u32,
/// Model-space bounds (object bounds of its instances, picking).
@@ -130,12 +130,45 @@ impl Instance {
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];
- GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, 0.0), 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)] }
+ 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)] }
}
/// 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] {
t.map(|v| self.world.transform_point3a(v))
}
+ /// A triangle of its mesh (vertices `t`, attributes `a`, vertex colours `c`) as flattening has it: in world space
+ /// (`tri`, `instance_attr`), and under a mirroring instance with its second and third vertex changed places, so
+ /// that it faces as the mesh's does (as `append_arrays` flattens a mirrored placement).
+ pub fn flat(&self, t: &[Vec3A; 3], a: &GpuTriAttr, c: Option<[u32; 3]>) -> ([Vec3A; 3], GpuTriAttr, Option<[u32; 3]>) {
+ let (w, b) = (self.tri(t), instance_attr(a, self.world, self.object));
+ if !mirrors(self.world) {
+ return (w, b, c);
+ }
+ // (The UVs are packed along the normals: uv0 in n0.w n1.w, uv1 in n2.w uv.x, uv2 in uv.y uv.z.)
+ let swapped = GpuTriAttr { n1: [b.n2[0], b.n2[1], b.n2[2], b.n1[3]], n2: [b.n1[0], b.n1[1], b.n1[2], b.uv[1]], uv: [b.uv[2], b.n2[3], b.uv[0], b.uv[3]], ..b };
+ ([w[0], w[2], w[1]], swapped, c.map(|c| [c[0], c[2], c[1]]))
+ }
+}
+
+/// A triangle in a node's own space (vertices, normals, UVs, an authored tangent) placed by `w` as the build flattens
+/// it: under a mirroring `w` the second and third vertex change places, so that it faces as its mesh does, and an
+/// authored tangent's frame changes hand (`Instance::flat` does the same with a mesh's triangle; a tangent worked out
+/// from the placed triangle has the right hand by itself).
+#[allow(clippy::type_complexity)]
+pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent: Option<(Vec3, f32)>) -> ([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>) {
+ let nm = Mat3::from_mat4(w).inverse().transpose();
+ let (k, hand) = if mirrors(w) { ([0, 2, 1], -1.0) } else { ([0, 1, 2], 1.0) };
+ (k.map(|i| w.transform_point3(p[i])), k.map(|i| (nm * n[i]).normalize_or_zero()), k.map(|i| uv[i]), tangent.map(|(v, s)| (w.transform_vector3(v).normalize_or_zero(), s * hand)))
+}
+
+/// Bit of an instance record's n1.w, beside the units' flags there (units.rs `UNIT_*`): the instance mirrors its mesh
+/// (the kernel's `inst_sign`).
+pub const INST_MIRRORED: u32 = 4;
+
+/// Whether a placement mirrors what it places (a negative determinant).
+pub fn mirrors(w: Mat4) -> bool {
+ glam::Mat3::from_mat4(w).determinant() < 0.0
}
/// Procedural geometry placed in the scene (`Kind::Procedural`): an instance of its own AABB BLAS (hardware RT), its
@@ -349,7 +382,7 @@ pub fn lod_offset(w: Mat4) -> f32 {
}
/// Model-space shading attributes of a pool triangle placed by `w` (normals by the inverse transpose, tangent by the
-/// matrix, texture-LOD constant by the scale), object `object`.
+/// matrix, its frame's hand changed by a mirroring one, texture-LOD constant by the scale), object `object`.
pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr {
let m3 = glam::Mat3::from_mat4(w);
let nm = m3.inverse().transpose();
@@ -358,7 +391,8 @@ pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr {
[r.x, r.y, r.z, v[3]]
};
let t = (m3 * Vec3::new(a.t[0], a.t[1], a.t[2])).normalize_or_zero();
- GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: [t.x, t.y, t.z, a.t[3]], x: [a.x[0] + lod_offset(w), f32::from_bits(object), a.x[2], a.x[3]] }
+ let hand = if mirrors(w) { -a.t[3] } else { a.t[3] };
+ GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: [t.x, t.y, t.z, hand], x: [a.x[0] + lod_offset(w), f32::from_bits(object), a.x[2], a.x[3]] }
}
#[repr(C)]
@@ -721,8 +755,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 / function
-/// triangles are flattened (shadow rays, a function's inputs), and what `flatten_coincident` takes with them: `rest`,
+/// 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`.
#[derive(Clone, Default)]
pub struct RigidModel {
@@ -1270,14 +1304,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, non-emissive materials without functions, not mirrored. THREERT_INSTANCING=0 flattens everything.
+ // per node, no glass. 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, functions).
+ // Model-space triangles of instanced meshes that each placement flattens (glass).
let mut rest_tris: Vec<[Vec3A; 3]> = vec![];
let mut rest_attrs: Vec<GpuTriAttr> = vec![];
let mut meshes: Vec<InstMesh> = vec![];
@@ -1290,7 +1324,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mut count: HashMap<PoseKey, usize> = HashMap::new();
for id in &order {
let Kind::Model { uri, nodes, animation: Some(a), functions } = &w.objects[id].kind else { continue };
- if !w.shown(*id) || worlds[id].determinant() <= 0.0 {
+ if !w.shown(*id) || worlds[id].determinant() == 0.0 {
continue;
}
// (Rigid models whose nodes move are `RigidModel`s.)
@@ -1320,12 +1354,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let shown = w.shown(*id);
let flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
match &n.kind {
- 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))) => {
+ 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 and
- // function materials are flattened (as a model's would be), so they are never instanced. A material
- // that only 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. 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`).
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]);
@@ -1362,7 +1396,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
put_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, false, None)));
- // (A driven mesh that cannot be an instance (glass, a material function): dynamic triangles,
+ // (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 {
@@ -1373,9 +1407,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// Copies of one geometry: one shared mesh (one BLAS), an instance and an object entry per copy, the
// 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). Glass and function
- // materials and mirrored copies are flattened instead, each copy its own triangles, as `own_blas`
- // meshes are; changing their instances rebuilds.
+ // (`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.
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();
@@ -1398,8 +1432,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let class = mesh_class(&materials[mat as usize]);
let emits = emits_only(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
- let mirrored = placed.iter().any(|(wm, hidden)| !hidden && wm.determinant() < 0.0);
- if instancing && class < 2 && !mirrored {
+ if instancing && class < 2 {
let mesh = match inst_mesh_of.get(&(*geometry, mat)) {
Some(&k) => Some(k),
None => {
@@ -1520,14 +1553,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let a = animation.as_ref().unwrap();
let moving = glb.moving_nodes(&a.clip)?;
let globals = glb.node_globals(Some(a))?;
- let static_tris = glb.node_triangles(m, Some(a), &|ni| !moving[ni], false, &|_| false)?;
+ let static_tris = glb.node_triangles(m, Some(a), &|ni| !moving[ni], false)?;
let base_flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
for (_, t) in &static_tris {
let mat = resolve(t.material.and_then(|i| doc.materials().nth(i)))?.0;
push_tri(&mut tris, &mut tri_flags, &mut attrs, t.p, t.n, t.uv, t.tangent, mat, base_flags);
}
- let mirrored = |ni: usize| (m * globals[ni]).determinant() < 0.0;
- let local = glb.node_triangles(Mat4::IDENTITY, None, &|ni| moving[ni], true, &mirrored)?;
+ let local = glb.node_triangles(Mat4::IDENTITY, None, &|ni| moving[ni], true)?;
// Group by node (the order within a node is the file's).
let mut by_node: Vec<(usize, Vec<usize>)> = vec![];
for (k, (ni, _)) in local.iter().enumerate() {
@@ -1584,13 +1616,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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 });
}
- let nm = Mat3::from_mat4(w_n).inverse().transpose();
for &(k, mat) in &classed[2] {
let t = &local[k].1;
- let p = t.p.map(|v| w_n.transform_point3(v));
- let nn = t.n.map(|v| (nm * v).normalize_or_zero());
- let tg = t.tangent.map(|(v, s)| (w_n.transform_vector3(v).normalize_or_zero(), s));
- push_tri(&mut tris, &mut tri_flags, &mut attrs, p, nn, t.uv, tg, mat, base_flags | TRI_DYNAMIC);
+ 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);
rigid.rest.mats.push(mat);
rigid.rest_local.push((*ni, t.p, t.n, t.uv, t.tangent));
}
@@ -1632,7 +1661,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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));
}
- // Triangles flattened per placement (glass, emissive, functions): each model skinned alone.
+ // Triangles flattened per placement (glass, emissive): each model skinned alone.
let g = (classed[2].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));
@@ -1673,15 +1702,15 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
}
- if instancing && !posed && m.determinant() > 0.0 {
+ if instancing && !posed && m.determinant() != 0.0 {
let key = mesh_key.clone();
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`); glass and function triangles are
- // flattened per placement (shadow-ray pass-through, a function's world-space inputs).
+ // emitters in the light list: `InstMesh::emitters`); glass triangles are flattened per
+ // placement (shadow-ray pass-through).
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), None)?;
let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
let mut emitting: std::collections::HashSet<u32> = Default::default();
@@ -1739,9 +1768,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let inst = Instance { mesh, world: m, object: oi, cast_shadow: 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 {
- tris.push(inst.tri(&rest_tris[k as usize]));
+ let (t, a, _) = inst.flat(&rest_tris[k as usize], &rest_attrs[k as usize], None);
+ tris.push(t);
tri_flags.push(flags);
- attrs.push(instance_attr(&rest_attrs[k as usize], m, oi));
+ attrs.push(a);
}
if tris.len() as u32 > first {
tri_nodes.push((n.name.clone(), first, tris.len() as u32));
@@ -2183,10 +2213,10 @@ fn pool_emitters(classed: &[Vec<(usize, u32)>; 3], emitting: &std::collections::
}
/// Instancing class of a GPU material: 0 opaque, 1 cutout (any-hit), 2 flattened per placement (glass: shadow rays pass;
-/// material functions; emissive, where the light list does not follow the mesh: one that deforms. Elsewhere
-/// `mesh_class`).
+/// 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`).
pub fn material_class(g: &GpuMaterial) -> u32 {
- let flat = g.layer[0] > 0.0 || g.tex1[3] != 0 || g.emissive[..3].iter().any(|e| *e > 0.0);
+ let flat = g.layer[0] > 0.0 || g.emissive[..3].iter().any(|e| *e > 0.0);
if flat {
2
} else if g.uv2[3] > 0.0 {
@@ -2238,10 +2268,10 @@ pub fn own_mesh_tris(g: &world::Geometry, mat: u32) -> (Vec<[Vec3A; 3]>, Vec<Gpu
(tris, attrs)
}
-/// A material that only emits (no glass, no material function): an `own_blas` mesh of it is a mesh as any other, its
-/// instances' emitters in the light list (`InstMesh::emitters`).
+/// 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.tex1[3] == 0 && g.emissive[..3].iter().any(|e| *e > 0.0)
+ g.layer[0] <= 0.0 && 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
@@ -2445,31 +2475,43 @@ mod instance_tests {
assert_eq!(texture_image(&tex(0), assets).unwrap().0, kb);
}
- /// An instance's placed triangle and attributes equal flattening the same triangle at the instance transform.
+ /// An instance's placed triangle and attributes equal flattening the same triangle at the instance transform: as
+ /// the flattening path has them (`Instance::flat`) against the triangle built in world space as `append_arrays`
+ /// builds it, under a transform that keeps the hand and under one that mirrors (the second and third vertex
+ /// change places, the tangent frame changes hand), with distinct normals, UVs and vertex colours a vertex.
#[test]
fn instance_matches_flattening() {
let p = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.5, 0.2)];
- let n = [Vec3::new(0.0, -0.37, 0.93).normalize(); 3];
- let uv = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)];
- let w = Mat4::from_scale_rotation_translation(Vec3::splat(2.0), glam::Quat::from_rotation_y(0.7) * glam::Quat::from_rotation_x(-0.3), Vec3::new(5.0, 1.0, -3.0));
+ let n = [Vec3::new(0.0, -0.37, 0.93).normalize(), Vec3::new(0.1, -0.3, 0.9).normalize(), Vec3::new(-0.2, -0.4, 0.8).normalize()];
+ let uv = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.25), Vec2::new(0.5, 1.0)];
+ let colors = [1, 2, 3];
+ let keeps = Mat4::from_scale_rotation_translation(Vec3::splat(2.0), glam::Quat::from_rotation_y(0.7) * glam::Quat::from_rotation_x(-0.3), Vec3::new(5.0, 1.0, -3.0));
let local = tri_attr(p, n, uv, None, 7);
- let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, first_emitter: 0 };
- let placed = inst.tri(&[p[0].into(), p[1].into(), p[2].into()]);
- let wp = p.map(|v| w.transform_point3(v));
- let flat = tri_attr(wp, n.map(|v| (glam::Mat3::from_mat4(w).inverse().transpose() * v).normalize()), uv, None, 7);
- let got = instance_attr(&local, w, 3);
- for k in 0..3 {
- assert!((Vec3::from(placed[k]) - wp[k]).length() < 1e-5);
- }
- for (a, b) in [(got.n0, flat.n0), (got.n1, flat.n1), (got.n2, flat.n2), (got.t, flat.t)] {
- assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5, "{a:?} vs {b:?}");
- assert_eq!(a[3], b[3]);
+ 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");
+ let (placed, got, got_colors) = inst.flat(&[p[0].into(), p[1].into(), p[2].into()], &local, Some(colors));
+ // The world-space triangle: its vertices in the order the build flattens a placement in.
+ let order = if mirrored { [0, 2, 1] } else { [0, 1, 2] };
+ let nm = glam::Mat3::from_mat4(w).inverse().transpose();
+ let wp = order.map(|k| w.transform_point3(p[k]));
+ let flat = tri_attr(wp, order.map(|k| (nm * n[k]).normalize()), order.map(|k| uv[k]), None, 7);
+ for k in 0..3 {
+ assert!((Vec3::from(placed[k]) - wp[k]).length() < 1e-5, "mirrored {mirrored}: vertex {k}");
+ }
+ assert!((placed[1] - placed[0]).cross(placed[2] - placed[0]).dot(Vec3A::from(nm * n[0])) > 0.0, "mirrored {mirrored}: it faces as its normals do");
+ for (a, b) in [(got.n0, flat.n0), (got.n1, flat.n1), (got.n2, flat.n2), (got.t, flat.t)] {
+ assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5, "mirrored {mirrored}: {a:?} vs {b:?}");
+ assert_eq!(a[3], b[3], "mirrored {mirrored}: the UV packed there, the tangent frame's hand");
+ }
+ assert_eq!(got.uv, flat.uv, "mirrored {mirrored}");
+ assert_eq!(got_colors, Some(order.map(|k| colors[k])), "mirrored {mirrored}: the vertex colours follow their vertices");
+ // Uniform scale 2: texel density per metre halves (LOD constant - 1), exactly as the world-space triangle.
+ assert!((got.x[0] - flat.x[0]).abs() < 1e-5);
+ assert!((lod_offset(w) + 1.0).abs() < 1e-5);
+ assert_eq!(got.x[1].to_bits(), 3);
}
- // Uniform scale 2: texel density per metre halves (LOD constant - 1), exactly as the world-space triangle.
- assert!((got.x[0] - flat.x[0]).abs() < 1e-5);
- assert!((lod_offset(w) + 1.0).abs() < 1e-5);
- assert_eq!(got.x[1].to_bits(), 3);
- assert_eq!(got.uv, flat.uv);
}
/// Software traversal flattens instances: a cutout material's triangles keep TRI_MASKED (any-hit alpha test),
@@ -2491,7 +2533,7 @@ mod instance_tests {
/// 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.
/// 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; mirrored copies flatten every drawn copy.
+ /// past the count and where a matrix scales to 0; a copy may mirror the mesh.
#[test]
fn instanced_objects_share_one_mesh() {
let mut w = World::default();
@@ -2513,7 +2555,8 @@ mod instance_tests {
m[0] = -1.0;
w.set_instances(2, 3, Some(m), None, None).unwrap();
let sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();
- assert_eq!((sc.instances.len(), sc.tris.len(), sc.tri_instances.iter().map(|r| r.2).collect::<Vec<_>>()), (0, 2, vec![0, 1]), "mirrored: the drawn copies flattened");
+ 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");
}
/// An instanced object whose material only emits is placed as any other: one shared mesh, which has the emitters,
@@ -2545,6 +2588,42 @@ mod instance_tests {
assert!(power(1) > 0.0 && crate::switchable_power(&e[2], &sc.materials, &sc.objects, st) > 0.0, "a hidden copy's emitter is one the light tree would have");
}
+ /// A model placed mirrored (a negative scale) is an instance as one placed straight is, of the same mesh: a model
+ /// that stays and a rigid model's moving node (tests/render/data/panel-decal.glb). The meshes do not depend on
+ /// the placement's hand; the instances' records say that they mirror; what the build flattens of them keeps
+ /// facing as its normals do.
+ #[test]
+ fn a_mirrored_model_is_an_instance_of_the_same_mesh() {
+ let scene = |x: f32| {
+ 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() });
+ let model = |animation| Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation, functions: vec![] };
+ w.set_object(1, "still".into(), None, model(None), true, false).unwrap();
+ w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true })), true, false).unwrap();
+ for id in [1, 2] {
+ w.set_transform(id, Vec3::new(id as f32, 0.0, 0.0), glam::Quat::from_rotation_y(0.4), Vec3::new(x, 1.0, 1.0)).unwrap();
+ }
+ 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<_>>();
+ 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");
+ // 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")] {
+ assert!(!sc.tris.is_empty());
+ for (t, a) in sc.tris.iter().zip(&sc.attrs) {
+ assert!((t[1] - t[0]).cross(t[2] - t[0]).dot(Vec3A::new(a.n0[0], a.n0[1], a.n0[2])) > 0.0, "{what}: a flattened triangle faces away from its normals");
+ }
+ }
+ }
+
/// 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/skin.rs b/renderer/src/skin.rs
index 0785a26..28d81fc 100644
--- a/renderer/src/skin.rs
+++ b/renderer/src/skin.rs
@@ -227,8 +227,9 @@ impl Model {
/// A rigid model's triangles of the nodes `keep` admits, with each one's node: in world space for `pose`
/// (`world` x the node's global transform), or in the node's own space (`local`: the caller places them per node).
/// Same order as `triangles`. Mirrored placements keep the winding front-facing in world space, as `triangles`
- /// does; in local space `mirrored(node)` says which nodes will be placed mirrored.
- pub fn node_triangles(&self, world: Mat4, pose: Option<&desc::Animation>, keep: &dyn Fn(usize) -> bool, local: bool, mirrored: &dyn Fn(usize) -> bool) -> Result<Vec<(usize, ModelTri)>> {
+ /// does; in local space a node's triangles are as its mesh has them (an instance that places it mirrored says so
+ /// itself: `scene::INST_MIRRORED`).
+ pub fn node_triangles(&self, world: Mat4, pose: Option<&desc::Animation>, keep: &dyn Fn(usize) -> bool, local: bool) -> Result<Vec<(usize, ModelTri)>> {
let globals = self.globals(pose)?;
let mut out = vec![];
for p in self.prims.iter().filter(|p| keep(p.node)) {
@@ -236,7 +237,8 @@ impl Model {
let nm = Mat3::from_mat4(m).inverse().transpose();
let pos: Vec<Vec3> = p.positions.iter().map(|v| m.transform_point3(*v)).collect();
let nrm: Option<Vec<Vec3>> = p.normals.as_ref().map(|n| n.iter().map(|v| (nm * *v).normalize_or_zero()).collect());
- let flip = if local { mirrored(p.node) } else { m.determinant() < 0.0 };
+ // (A mirroring placement: the winding stays front-facing, and an authored tangent's frame changes hand.)
+ let flip = !local && m.determinant() < 0.0;
for t in p.indices.chunks_exact(3) {
let (a, b, c) = if flip { (t[0], t[2], t[1]) } else { (t[0], t[1], t[2]) };
let (a, b, c) = (a as usize, b as usize, c as usize);
@@ -245,7 +247,7 @@ impl Model {
let n = nrm.as_ref().map(|n| [n[a], n[b], n[c]]).unwrap_or([gn; 3]);
let tangent = p.tangents.as_ref().map(|tv| {
let tt = tv[a];
- (m.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), tt[3])
+ (m.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), if flip { -tt[3] } else { tt[3] })
});
out.push((p.node, ModelTri { p: tp, n, uv: [p.uvs[a], p.uvs[b], p.uvs[c]], tangent, material: p.material }));
}
@@ -310,7 +312,7 @@ impl Model {
let n = nrm.as_ref().map(|n| [n[a], n[b], n[c]]).unwrap_or([gn; 3]);
let tangent = p.tangents.as_ref().map(|tv| {
let tt = tv[a];
- (m.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), tt[3])
+ (m.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), if mirrored { -tt[3] } else { tt[3] })
});
out.push(ModelTri { p: tp, n, uv: [p.uvs[a], p.uvs[b], p.uvs[c]], tangent, material: p.material });
}
@@ -375,11 +377,11 @@ mod tests {
assert!((g[1].transform_point3(Vec3::ZERO) - Vec3::new(1.0, 1.0, 0.0)).length() < 1e-6);
// Static part in world space (the object at x = 10), the moving part in its node's space.
let world = Mat4::from_translation(Vec3::new(10.0, 0.0, 0.0));
- let stat = m.node_triangles(world, Some(&pose), &|n| n == 2, false, &|_| false).unwrap();
+ let stat = m.node_triangles(world, Some(&pose), &|n| n == 2, false).unwrap();
assert_eq!(stat.len(), 1);
assert_eq!(stat[0].0, 2);
assert!((stat[0].1.p[1] - Vec3::new(11.0, 0.0, 5.0)).length() < 1e-6);
- let local = m.node_triangles(Mat4::IDENTITY, None, &|n| n != 2, true, &|_| false).unwrap();
+ let local = m.node_triangles(Mat4::IDENTITY, None, &|n| n != 2, true).unwrap();
assert_eq!(local.len(), 1);
assert_eq!(local[0].0, 1);
assert_eq!(local[0].1.p, [Vec3::ZERO, Vec3::X, Vec3::Y]);
@@ -387,9 +389,23 @@ mod tests {
let posed = m.triangles(world, None, Some(&pose)).unwrap();
let w = world * g[1];
assert!(posed.iter().any(|t| (0..3).all(|k| (t.p[k] - w.transform_point3(local[0].1.p[k])).length() < 1e-5)));
- // A node placed mirrored keeps its winding front-facing once placed.
- let flipped = m.node_triangles(Mat4::IDENTITY, None, &|n| n == 1, true, &|_| true).unwrap();
- assert_eq!(flipped[0].1.p, [Vec3::ZERO, Vec3::Y, Vec3::X]);
+ }
+
+ /// An authored tangent's frame changes hand where a placement mirrors (the winding is swapped there too); in a
+ /// node's own space it is as authored (the instance that places the node says whether it mirrors).
+ #[test]
+ fn a_mirrored_placement_changes_an_authored_tangents_hand() {
+ let mut m = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap();
+ for p in &mut m.prims {
+ p.tangents = Some(vec![[1.0, 0.0, 0.0, 1.0]; p.positions.len()]);
+ }
+ let hand = |t: &ModelTri| t.tangent.unwrap().1;
+ let straight = Mat4::from_translation(Vec3::new(10.0, 0.0, 0.0));
+ let mirrored = straight * Mat4::from_scale(Vec3::new(-1.0, 1.0, 1.0));
+ assert!(m.triangles(straight, None, None).unwrap().iter().all(|t| hand(t) == 1.0));
+ assert!(m.triangles(mirrored, None, None).unwrap().iter().all(|t| hand(t) == -1.0));
+ assert!(m.node_triangles(mirrored, None, &|_| true, false).unwrap().iter().all(|(_, t)| hand(t) == -1.0));
+ assert!(m.node_triangles(Mat4::IDENTITY, None, &|_| true, true).unwrap().iter().all(|(_, t)| hand(t) == 1.0));
}
fn ch(interpolation: gltf::animation::Interpolation, path: Path, times: Vec<f32>, values: Vec<[f32; 4]>) -> Channel {
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 523ef60..1df8bf5 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -146,6 +146,11 @@ impl Tables {
if !self.can_emit(mi, &gm) {
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) {
+ return Ok(None);
+ }
self.materials[mi as usize] = gm;
d.materials = true;
}
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index 64be479..ef71d51 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -304,7 +304,8 @@ pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {
/// aside, which no comparison in the walk sees). (The third word is every instance's: its first emitter.)
pub fn unit_record(mut r: GpuInstance, root: u32, cast_shadow: bool) -> GpuInstance {
r.n[0][3] = f32::from_bits(root);
- r.n[1][3] = f32::from_bits(if cast_shadow { UNIT_SHADOW } else { 0 } | if translation_alone(&r) { UNIT_SHIFTED } else { 0 });
+ // (Beside the record's own bit there: `scene::INST_MIRRORED`.)
+ r.n[1][3] = f32::from_bits(r.n[1][3].to_bits() & crate::scene::INST_MIRRORED | if cast_shadow { UNIT_SHADOW } else { 0 } | if translation_alone(&r) { UNIT_SHIFTED } else { 0 });
r
}
diff --git a/tests/render/geometry-emitter-instanced-added-live.ts b/tests/render/geometry-emitter-instanced-added-live.ts
new file mode 100644
index 0000000..f9541d4
--- /dev/null
+++ b/tests/render/geometry-emitter-instanced-added-live.ts
@@ -0,0 +1,45 @@
+// An emitting instanced mesh added in place (live/edits.rs `edit_geometry`; ROADMAP § 6 step 3): after a few frames
+// the frame script adds the panel of geometry/emitter-instanced (four quads of 1 nit tiling 8 x 8 m, a fifth scaled
+// to 0, a sixth past `count`), 1 m above a Lambert 0.5 floor. Each copy's emitters come into the light list in
+// place, no rebuild, and the floor below the centre reads the same analytic value. The material is in the scene
+// from the start (a speck far away): a new material rebuilds.
+import { InstancedMesh, Matrix4, Mesh, PlaneGeometry } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { E, glow, tile } from "./geometry-emitter-instanced.ts";
+
+export const test: TestMeta = {
+ id: "geometry/emitter-instanced-added-live", features: ["emitters", "instancing", "instanced-mesh", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ live: 90,
+ note: "an InstancedMesh of four emitting quads (1 nit) added in place, 1 m above a Lambert 0.5 floor",
+};
+
+let elapsed = 0;
+let edited = false;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ edited = false;
+ const scene = sceneWithSky(0);
+ const speck = new Mesh(new PlaneGeometry(0.01, 0.01), glow());
+ speck.name = "speck";
+ speck.dynamicGeometry = true;
+ speck.position.set(900, -50, 0);
+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), speck]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (edited || elapsed <= 3 / 60) return;
+ edited = true;
+ const panel = new InstancedMesh(new PlaneGeometry(4, 4), (f.scene.getObjectByName("speck") as Mesh).material, 6);
+ panel.name = "panel";
+ for (let i = 0; i < 4; i++) panel.setMatrixAt(i, tile(i));
+ panel.setMatrixAt(4, new Matrix4().makeScale(0, 0, 0));
+ panel.setMatrixAt(5, new Matrix4().makeTranslation(0, 0.5, 0));
+ panel.count = 5;
+ f.scene.add(panel);
+ },
+ handlers: {},
+});
diff --git a/tests/render/material-function-alpha-instance.ts b/tests/render/material-function-alpha-instance.ts
new file mode 100644
index 0000000..dbf589d
--- /dev/null
+++ b/tests/render/material-function-alpha-instance.ts
@@ -0,0 +1,33 @@
+// A cutout whose alpha is a material function's, on a mesh of its own: the alpha test of a candidate hit evaluates
+// the function at the point as the instance places it (pathtrace.wgsl `alpha_pass`, `mat_in_at`). A cover (Lambert
+// 0.2) 100 m from the origin hides the centre of a plane (Lambert 0.5); its function keeps it where the world x is
+// over 50 and cuts it elsewhere (in the mesh's own space every point has |x| < 1). Under a uniform sky of 1 nit the
+// centre reads the cover, 0.2; cut away it would read the plane.
+import { MaterialFunction, Mesh, PlaneGeometry } from "@threert/scene";
+import { CENTER, camera, lambert, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "material/function-alpha-instance", features: ["material-function", "cutout", "instancing"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 0.2, tolerance: 0.02 },
+ note: "a cover kept by its function's alpha where world x > 50, seen straight on under a 1 nit sky: 0.2",
+};
+
+const FAR_KEPT = new MaterialFunction("far_kept", {
+ params: {},
+ code: `
+ o.opacity = select(0.0, 1.0, i.wp.x > 50.0);`,
+});
+
+export default () => {
+ const scene = sceneWithSky(1);
+ const back = new Mesh(new PlaneGeometry(4, 4), lambert(0.5, "plane"));
+ back.position.x = 100;
+ const material = lambert(0.2, "cover");
+ material.alphaTest = 0.5;
+ material.shader = FAR_KEPT.with({});
+ const cover = new Mesh(new PlaneGeometry(1.5, 1.5), material);
+ cover.name = "cover";
+ cover.dynamicGeometry = true;
+ cover.position.set(100, 0, 1);
+ return result(scene, camera(scene, [100, 0, 6], [100, 0, 0]), [back, cover]);
+};
diff --git a/tests/render/material-function-emitter-instance.ts b/tests/render/material-function-emitter-instance.ts
new file mode 100644
index 0000000..024d7ff
--- /dev/null
+++ b/tests/render/material-function-emitter-instance.ts
@@ -0,0 +1,38 @@
+// A material function sees a mesh's triangle as its instance places it outside full shading too: light sampling
+// evaluates an emitter's function at the point it drew (pathtrace.wgsl `mat_in_at`). An 8 x 8 m panel of a mesh of
+// its own, 100 m from the origin, 1 m above a Lambert 0.5 floor; its function emits 1 nit where the world x is over
+// 50 and nothing elsewhere (in the mesh's own space every point has |x| <= 4). As geometry/emitter-instance: the
+// floor below the centre reads 0.5 / pi x 2.989 only when light sampling and the BSDF rays see the same emission.
+import { Color, MaterialFunction, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const corner = (x: number, y: number) => (x / Math.sqrt(1 + x * x)) * Math.atan(y / Math.sqrt(1 + x * x)) + (y / Math.sqrt(1 + y * y)) * Math.atan(x / Math.sqrt(1 + y * y));
+const E = 4 * (1 / 2) * corner(4, 4);
+
+export const test: TestMeta = {
+ id: "material/function-emitter-instance", features: ["material-function", "emitters", "instancing"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ spp: 256,
+ note: "camera under the panel at (103, 0.8, 0) looking at the floor point below its centre",
+};
+
+const FAR_GLOW = new MaterialFunction("far_glow", {
+ params: {},
+ code: `
+ o.base = vec3<f32>(0.0);
+ o.emissive = vec3<f32>(select(0.0, 1.0, i.wp.x > 50.0));`,
+});
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const glow = new MeshStandardMaterial({ name: "glow", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 1, roughness: 1 });
+ glow.shader = FAR_GLOW.with({});
+ const panel = new Mesh(new PlaneGeometry(8, 8), glow);
+ panel.name = "panel";
+ panel.dynamicGeometry = true;
+ panel.rotation.x = Math.PI / 2;
+ panel.position.set(100, 1, 0);
+ const floor = plane(40, lambert(0.5), "floor");
+ floor.position.x = 100;
+ return result(scene, camera(scene, [103, 0.8, 0], [100, 0, 0]), [floor, panel]);
+};
diff --git a/tests/render/material-function-emitter-mirrored.ts b/tests/render/material-function-emitter-mirrored.ts
new file mode 100644
index 0000000..5e6af84
--- /dev/null
+++ b/tests/render/material-function-emitter-mirrored.ts
@@ -0,0 +1,36 @@
+// material/function-emitter-instance with the panel placed mirrored (a negative scale): light sampling gives the
+// emitter's function the geometric normal on the mesh's outer side, as the placed mesh has it (pathtrace.wgsl
+// `mat_in_at`, `inst_sign`). The function emits 1 nit where that normal points down, toward the floor, and nothing
+// where it points up; the floor below the centre reads 0.5 / pi x 2.989.
+import { Color, MaterialFunction, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const corner = (x: number, y: number) => (x / Math.sqrt(1 + x * x)) * Math.atan(y / Math.sqrt(1 + x * x)) + (y / Math.sqrt(1 + y * y)) * Math.atan(x / Math.sqrt(1 + y * y));
+const E = 4 * (1 / 2) * corner(4, 4);
+
+export const test: TestMeta = {
+ id: "material/function-emitter-mirrored", features: ["material-function", "emitters", "instancing", "mirrored"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ spp: 256,
+ note: "camera under the mirrored panel at (3, 0.8, 0) looking at the floor point below its centre",
+};
+
+const DOWN_GLOW = new MaterialFunction("down_glow", {
+ params: {},
+ code: `
+ o.base = vec3<f32>(0.0);
+ o.emissive = vec3<f32>(select(0.0, 1.0, i.ng.y < 0.0));`,
+});
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const glow = new MeshStandardMaterial({ name: "glow", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 1, roughness: 1 });
+ glow.shader = DOWN_GLOW.with({});
+ const panel = new Mesh(new PlaneGeometry(8, 8), glow);
+ panel.name = "panel";
+ panel.dynamicGeometry = true;
+ panel.rotation.x = Math.PI / 2;
+ panel.position.y = 1;
+ panel.scale.x = -1;
+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), panel]);
+};
diff --git a/tests/render/material-function-mirrored.ts b/tests/render/material-function-mirrored.ts
new file mode 100644
index 0000000..3525a46
--- /dev/null
+++ b/tests/render/material-function-mirrored.ts
@@ -0,0 +1,35 @@
+// A mesh placed mirrored (a negative scale) is an instance like any other; the tangent frame its material sees
+// changes hand with it (pathtrace.wgsl `inst_sign`). Two planes of one geometry and one material, each a mesh of its
+// own, the right one mirrored in x: the material's function emits 5 nits where the bitangent it is given points up
+// and 2 where it points down. A plane's image-up direction is up however it is mirrored in x: both read the same.
+import { Color, MaterialFunction, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "material/function-mirrored", features: ["material-function", "instancing", "mirrored"], reference: "analytic", temporal: false,
+ metric: { kind: "ratio", a: [0.6, 0.4, 0.75, 0.6], b: [0.25, 0.4, 0.4, 0.6], expected: 1, tolerance: 0.02 },
+ note: "left plane as it is, right plane mirrored in x, emission by the bitangent's side: right / left = 1",
+};
+
+const UP = new MaterialFunction("bitangent_up", {
+ params: {},
+ code: `
+ o.base = vec3<f32>(0.0);
+ o.emissive = vec3<f32>(select(2.0, 5.0, i.b.y > 0.0));`,
+});
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const material = new MeshStandardMaterial({ name: "side", color: new Color(0, 0, 0), roughness: 1 });
+ material.shader = UP.with({});
+ const geometry = new PlaneGeometry(1.8, 1.8);
+ const planes = [-1, 1].map((x) => {
+ const m = new Mesh(geometry, material);
+ m.name = x < 0 ? "left" : "right";
+ m.dynamicGeometry = true;
+ m.position.x = x;
+ m.scale.x = x < 0 ? 1 : -1;
+ return m;
+ });
+ return result(scene, camera(scene, [0, 0, 8], [0, 0, 0]), planes);
+};
diff --git a/tests/render/material-vertex-colors-mirrored.ts b/tests/render/material-vertex-colors-mirrored.ts
new file mode 100644
index 0000000..38cf418
--- /dev/null
+++ b/tests/render/material-vertex-colors-mirrored.ts
@@ -0,0 +1,21 @@
+// material/vertex-colors on a mesh placed mirrored (a negative scale): an instance, its vertex colours on their
+// vertices. The quad's colours run 0 .. 1 along its own x; mirrored in x, the world's left side is the bright one:
+// half a metre left of the centre reads 0.75, half a metre right 0.25.
+import { Mesh } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { gradientQuad, white } from "./material-vertex-colors.ts";
+
+export const test: TestMeta = {
+ id: "material/vertex-colors-mirrored", features: ["vertex-colors", "instancing", "mirrored"], reference: "analytic", temporal: false,
+ metric: { kind: "ratio", a: [0.3, 0.4, 0.35, 0.6], b: [0.65, 0.4, 0.7, 0.6], expected: 3, tolerance: 0.03 },
+ note: "a quad with vertex colours 0 .. 1 along x, mirrored in x: 0.75 at x = -0.5 over 0.25 at x = +0.5",
+};
+
+export default function () {
+ const scene = sceneWithSky(1);
+ const quad = new Mesh(gradientQuad(), white());
+ quad.name = "quad";
+ quad.dynamicGeometry = true;
+ quad.scale.x = -1;
+ return result(scene, camera(scene, [0, 0, 3], [0, 0, 0]), [quad]);
+}