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: a rough dielectric with a value and a density (#107)

Yujia1b1aa139a5b2
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 5cf9621..c05a15d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2512,6 +2512,27 @@ whoever reads it next: the particles' BLAS slot is 0.45 ms when the frame fits a
with a spread of 3 when it is between one and two, in main's build too: it times a wait.) Next here: the segment
test, whose pixels can go to the pass; a record that carries the surface where its material function is dear.
+**Glass as a rough dielectric (2026-11-16, after it).** Frosted glass was a delta event whatever its roughness: the
+ray refracted through a sampled microfacet with the weight of smooth glass, so the lobe had no value and no
+density, lights were never sampled through it, and a ray totally reflected inside took the glass's tint (a grey
+sheet seen past the critical angle read 0.5 of the sky). It is Walter et al. 2007's interface now (docs/RUNTIME.md
+"Glass"): reflection or refraction at a visible microfacet by the exact Fresnel reflectance, both with a value and
+a density; lights sampled on both sides, their shadow rays from the side they light; a delta lobe below roughness
+0.05 only; the energy single scattering loses returned from a table (Turquin 2019). Held by eleven `glass/*` tests
+against the BSDF's integral (lib.rs `glass_energy_tests`): one interface in a white sky 0.957 for 0.9573 entering,
+0.738 for 0.739 and 0.648 for 0.647 leaving, 0.999 and 0.992 with compensation, a lamp through frosted glass 4.01
+for 4.04, a frosted sphere in a furnace 0.999. Pictures without glass are as they were (render-identity: 196 of
+239 to the byte, the rest glass and water; Bistro's offline render to the byte, Kabukichō's still 4.66). The glass
+scene's offline render moved by ΔE 0.36 and its live frame keeps its distance to it (1.16 -> 1.18). The trace:
+the glass scene 3.95 -> 4.40 ms (+11 %), of which 0.36 ms is the lights now sampled through frosted glass;
+Bistro, Zero Day, lamp-rooms, Kabukichō, Tokyo as they were. bench-window kept one offline reference a shot
+whatever renderer made it: a build that changes the offline picture was read against the old one; the reference
+is keyed by the renderer's binary now, and the tool has a glass shot. Not here: thin walls (a pane is a solid's
+face), absorption by distance, the shadow rays' share (a Schlick albedo still, on a straight ray). Two things the
+kernel's shape decided: a shadow ray's origin on the side it leaves from is every surface's rule, but written into
+every kernel it cost Bistro's trace 4 %, so only kernels with glass have it; and the energy table's vec4 indexed
+by a variable cost the glass scene 1.5 %, a select chain nothing.
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
@@ -3051,6 +3072,7 @@ dynamic-resolution floor, 60 Hz camera input.
- The mannequin plaza's car now has clearcoated paint and a glass cabin with seats inside.
- Not yet:
- Thin-walled glass: a single-plane pane refracts as if solid.
+ - (Rough glass as a BSDF with a value and a density: done 2026-11-16, § 1.)
- Tinted shadows.
- Light through windows in the radiance cache: it treats glass as a surface, not a window.
- glTF KHR_materials_transmission / clearcoat.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 8bac46c..23e96db 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1566,6 +1566,28 @@ none of them it traces its light there. Two limits are known and held by tests s
sunlit mirror wall 5 % bright), and a surface seen in a reflection takes the sky's light from it, unshadowed
below a voxel's size.
+## Glass
+
+A transmissive material (`transmission`, `ior`, `roughness`) is a rough dielectric interface, Walter et al. 2007
+with GGX (pathtrace.wgsl "The dielectric"): light reflects off a microfacet or refracts through it by the exact
+Fresnel reflectance there. Reflection and transmission both have a value and a density, so lights are sampled
+through frosted glass, on both sides of it, and weighed against the BSDF's rays. Total internal reflection is
+reflection and is not tinted.
+
+- Below roughness 0.05 the transmission is a delta lobe: what lies behind a clear pane is seen straight (the path
+ loop's `through`: no clamp, the live specular signal). The reflection keeps its microfacet lobe.
+- Single scattering loses energy as the roughness grows (leaving glass of roughness 0.6 at 45 degrees: R + T =
+ 0.74). With energy compensation the interface is scaled by 1 / (R + T) from a table (Turquin 2019, as Cycles:
+ 16 x 16 x 8 x 2 values over the cosine, the roughness, the index and the side; lib.rs `glass_energy_lut`, a
+ section of the scene's tables).
+- Shadow rays cross glass straight, weighed by a share of their own (`glass_at`), as before.
+- Not yet: thin walls (a single sheet refracts as a solid's face), absorption by distance, the radiance scaling
+ by the indices' ratio squared (it cancels over a closed solid; Cycles and glTF's formula leave it out too).
+
+Held by `glass/*`: one interface in a white sky from either side against a quadrature over microfacet normals
+done apart, with compensation 1, a lamp seen through frosted glass against the BTDF's integral, a frosted sphere
+in a furnace.
+
## What the kernel trusts
The kernel follows indices it reads from buffers and loops over counts it is given; it checks none of them (a
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 29cd0fa..32f42a2 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -120,7 +120,7 @@ struct Params {
ltile: vec4<u32>, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
- table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, -, -
+ table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, -
word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, -
live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -
live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists
@@ -169,7 +169,8 @@ struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: ve
// - objects, per object (scene node): pivot (world position), world bounds size (UE ObjectPositionWS /
// ObjectBounds), then what `OBJECT_STRIDE` says;
// - instances (Instance), media (Medium);
-// - the GGX energy LUT: (E.x, E.y) for 32 roughness x 32 NoV, two per vec4.
+// - the GGX energy LUT: (E.x, E.y) for 32 roughness x 32 NoV, two per vec4;
+// - the glass energy table (`glass_energy`): four values per vec4.
// The buffer whole is `tables` in every layout (unsigned words: integers are read as they are, floats by a bit
// cast): the light groups, the light tree and the energy LUT are read from it, and what a scene has more of is
// another section of it, not another binding.
@@ -180,6 +181,7 @@ fn table_i(i: u32) -> vec4<i32> { return bitcast<vec4<i32>>(tables[i]); }
fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }
fn light_group_at(i: u32) -> vec4<f32> { return table_f(P.table_first[0].w + i); }
fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }
+fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }
// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,
// `object_at`, `instance_at` and `medium_at` in every layout.
@if(merged) {
@@ -827,7 +829,7 @@ fn light_vis(shadows: bool, o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> v
}
// Glass at a hit along d, `t` from the ray's start (texture LOD): its geometric normal, the share of the ray its
-// transmission lobe takes at that angle (transmission (x its texture) x (1 - E_spec), as lobes(); 0: not glass), its
+// transmission takes at that angle (transmission (x its texture) x (1 - a Schlick specular albedo); 0: not glass), its
// tint (base colour x texture: what the transmission lobe passes), and whether a ray from that side is totally
// reflected.
struct GlassAt { ng: vec3<f32>, share: f32, tir: bool, tint: vec3<f32> };
@@ -867,6 +869,9 @@ fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {
let ior = max(m.layer.y, 1.0001);
let eta = select(1.0 / ior, ior, dot(g.ng, d) > 0.0);
g.tir = eta * eta * (1.0 - c * c) >= 1.0;
+ // (Schlick from either side, no total reflection: the ray goes straight where the light it stands for refracts,
+ // glass_tr. With the dielectric's own reflectance a surface seen past the critical angle let the whole sky
+ // through: water/furnace 1.16.)
let r = (ior - 1.0) / (ior + 1.0);
let f0 = r * r;
let e = energy_lookup(clamp(m.params.y, 0.02, 1.0), c);
@@ -1358,14 +1363,118 @@ fn lut(x: u32, y: u32) -> vec2<f32> {
return select(v.xy, v.zw, (i & 1u) == 1u);
}
-// Base layer: diffuse + GGX specular (p_spec: the specular share of the base's samples). Over it a clearcoat (GGX, F0
-// 0.04; the base gets what the coat's directional albedo e_coat lets through), and for glass a transmitted share
-// `tint` (delta lobe, sampled with p_trans) in place of the diffuse. p_coat / p_trans: shares of all samples.
+// Base layer: diffuse + GGX specular (e_spec: the specular's directional albedo; kd: what it leaves the diffuse
+// under it; p_spec: the specular share of the base's samples). Over it a clearcoat (GGX, F0 0.04; the base gets what
+// the coat's directional albedo e_coat lets through). Glass: a share of the base is a dielectric interface (below,
+// "The dielectric"), the rest keeps the diffuse and the specular. p_coat / p_trans: the coat's and the dielectric's
+// shares of all samples.
struct Lobes {
- diffuse: vec3<f32>, f0: vec3<f32>, f90: vec3<f32>, w: vec3<f32>, e_spec: vec3<f32>, a2: f32, p_spec: f32,
+ diffuse: vec3<f32>, f0: vec3<f32>, f90: vec3<f32>, w: vec3<f32>, e_spec: vec3<f32>, kd: vec3<f32>, a2: f32, p_spec: f32,
coat: f32, coat_alpha: f32, e_coat: f32, p_coat: f32, tint: vec3<f32>, p_trans: f32,
+ // The dielectric: its share of the base under the coat x its energy compensation (reflection's factor), `tint`
+ // the same x the base colour (transmission's); n(far side) / n(view side); whether its transmission has a density;
+ // its directional reflection albedo (before the coat).
+ t: f32, eta: f32, rough_t: bool, e_glass: f32,
};
+// ------------------------------------------------------------------------------------------------
+// The dielectric (glass): a rough interface between two indices of refraction, Walter et al. 2007 (GGX): light
+// reflects off a microfacet or refracts through it by the Fresnel reflectance there, exact (total internal
+// reflection is reflection, untinted). Both have a value and a density, so lights are sampled through frosted glass
+// and weighed against the BSDF's rays. Below GLASS_DELTA its transmission is a delta lobe (a clear pane: what lies
+// behind is seen straight, `through` in the path loop); its reflection keeps the microfacet lobe. Single scattering
+// loses energy as the roughness grows (leaving glass at 0.6: a quarter); the whole is scaled by 1 / (R + T) from a
+// table (Turquin 2019, as Cycles), P.misc.z of it.
+// Not here: the radiance scaling by the indices' ratio squared (as Cycles and glTF's formula: it cancels over a
+// closed solid, and a single-sheet pane, which refracts as a solid here, would be scaled once); thin walls;
+// absorption by distance.
+const GLASS_DELTA: f32 = 0.05; // roughness (RTXPT 0.04, Falcor 0.08)
+
+// Unpolarised Fresnel reflectance: `c` the cosine on the incident side, `eta` = n(far) / n(incident); 1 at total
+// internal reflection (Walter eq. 22).
+fn fresnel_dielectric(c: f32, eta: f32) -> f32 {
+ let g2 = eta * eta - 1.0 + c * c;
+ if (g2 <= 0.0) { return 1.0; }
+ let g = sqrt(g2);
+ let a = (g - c) / (g + c);
+ let b = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
+ return 0.5 * a * a * (1.0 + b * b);
+}
+
+// Smith's Lambda (GGX) at |cosine| c: g1 = 1 / (1 + Lambda).
+fn lambda_ggx(a2: f32, c: f32) -> f32 {
+ let c2 = c * c;
+ return 0.5 * (sqrt(1.0 + a2 * (1.0 - c2) / max(c2, 1e-8)) - 1.0);
+}
+
+// The glass energy table (lib.rs `glass_energy_lut`, `GLASS_E`): R + T of the interface at GLASS_E_MU nodes over
+// sqrt(cos), GLASS_E_ROUGH over the roughness, GLASS_E_IOR over sqrt((ior - 1) / (ior + 1)) up to GLASS_E_ZMAX
+// (ior 3); entering, then leaving.
+const GLASS_E_MU: u32 = 16u;
+const GLASS_E_ROUGH: u32 = 16u;
+const GLASS_E_IOR: u32 = 8u;
+const GLASS_E_ZMAX: f32 = 0.70710678;
+// (A select chain: the vec4 indexed by a variable cost the glass scene's trace 1.5 %.)
+fn glass_e_at(i: u32) -> f32 {
+ let v = glass_energy_at(i / 4u);
+ let k = i & 3u;
+ return select(select(v.x, v.y, k == 1u), select(v.z, v.w, k == 3u), k >= 2u);
+}
+// One (roughness, ior, side) row of it at x, between the nodes.
+fn glass_e_row(row: u32, x: f32) -> f32 {
+ let x0 = u32(x);
+ return mix(glass_e_at(row * GLASS_E_MU + x0), glass_e_at(row * GLASS_E_MU + min(x0 + 1u, GLASS_E_MU - 1u)), x - f32(x0));
+}
+fn glass_energy(nov: f32, roughness: f32, ior: f32, leaving: bool) -> f32 {
+ let x = clamp(sqrt(nov), 0.0, 1.0) * f32(GLASS_E_MU - 1u);
+ let y = clamp(roughness, 0.0, 1.0) * f32(GLASS_E_ROUGH - 1u);
+ let z = clamp(sqrt(max(ior - 1.0, 0.0) / (ior + 1.0)) / GLASS_E_ZMAX, 0.0, 1.0) * f32(GLASS_E_IOR - 1u);
+ let y0 = u32(y);
+ let y1 = min(y0 + 1u, GLASS_E_ROUGH - 1u);
+ let z0 = select(0u, GLASS_E_IOR, leaving) + u32(z);
+ let z1 = select(0u, GLASS_E_IOR, leaving) + min(u32(z) + 1u, GLASS_E_IOR - 1u);
+ let e0 = mix(glass_e_row(z0 * GLASS_E_ROUGH + y0, x), glass_e_row(z0 * GLASS_E_ROUGH + y1, x), y - f32(y0));
+ let e1 = mix(glass_e_row(z1 * GLASS_E_ROUGH + y0, x), glass_e_row(z1 * GLASS_E_ROUGH + y1, x), y - f32(y0));
+ return mix(e0, e1, z - floor(z));
+}
+
+// Whether lights on both sides of the surface reach it: rough glass.
+fn two_sided(lb: Lobes) -> bool { return has(F_GLASS) && lb.rough_t; }
+
+// The dielectric's transmission toward l (the far side; nov, nol: |cosines|) x |n.l|: Walter eq. 21 from the view
+// side. `h` = the microfacet normal that refracts v to l, on the shading normal's side.
+fn dielectric_t(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>, nov: f32, nol: f32) -> vec3<f32> {
+ if (!lb.rough_t) { return vec3<f32>(0.0); }
+ var h = normalize(v + lb.eta * l);
+ if (dot(h, s.n) < 0.0) { h = -h; }
+ let voh = dot(v, h);
+ let loh = dot(l, h);
+ if (voh <= 0.0 || loh >= 0.0) { return vec3<f32>(0.0); }
+ let den = voh + lb.eta * loh;
+ let g2 = 1.0 / (1.0 + lambda_ggx(lb.a2, nov) + lambda_ggx(lb.a2, nol));
+ return lb.tint * ((1.0 - fresnel_dielectric(voh, lb.eta)) * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) * g2 * voh * lb.eta * lb.eta * -loh / (nov * max(den * den, 1e-12)));
+}
+
+// Density of l under the dielectric's sampling (`sample_bsdf`: a visible microfacet normal, the ray reflected or
+// refracted by the Fresnel reflectance there; at the shading normal's for smooth glass), x its share of the samples.
+fn pdf_dielectric(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
+ let nov = max(dot(s.n, v), 1e-4);
+ if (dot(s.n, l) > 0.0) {
+ let h = normalize(v + l);
+ let voh = max(dot(v, h), 1e-6);
+ let f = fresnel_dielectric(select(nov, voh, lb.rough_t), lb.eta);
+ return lb.p_trans * f * g1(lb.a2, nov) * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) / (4.0 * nov);
+ }
+ if (!lb.rough_t) { return 0.0; }
+ var h = normalize(v + lb.eta * l);
+ if (dot(h, s.n) < 0.0) { h = -h; }
+ let voh = dot(v, h);
+ let loh = dot(l, h);
+ if (voh <= 0.0 || loh >= 0.0) { return 0.0; }
+ let den = voh + lb.eta * loh;
+ return lb.p_trans * (1.0 - fresnel_dielectric(voh, lb.eta)) * g1(lb.a2, nov) * voh * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) * lb.eta * lb.eta * -loh / (nov * max(den * den, 1e-12));
+}
+
fn lobes(s: Surface, nov: f32) -> Lobes {
var l: Lobes;
let t = s.transmission * (1.0 - s.metallic);
@@ -1382,10 +1491,16 @@ fn lobes(s: Surface, nov: f32) -> Lobes {
// misc.z = multiple-scattering compensation amount (1 = energy conserving, matches the white furnace).
l.w = 1.0 + P.misc.z * l.f0 * ((1.0 - e.x) / e.x);
l.e_spec = l.w * (e.x * l.f0 + e.y * (l.f90 - l.f0));
+ l.kd = 1.0 - l.e_spec;
+ if (has(F_GLASS) && t > 0.0) {
+ // The share that is not the dielectric keeps this specular lobe (the diffuse, 1 - t of it already, under it).
+ l.w *= 1.0 - t;
+ l.e_spec *= 1.0 - t;
+ }
let r = s.roughness;
l.a2 = r * r * r * r;
let ws = dot(l.e_spec, vec3<f32>(0.3, 0.6, 0.1));
- let wd = dot(l.diffuse * (1.0 - l.e_spec), vec3<f32>(0.3, 0.6, 0.1));
+ let wd = dot(l.diffuse * l.kd, vec3<f32>(0.3, 0.6, 0.1));
l.p_spec = clamp(ws / max(ws + wd, 1e-6), 0.05, 1.0);
if (wd <= 0.0) { l.p_spec = 1.0; }
l.coat_alpha = 1.0;
@@ -1396,8 +1511,17 @@ fn lobes(s: Surface, nov: f32) -> Lobes {
l.coat_alpha = s.coat_rough * s.coat_rough;
}
let under = 1.0 - l.e_coat;
- l.tint = s.base * t * (1.0 - l.e_spec) * under;
- let wt = dot(l.tint, vec3<f32>(0.3, 0.6, 0.1));
+ var wt = 0.0;
+ if (has(F_GLASS) && t > 0.0) {
+ l.eta = select(1.0 / s.ior, s.ior, s.front);
+ l.rough_t = s.roughness > GLASS_DELTA && abs(s.ior - 1.0) > 1e-3;
+ var comp = 1.0;
+ if (l.rough_t) { comp = mix(1.0, 1.0 / glass_energy(nov, s.roughness, s.ior, !s.front), P.misc.z); }
+ l.t = t * under * comp;
+ l.tint = s.base * l.t;
+ l.e_glass = t * fresnel_dielectric(nov, l.eta);
+ wt = under * (l.e_glass + (t - l.e_glass) * dot(s.base, vec3<f32>(0.3, 0.6, 0.1)));
+ }
let total = (ws + wd) * under + l.e_coat + wt;
l.p_coat = l.e_coat / max(total, 1e-6);
l.p_trans = wt / max(total, 1e-6);
@@ -1425,18 +1549,27 @@ fn f_schlick(f0: vec3<f32>, f90: vec3<f32>, voh: f32) -> vec3<f32> {
fn eval_bsdf_k(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>, k: f32) -> vec3<f32> {
let nol = dot(s.n, l);
let nov = max(dot(s.n, v), 1e-4);
+ if (two_sided(lb) && nol < 0.0 && dot(s.ng, l) < 0.0) {
+ split_frac = vec3<f32>(1.0);
+ return dielectric_t(s, lb, v, l, nov, -nol);
+ }
if (nol <= 0.0 || dot(s.ng, l) <= 0.0) { return vec3<f32>(0.0); }
let h = normalize(v + l);
let noh = max(dot(s.n, h), 0.0);
let voh = max(dot(v, h), 0.0);
- var spec = d_ggx(lb.a2, noh) * vis_smith_joint_approx(lb.a2, nov, nol) * f_schlick(lb.f0, lb.f90, voh) * lb.w * k;
- var diff = lb.diffuse * (1.0 / PI) * (1.0 - lb.e_spec);
+ let dv = d_ggx(lb.a2, noh) * vis_smith_joint_approx(lb.a2, nov, nol);
+ var spec = dv * f_schlick(lb.f0, lb.f90, voh) * lb.w * k;
+ // (The dielectric's reflection: lb.t holds the coat's share already, so it joins after the coat's layering.)
+ var glass = 0.0;
+ if (has(F_GLASS) && lb.t > 0.0) { glass = lb.t * fresnel_dielectric(voh, lb.eta) * dv * k; }
+ var diff = lb.diffuse * (1.0 / PI) * lb.kd;
if (has(F_COAT) && lb.coat > 0.0) {
let ca2 = lb.coat_alpha * lb.coat_alpha;
let coat = d_ggx(ca2, noh) * vis_smith_joint_approx(ca2, nov, nol) * f_schlick(vec3<f32>(0.04), vec3<f32>(1.0), voh).x * lb.coat * k;
diff *= 1.0 - lb.e_coat;
spec = spec * (1.0 - lb.e_coat) + vec3<f32>(coat);
}
+ spec += vec3<f32>(glass);
split_frac = spec / max(diff + spec, vec3<f32>(1e-12));
return (diff + spec) * nol;
}
@@ -1452,7 +1585,9 @@ fn g1(a2: f32, nov: f32) -> f32 {
fn pdf_bsdf(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
let nol = dot(s.n, l);
- if (nol <= 0.0) { return 0.0; }
+ var pg = 0.0;
+ if (has(F_GLASS) && lb.p_trans > 0.0) { pg = pdf_dielectric(s, lb, v, l); }
+ if (nol <= 0.0) { return pg; }
let nov = max(dot(s.n, v), 1e-4);
let h = normalize(v + l);
let noh = max(dot(s.n, h), 0.0);
@@ -1465,8 +1600,8 @@ fn pdf_bsdf(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
let ca2 = lb.coat_alpha * lb.coat_alpha;
pc = g1(ca2, nov) * d_ggx(ca2, noh) / (4.0 * nov);
}
- // The delta transmission lobe has no density here: its share of samples only lowers the others'.
- return lb.p_coat * pc + (1.0 - lb.p_coat - lb.p_trans) * (lb.p_spec * ps + (1.0 - lb.p_spec) * pd);
+ // (Smooth glass's transmission is a delta lobe, without a density: its samples only lower the others' share.)
+ return pg + lb.p_coat * pc + (1.0 - lb.p_coat - lb.p_trans) * (lb.p_spec * ps + (1.0 - lb.p_spec) * pd);
}
// MIS weight of a light sample (solid-angle pdf `pdf_l`) against BSDF sampling. A_CUTOUT_PATHS: light that reached
@@ -1491,6 +1626,7 @@ fn light_mis(pdf_l: f32, s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f
let ca2 = lb.coat_alpha * lb.coat_alpha;
p += lb.p_coat * g1(ca2, nov) * d_ggx(ca2, noh) / (4.0 * nov);
}
+ if (has(F_GLASS) && lb.p_trans > 0.0) { p += pdf_dielectric(s, lb, v, l); }
see = min(p / pb, 1.0);
}
return 1.0 - see * (1.0 - w);
@@ -1523,6 +1659,8 @@ fn sample_vndf(v: vec3<f32>, tbn: mat3x3<f32>, alpha: f32, u1: f32, u2: f32) ->
return tbn * hl;
}
+// A direction by the BSDF's lobes (`pdf_bsdf` its density; which lobe: sampled_spec, sampled_trans). The zero vector:
+// no sample (every value and density of it is 0).
fn sample_bsdf(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
let tbn = basis(s.n);
let r = rng4(rng_dim(D_BSDF));
@@ -1534,14 +1672,21 @@ fn sample_bsdf(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
return reflect(-v, sample_vndf(v, tbn, lb.coat_alpha, r.z, r.w));
}
if (u < lb.p_coat + lb.p_trans) {
- // Refraction through a microfacet normal (Walter et al. 2007; smooth glass: the shading normal).
+ // The dielectric: a visible microfacet normal; reflected off it, or refracted through it (smooth glass:
+ // through the shading normal), by the Fresnel reflectance there.
+ let h = sample_vndf(v, tbn, s.roughness * s.roughness, r.z, r.w);
+ var m = s.n;
+ if (lb.rough_t) { m = h; }
+ let t = refract(-v, m, 1.0 / lb.eta);
+ sampled_spec = u - lb.p_coat < fresnel_dielectric(max(dot(v, m), 1e-4), lb.eta) * lb.p_trans || all(t == vec3<f32>(0.0));
+ // A ray reflected under the surface, or refracted and still above it, is one the microfacets' masking
+ // stops: no sample.
+ if (sampled_spec) {
+ let rl = reflect(-v, h);
+ return select(rl, vec3<f32>(0.0), dot(rl, s.n) <= 0.0);
+ }
sampled_trans = true;
- sampled_spec = false;
- var h = s.n;
- if (s.roughness > 0.05) { h = sample_vndf(v, tbn, s.roughness * s.roughness, r.z, r.w); }
- let t = refract(-v, h, select(s.ior, 1.0 / s.ior, s.front));
- // Total internal reflection: the ray stays inside.
- return select(t, reflect(-v, h), all(t == vec3<f32>(0.0)));
+ return select(t, vec3<f32>(0.0), dot(t, s.n) >= 0.0);
}
}
sampled_spec = r.y < lb.p_spec;
@@ -1826,6 +1971,14 @@ fn lt_in_list(i: u32) -> bool {
return false;
}
+// A shadow ray's origin toward l at a surface: on the side l leaves it from (`o`: the near side's, as computed once).
+// Only a surface that lets light through has a value for the far side, so only a kernel with glass has the code
+// (in every kernel, at its five inlined sites, it cost Bistro's trace 4 %).
+fn light_origin(s: Surface, o: vec3<f32>, l: vec3<f32>) -> vec3<f32> {
+ if (has(F_GLASS) && dot(l, s.ng) < 0.0) { return offset_origin(s.p, -s.ng); }
+ return o;
+}
+
fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>, vol: bool, d: vec3<f32>, rd: u32) -> vec3<f32> {
let nd = P.counts2.x;
let nl = P.counts.x - nd;
@@ -1856,12 +2009,12 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
let dc = li.pos.xyz - x;
let reach = li.color.w + select(li.dir.w, length(li.ext.xyz) + li.dir.w, u32(li.pos.w) == 3u);
if (li.color.w > 0.0 && dot(dc, dc) > reach * reach) { continue; }
- if (u32(li.pos.w) != 3u && dot(dc, s.ng) < -li.dir.w) { continue; } // eval_bsdf rejects it anyway
+ if (u32(li.pos.w) != 3u && dot(dc, s.ng) < -li.dir.w && !two_sided(lb)) { continue; } // eval_bsdf rejects it anyway
let ls = local_light(li, x, rng2(rng_sub(rd, i)));
if (all(ls.c <= vec3<f32>(0.0))) { continue; }
let f = eval_bsdf_k(s, lb, v, ls.l, li.x.y);
if (any(f > vec3<f32>(0.0))) {
- let vis = light_vis(li.ext.w >= 0.5, o, ls.sl, ls.dist * 0.999, rng_sub(rd ^ 0x40000000u, i));
+ let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, ls.l), ls.sl, ls.dist * 0.999, rng_sub(rd ^ 0x40000000u, i));
if (any(vis > vec3<f32>(0.0))) {
sum += ls.c * f * tr3(vis);
dl_spec += ls.c * f * tr3(vis) * split_frac;
@@ -1903,7 +2056,7 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
}
let ls = local_light(light_at(idx), x, r4.yz);
var ph = luminance(ls.c);
- if (vol) { ph *= light_at(idx).x.x; } else { ph *= max(dot(s.n, ls.l), 0.0) + 0.05 * max(dot(s.ng, ls.l), 0.0); }
+ if (vol) { ph *= light_at(idx).x.x; } else if (two_sided(lb)) { ph *= abs(dot(s.n, ls.l)); } else { ph *= max(dot(s.n, ls.l), 0.0) + 0.05 * max(dot(s.ng, ls.l), 0.0); }
if (ph <= 0.0) { continue; }
if (nt > 0u && k < m_cand && lt_in_list(idx)) { continue; }
let w = ph * stands;
@@ -1919,7 +2072,7 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
let lk = light_at(pick).x;
if (vol) { c = pick_ls.c * hg_phase(P.vol.y, dot(pick_ls.l, d)) * lk.x; } else { c = pick_ls.c * eval_bsdf_k(s, lb, v, pick_ls.l, lk.y); }
if (any(c > vec3<f32>(0.0))) {
- let vis = light_vis(light_at(pick).ext.w >= 0.5, o, pick_ls.sl, pick_ls.dist * 0.999, rng_sub(rd, 0xffffffffu));
+ let vis = light_vis(light_at(pick).ext.w >= 0.5, light_origin(s, o, pick_ls.l), pick_ls.sl, pick_ls.dist * 0.999, rng_sub(rd, 0xffffffffu));
if (any(vis > vec3<f32>(0.0))) {
let r = c * tr3(vis) * (wsum * f32(count) / (f32(m_cand) * pick_ph));
sum += r;
@@ -1989,7 +2142,7 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
let dl = lp - x;
let d2 = max(dot(dl, dl), 1e-8);
let l = dl * inverseSqrt(d2);
- var g = abs(dot(ln, l)) * max(dot(n, l), 0.0) / d2;
+ var g = abs(dot(ln, l)) * select(max(dot(n, l), 0.0), 1.0, dot(n, n) == 0.0) / d2;
if (m > 1u) { g = abs(dot(ln, l)) * luminance(eval_bsdf(sf, lb, v, l)) / d2; }
// target (emitted luminance x G) over source pdf (luminance x light LOD / total, per area) = total x G / LOD;
// with the tree the source pdf is its selection probability / area (weight / area = luminance x power)
@@ -2101,7 +2254,7 @@ fn hg_phase(g: f32, c: f32) -> f32 {
let l = basis(to_light) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
let f = eval_bsdf_k(s, lb, v, l, li.x.y);
if (any(f > vec3<f32>(0.0))) {
- let vis = light_vis(li.ext.w >= 0.5, o, l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
+ let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, l), l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
if (any(vis > vec3<f32>(0.0))) {
let pdf_l = 1.0 / (2.0 * PI * (1.0 - cos_max));
sum += li.color.rgb * f * light_mis(pdf_l, s, lb, v, l) * tr3(vis);
@@ -2121,7 +2274,7 @@ fn env_light(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>) -> vec3<f32> {
if (any(f > vec3<f32>(0.0))) {
let pdf_e = env_pdf(l);
if (pdf_e > 0.0) {
- let vis = sky_tr(o, l, rng_dim(D_ENV_VIS));
+ let vis = sky_tr(light_origin(s, o, l), l, rng_dim(D_ENV_VIS));
if (any(vis > vec3<f32>(0.0))) { return env_radiance(l) * f * light_mis(pdf_e, s, lb, v, l) / pdf_e * tr3(vis); }
}
}
@@ -2147,7 +2300,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
let f = eval_bsdf_k(s, lb, v, l, li.x.y);
if (any(f > vec3<f32>(0.0))) {
- let vis = light_vis(li.ext.w >= 0.5, o, l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
+ let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, l), l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
if (any(vis > vec3<f32>(0.0))) {
let pdf_l = 1.0 / (2.0 * PI * (1.0 - cos_max));
let frac = split_frac;
@@ -2185,18 +2338,22 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
@if(!light_pick) sum += local_lights(s, lb, v, o, s.p, false, vec3<f32>(0.0), rng_dim(D_LOCAL));
@if(light_pick) if (take_local) { sum += local_lights(s, lb, v, o, s.p, false, vec3<f32>(0.0), rng_dim(D_LOCAL)); }
// Emissive triangles (incl. rect lights)
+ // (Rough glass takes emitters from both sides: as a point without a hemisphere does, the samples and `emit_mis`
+ // alike. The tree's bound has no two-sided cosine; without one the estimate is the same, its noise a little more.)
+ var ne = s.n;
+ if (two_sided(lb)) { ne = vec3<f32>(0.0); }
mis_x = o;
- mis_n = s.n;
+ mis_n = ne;
var emitters = P.counts.y;
@if(light_pick) if (!take_emit) { emitters = 0u; }
if (emitters > 0u) {
var es: ES;
// With the light tree its candidates are already near the point: P.ltree.y of them at camera hits, one elsewhere.
- if (lt_on()) { es = sample_emitter_ris(o, s.n, select(1u, u32(P.ltree.w), cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (seen_directly()) { es = sample_emitter_ris(o, s.n, select(EMIT_RIS_M / 2u, EMIT_RIS_M, cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (P.light_lod.w > 0.0) { es = sample_emitter_ris(o, s.n, 2u, s, lb, v, rng_dim(D_EMIT)); } else { es = sample_emitter(o, s.n, rng_dim(D_EMIT)); }
+ if (lt_on()) { es = sample_emitter_ris(o, ne, select(1u, u32(P.ltree.w), cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (seen_directly()) { es = sample_emitter_ris(o, ne, select(EMIT_RIS_M / 2u, EMIT_RIS_M, cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (P.light_lod.w > 0.0) { es = sample_emitter_ris(o, ne, 2u, s, lb, v, rng_dim(D_EMIT)); } else { es = sample_emitter(o, ne, rng_dim(D_EMIT)); }
if (es.pdf_w > 0.0) {
let f = eval_bsdf(s, lb, v, es.l);
if (any(f > vec3<f32>(0.0))) {
- let vis = emitter_tr(o, es.l, es.dist * 0.999, rng_dim(D_EMIT_VIS));
+ let vis = emitter_tr(light_origin(s, o, es.l), es.l, es.dist * 0.999, rng_dim(D_EMIT_VIS));
if (vis > 0.0) {
let frac = split_frac;
let wgt = light_mis(es.pdf_w, s, lb, v, es.l) * tr1(vis);
@@ -3077,6 +3234,7 @@ fn white_lobes() -> Lobes {
l.f90 = vec3<f32>(0.0);
l.w = vec3<f32>(1.0);
l.e_spec = vec3<f32>(0.0);
+ l.kd = vec3<f32>(1.0);
l.a2 = 1.0;
l.p_spec = 0.0;
l.coat_alpha = 1.0;
@@ -3087,7 +3245,8 @@ fn white_lobes() -> Lobes {
// diffuse + directional specular albedo, under the coat's (as `eval_bsdf_k` layers them; without the coat's term a
// coated surface reflected e_coat (1 - the rest) too little).
fn cache_reflectance(lb: Lobes) -> vec3<f32> {
- let r = lb.diffuse * (1.0 - lb.e_spec) + lb.e_spec;
+ var r = lb.diffuse * lb.kd + lb.e_spec;
+ if (has(F_GLASS)) { r += vec3<f32>(lb.e_glass); }
if (has(F_COAT)) { return r * (1.0 - lb.e_coat) + lb.e_coat; }
return r;
}
@@ -3731,9 +3890,10 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
let l = sample_bsdf(s, lb, v);
- // Through glass: a delta lobe (weight tint / its sampling share, no MIS: what lies behind counts in full) whose
- // light the live viewport files with the specular, like a reflection.
- let through = has(F_GLASS) && sampled_trans;
+ // Through smooth glass: a delta lobe (weight tint / its sampling share, no MIS: what lies behind counts in full).
+ // Rough glass's transmission has a density like any lobe. Either way the live viewport files the light with
+ // the specular, like a reflection.
+ let through = has(F_GLASS) && sampled_trans && !lb.rough_t;
var pdf = 0.0;
var wgt = lb.tint / max(lb.p_trans, 1e-6);
if (through) {
@@ -3747,7 +3907,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
k_spec = split_frac;
rad0 = radiance;
split = true;
- spec_lobe = sampled_spec || through;
+ spec_lobe = sampled_spec || sampled_trans;
through0 = through;
glass0 = has(F_GLASS) && s.transmission > 0.0;
refl_e = lb.e_spec;
@@ -3763,7 +3923,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
behind_glass = true;
bent = !bent;
} else if (through) {
- // Total internal reflection: a specular vertex (no light sampling covers what it reflects).
+ // (A refracted direction the geometric normal keeps on this side: a specular vertex.)
last_pdf = 0.0;
specular_bounce = true;
behind_glass = false;
@@ -3777,7 +3937,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
straight = straight && through;
cone_w = width;
cone_a += 2.0 * s.roughness * s.roughness;
- mirror_path = (depth == 0u || mirror_path) && s.roughness < MIRROR_ROUGHNESS && (sampled_spec || through);
+ mirror_path = (depth == 0u || mirror_path) && s.roughness < MIRROR_ROUGHNESS && (sampled_spec || sampled_trans);
if (depth >= P.counts.w) {
let q = min(max(thr.x, max(thr.y, thr.z)), 0.95);
if (rng1(rng_dim(D_RR)) > q) { break; }
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 011148b..78b630b 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -2095,6 +2095,7 @@ impl Gpu {
(Table::Instances, bytemuck::cast_slice(if records.is_empty() { &none[..] } else { &records[..] }), room.records * std::mem::size_of::<crate::scene::GpuInstance>()),
(Table::Media, bytemuck::cast_slice(&scene.media), 0),
(Table::Energy, bytemuck::cast_slice(energy), 0),
+ (Table::GlassEnergy, bytemuck::cast_slice(crate::glass_energy_lut()), 0),
];
assert!(parts.iter().enumerate().all(|(k, p)| p.0.index() == k), "the tables in `Table`'s order");
let heap = Heap::filled(d, &parts.map(|p| (p.1.len() + p.2) as u64), |put| parts.iter().for_each(|p| put(p.0, 0, p.1)));
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
index 0025427..954a77b 100644
--- a/renderer/src/heap.rs
+++ b/renderer/src/heap.rs
@@ -47,10 +47,12 @@ pub enum Table {
Media,
/// The GGX energy table, 512 vec4s.
Energy,
+ /// The glass energy table (lib.rs `glass_energy_lut`).
+ GlassEnergy,
}
impl Section for Table {
- const COUNT: usize = 10;
+ const COUNT: usize = 11;
const UNIT: u64 = 16;
const LABEL: &'static str = "tables";
fn index(self) -> usize {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index fdbe6e0..80a9322 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -917,6 +917,241 @@ pub fn energy_lut() -> Vec<[f32; 4]> {
vals.chunks(2).map(|c| [c[0][0], c[0][1], c[1][0], c[1][1]]).collect()
}
+/// The glass energy table's nodes (pathtrace.wgsl GLASS_E_MU, _ROUGH, _IOR): cos(view) as its square root, roughness,
+/// the index of refraction as sqrt((ior - 1) / (ior + 1)) up to `GLASS_E_ZMAX` (ior 3); and the side (entering,
+/// leaving).
+pub const GLASS_E: [usize; 3] = [16, 16, 8];
+pub const GLASS_E_ZMAX: f64 = std::f64::consts::FRAC_1_SQRT_2;
+
+/// Unpolarised Fresnel reflectance of a dielectric interface: `c` the cosine on the incident side, `eta` = n_t / n_i;
+/// 1 at total internal reflection (Walter et al. 2007, eq. 22).
+fn fresnel_dielectric(c: f64, eta: f64) -> f64 {
+ let g2 = eta * eta - 1.0 + c * c;
+ if g2 <= 0.0 {
+ return 1.0;
+ }
+ let g = g2.sqrt();
+ let (a, b) = ((g - c) / (g + c), (c * (g + c) - 1.0) / (c * (g - c) + 1.0));
+ 0.5 * a * a * (1.0 + b * b)
+}
+
+/// What a rough dielectric interface (GGX, single scattering: the kernel's `dielectric_*`) returns of a uniform white
+/// surround toward a direction at cosine `mu`: reflection + transmission, without the tint. `alpha` = roughness^2,
+/// `eta` = n(far side) / n(view side). By `n` x `n` stratified visible normals (Heitz 2018), whose estimator is
+/// bounded: G2 / G1, reflected or refracted by Fresnel at the normal.
+pub fn glass_energy(mu: f64, alpha: f64, eta: f64, n: usize) -> f64 {
+ let a2 = alpha * alpha;
+ let lambda = |c: f64| {
+ let c = c.abs().min(1.0);
+ 0.5 * (-1.0 + (1.0 + a2 * (1.0 - c * c) / (c * c)).sqrt())
+ };
+ let v = [(1.0 - mu * mu).max(0.0).sqrt(), 0.0, mu];
+ let k = (alpha * alpha * v[0] * v[0] + v[2] * v[2]).sqrt();
+ let vh = [alpha * v[0] / k, 0.0, v[2] / k];
+ // (t1 = (0, 1, 0), t2 = vh x t1.)
+ let t2 = [-vh[2], 0.0, vh[0]];
+ let (lv, s) = (lambda(mu), 0.5 * (1.0 + vh[2]));
+ let mut sum = 0.0;
+ for i in 0..n {
+ for j in 0..n {
+ let (r, phi) = (((i as f64 + 0.5) / n as f64).sqrt(), 2.0 * std::f64::consts::PI * (j as f64 + 0.5) / n as f64);
+ let p1 = r * phi.cos();
+ let p2 = (1.0 - s) * (1.0 - p1 * p1).max(0.0).sqrt() + s * r * phi.sin();
+ let pz = (1.0 - p1 * p1 - p2 * p2).max(0.0).sqrt();
+ let nh = [p2 * t2[0] + pz * vh[0], p1, p2 * t2[2] + pz * vh[2]];
+ let m = [alpha * nh[0], alpha * nh[1], nh[2].max(0.0)];
+ let len = (m[0] * m[0] + m[1] * m[1] + m[2] * m[2]).sqrt();
+ let m = [m[0] / len, m[1] / len, m[2] / len];
+ let vm = v[0] * m[0] + v[2] * m[2];
+ let f = fresnel_dielectric(vm, eta);
+ // Reflection: the kernel's joint visibility (vis_smith_joint_approx x 4 nov nol) over G1(v).
+ let nol = 2.0 * vm * m[2] - v[2];
+ if nol > 0.0 {
+ let g2 = 2.0 * mu * nol / (nol * (mu * (1.0 - alpha) + alpha) + mu * (nol * (1.0 - alpha) + alpha)).max(1e-7);
+ sum += f * g2 * (1.0 + lv);
+ }
+ // Refraction (eq. 40): height-correlated Smith over G1(v).
+ let c2 = 1.0 - (1.0 - vm * vm) / (eta * eta);
+ if f < 1.0 && c2 > 0.0 {
+ let lz = (vm / eta - c2.sqrt()) * m[2] - v[2] / eta;
+ if lz < 0.0 {
+ sum += (1.0 - f) * (1.0 + lv) / (1.0 + lv + lambda(lz));
+ }
+ }
+ }
+ }
+ sum / (n * n) as f64
+}
+
+/// `glass_energy` over the table's nodes, entering then leaving, four values a vec4 (`heap::Table::GlassEnergy`; once
+/// a process, 35 ms).
+pub fn glass_energy_lut() -> &'static [[f32; 4]] {
+ static LUT: std::sync::OnceLock<Vec<[f32; 4]>> = std::sync::OnceLock::new();
+ LUT.get_or_init(|| {
+ let [nm, nr, nz] = GLASS_E;
+ let mut vals = Vec::with_capacity(2 * nz * nr * nm);
+ for side in 0..2 {
+ for iz in 0..nz {
+ let z = (iz as f64 / (nz - 1) as f64 * GLASS_E_ZMAX).max(0.02);
+ let ior = (1.0 + z * z) / (1.0 - z * z);
+ for ir in 0..nr {
+ let r = (ir as f64 / (nr - 1) as f64).max(0.02);
+ for im in 0..nm {
+ let y = im as f64 / (nm - 1) as f64;
+ vals.push(glass_energy((y * y).max(1e-3), r * r, if side == 0 { ior } else { 1.0 / ior }, 24).clamp(0.05, 1.0) as f32);
+ }
+ }
+ }
+ }
+ vals.chunks(4).map(|c| [c[0], c[1], c[2], c[3]]).collect()
+ })
+}
+
+#[cfg(test)]
+mod glass_energy_tests {
+ use super::*;
+
+ fn lambda(a2: f64, c: f64) -> f64 {
+ let c = c.abs().min(1.0);
+ 0.5 * (-1.0 + (1.0 + a2 * (1.0 - c * c) / (c * c)).sqrt())
+ }
+
+ /// The kernel's `dielectric_t`: the interface's transmission x |n.l| (Walter et al. 2007 eq. 21 from the view
+ /// side; n = +y, v above, l below).
+ fn transmitted(v: [f64; 3], l: [f64; 3], a2: f64, eta: f64) -> f64 {
+ let h = [v[0] + eta * l[0], v[1] + eta * l[1], v[2] + eta * l[2]];
+ let k = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt() * h[1].signum();
+ let h = [h[0] / k, h[1] / k, h[2] / k];
+ let (voh, loh) = (v[0] * h[0] + v[1] * h[1] + v[2] * h[2], l[0] * h[0] + l[1] * h[1] + l[2] * h[2]);
+ if voh <= 0.0 || loh >= 0.0 {
+ return 0.0;
+ }
+ let d = (h[1] * a2 - h[1]) * h[1] + 1.0;
+ let den = voh + eta * loh;
+ (1.0 - fresnel_dielectric(voh, eta)) * a2 / (std::f64::consts::PI * d * d) * voh * eta * eta * -loh / (v[1] * den * den * (1.0 + lambda(a2, v[1]) + lambda(a2, l[1])))
+ }
+
+ /// (R, T) of one interface toward a view at cosine `mu`: the BSDF's value x cosine integrated over the directions
+ /// of each side (`n` x 2 `n` points). What the kernel's light samples sum; the table's estimator is its sampling.
+ fn interface(mu: f64, alpha: f64, eta: f64, n: usize) -> (f64, f64) {
+ let a2 = alpha * alpha;
+ let v = [(1.0 - mu * mu).sqrt(), mu, 0.0];
+ let (mut r, mut t) = (0.0, 0.0);
+ for i in 0..n {
+ let c = (i as f64 + 0.5) / n as f64;
+ let st = (1.0 - c * c).sqrt();
+ for j in 0..2 * n {
+ let phi = std::f64::consts::PI * (j as f64 + 0.5) / n as f64;
+ let (x, z) = (st * phi.cos(), st * phi.sin());
+ // Reflection: D x the kernel's joint visibility x Fresnel at the half vector.
+ let h = [v[0] + x, v[1] + c, z];
+ let k = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt();
+ let (noh, voh) = (h[1] / k, (v[0] * h[0] + v[1] * h[1]) / k);
+ let d = (noh * a2 - noh) * noh + 1.0;
+ let vis = 0.5 / (c * (mu * (1.0 - alpha) + alpha) + mu * (c * (1.0 - alpha) + alpha)).max(1e-7);
+ r += a2 / (std::f64::consts::PI * d * d) * vis * fresnel_dielectric(voh, eta) * c;
+ t += transmitted(v, [x, -c, z], a2, eta);
+ }
+ }
+ let k = std::f64::consts::PI / (n * n) as f64;
+ (r * k, t * k)
+ }
+
+ /// The table's estimator against the BSDF's integral; the numbers the `glass/rough-*` render tests expect; the
+ /// table's cost.
+ #[test]
+ fn the_glass_energy_is_the_interfaces() {
+ for (r, eta, mu) in [(0.3, 1.5, 0.7071), (0.3, 1.0 / 1.5, 0.7071), (0.6, 1.5, 0.4), (0.6, 1.0 / 1.5, 0.9), (1.0, 1.5, 0.9), (1.0, 1.0 / 1.5, 0.9), (0.5, 1.33, 0.2), (0.8, 1.0 / 1.33, 0.5)] {
+ let (e, (qr, qt)) = (glass_energy(mu, r * r, eta, 24), interface(mu, r * r, eta, 700));
+ assert!((e - qr - qt).abs() < 0.012 * (qr + qt), "roughness {r}, eta {eta:.3}, cos {mu}: {e:.4} for {:.4}", qr + qt);
+ }
+ // tests/render/glass-rough-enter.ts, -leave.ts, -leave-low.ts (roughness 0.6, ior 1.5).
+ let c45 = std::f64::consts::FRAC_1_SQRT_2;
+ for (eta, mu, want) in [(1.5, c45, 0.9573), (1.0 / 1.5, c45, 0.7390), (1.0 / 1.5, 0.4, 0.6474)] {
+ let ((qr, qt), e) = (interface(mu, 0.36, eta, 1000), glass_energy(mu, 0.36, eta, 192));
+ eprintln!("eta {eta:.3}, cos {mu:.4}: R {qr:.4} + T {qt:.4} = {:.4}; by visible normals {e:.4}", qr + qt);
+ assert!((qr + qt - want).abs() < 1e-3 && (e - want).abs() < 5e-4, "eta {eta:.3}, cos {mu}: R {qr:.4} + T {qt:.4}, {e:.4} for {want}");
+ }
+ let t = std::time::Instant::now();
+ let lut = glass_energy_lut();
+ assert_eq!(lut.len() * 4, 2 * GLASS_E[0] * GLASS_E[1] * GLASS_E[2]);
+ assert!(lut.iter().flatten().all(|e| (0.05..=1.0).contains(e)));
+ eprintln!("glass energy table: {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+ }
+
+ /// tests/render/glass-rough-lamp.ts and -wide.ts: what a square emitter of side `side`, 1 m under a sheet of
+ /// glass (roughness 0.6, ior 1.5) where the 45-degree view's refracted ray arrives, sends through the sheet, as
+ /// a fraction of its radiance: `transmitted` integrated over the emitter's area.
+ #[test]
+ fn the_lamp_through_frosted_glass() {
+ let (a2, eta) = (0.6f64.powi(4), 1.5f64);
+ let c45 = std::f64::consts::FRAC_1_SQRT_2;
+ let v = [0.0, c45, c45];
+ // The refracted ray's foot 1 m down (the test's lamp is centred there: z = -0.5345).
+ let st = c45 / eta;
+ let cz = -st / (1.0 - st * st).sqrt();
+ assert!((cz + 0.5345).abs() < 1e-4);
+ for (side, want) in [(0.3, 0.40415), (1.0, 0.83641)] {
+ let n = 600;
+ let mut sum = 0.0;
+ for i in 0..n {
+ let x = ((i as f64 + 0.5) / n as f64 - 0.5) * side;
+ for j in 0..n {
+ let z = cz + ((j as f64 + 0.5) / n as f64 - 0.5) * side;
+ let d2 = x * x + 1.0 + z * z;
+ let d = d2.sqrt();
+ sum += transmitted(v, [x / d, -1.0 / d, z / d], a2, eta) / (d * d2);
+ }
+ }
+ let got = sum * (side / n as f64).powi(2);
+ assert!((got - want).abs() < 2e-4, "a {side} m lamp: {got:.5} for {want}");
+ }
+ }
+
+ /// Whether the table's nodes are enough: the kernel's lookup (pathtrace.wgsl `glass_energy`, trilinear over the
+ /// nodes; copied here) against the estimator between them.
+ #[test]
+ fn the_glass_energy_table_interpolates() {
+ let lut = glass_energy_lut();
+ let at = |i: usize| lut[i / 4][i % 4] as f64;
+ let [nm, nr, nz] = GLASS_E;
+ let look = |mu: f64, r: f64, ior: f64, leaving: bool| {
+ let x = (mu.sqrt() * (nm - 1) as f64).clamp(0.0, (nm - 1) as f64);
+ let y = (r * (nr - 1) as f64).clamp(0.0, (nr - 1) as f64);
+ let z = (((ior - 1.0).max(0.0) / (ior + 1.0)).sqrt() * (nz - 1) as f64 / GLASS_E_ZMAX).clamp(0.0, (nz - 1) as f64);
+ let (x0, y0, z0) = (x as usize, y as usize, z as usize);
+ let (x1, y1, z1) = ((x0 + 1).min(nm - 1), (y0 + 1).min(nr - 1), (z0 + 1).min(nz - 1));
+ let (fx, fy, fz) = (x - x0 as f64, y - y0 as f64, z - z0 as f64);
+ let plane = |zi: usize| {
+ let b = (if leaving { nz } else { 0 } + zi) * nr * nm;
+ let row = |yi: usize| at(b + yi * nm + x0) * (1.0 - fx) + at(b + yi * nm + x1) * fx;
+ row(y0) * (1.0 - fy) + row(y1) * fy
+ };
+ plane(z0) * (1.0 - fz) + plane(z1) * fz
+ };
+ let (mut worst, mut sum, mut n) = ((0.0f64, String::new()), 0.0, 0);
+ for leaving in [false, true] {
+ for ior in [1.2, 1.33, 1.5, 1.8, 2.4] {
+ for ri in 0..12 {
+ let r = 0.08 + ri as f64 * 0.08;
+ for mi in 0..24 {
+ let mu = 0.02 + mi as f64 * 0.0408;
+ let (t, e) = (look(mu, r, ior, leaving), glass_energy(mu, r * r, if leaving { 1.0 / ior } else { ior }, 48));
+ let d = (t - e).abs() / e;
+ sum += d;
+ n += 1;
+ if d > worst.0 {
+ worst = (d, format!("ior {ior} r {r:.2} mu {mu:.3} leaving {leaving}: table {t:.4}, direct {e:.4}"));
+ }
+ }
+ }
+ }
+ }
+ eprintln!("glass energy table against the estimator: mean {:.4}, worst {:.4} ({})", sum / n as f64, worst.0, worst.1);
+ assert!(sum / (n as f64) < 0.01 && worst.0 < 0.05, "mean {:.4}, worst {:.4} ({})", sum / n as f64, worst.0, worst.1);
+ }
+}
+
#[cfg(test)]
mod light_lod_tests {
use super::*;
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index c2b5714..d626fe1 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -194,7 +194,15 @@ mod tests {
assert!(kernel_template().contains(&format!("const {constant}: u32 = {}u;", bytes / 16)), "{constant}");
assert_eq!(layout(&m, name).1 as usize, bytes, "{name}");
}
- assert_eq!(<Table as crate::heap::Section>::COUNT, Table::Energy as usize + 1);
+ assert_eq!(<Table as crate::heap::Section>::COUNT, Table::GlassEnergy as usize + 1);
+ // The glass energy table's nodes.
+ let [mu, rough, ior] = crate::GLASS_E;
+ for (name, n) in [("GLASS_E_MU", mu), ("GLASS_E_ROUGH", rough), ("GLASS_E_IOR", ior)] {
+ assert!(kernel_template().contains(&format!("const {name}: u32 = {n}u;")), "{name}");
+ }
+ assert!(kernel_template().contains(&format!("const GLASS_E_ZMAX: f32 = {:.8};", crate::GLASS_E_ZMAX)));
+ assert!(kernel_template().contains("fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }"));
+ assert_eq!(Table::GlassEnergy as usize, 2 * 4 + 2, "`table_first[2].z`");
assert!(kernel_template().contains(&format!("const CACHE_SIZE: u32 = {}u;", crate::gpu::CACHE_SIZE)));
// `finish`'s records and its dispatch rows.
assert!(kernel_template().contains(&format!("const DEFERRED_VECS: u32 = {}u;", crate::gpu::DEFERRED_BYTES / 16)));
diff --git a/tests/render/glass-internal-reflection.ts b/tests/render/glass-internal-reflection.ts
new file mode 100644
index 0000000..c265c64
--- /dev/null
+++ b/tests/render/glass-internal-reflection.ts
@@ -0,0 +1,12 @@
+// Total internal reflection is not tinted: a smooth sheet of grey glass (base colour 0.5) seen from inside at 45
+// degrees, past the critical angle (41.8), reflects the whole sky: 1. The tint is for light that crosses the surface.
+// (Until 2026-11-16 the reflected ray carried the transmission lobe's weight: 0.5.)
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/internal-reflection", features: ["transmission", "refraction"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 1, tolerance: 0.02 },
+};
+
+export default () => sheet({ roughness: 0, leaving: true, color: 0.5 });
diff --git a/tests/render/glass-rough-enter-compensated.ts b/tests/render/glass-rough-enter-compensated.ts
new file mode 100644
index 0000000..8b8d419
--- /dev/null
+++ b/tests/render/glass-rough-enter-compensated.ts
@@ -0,0 +1,12 @@
+// glass/rough-enter with energy compensation: the interface's single scattering is scaled by 1 / (R + T) from the
+// glass energy table (Turquin 2019), so nothing is lost: 1.
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-enter-compensated", features: ["transmission", "refraction", "ggx", "energy-conservation"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 1, tolerance: 0.02 },
+ spp: 256,
+};
+
+export default () => sheet({ roughness: 0.6, compensation: 1 });
diff --git a/tests/render/glass-rough-enter.ts b/tests/render/glass-rough-enter.ts
new file mode 100644
index 0000000..5c18e38
--- /dev/null
+++ b/tests/render/glass-rough-enter.ts
@@ -0,0 +1,26 @@
+// One rough dielectric interface in a white furnace: a single sheet of glass (ior 1.5, roughness 0.6; the far side
+// stays glass) in a uniform sky of radiance 1, seen at 45 degrees from the air. Without energy compensation the pixel
+// reads what one interface reflects and transmits by single scattering: R 0.037 + T 0.920 = 0.9573, the BSDF
+// (Walter et al. 2007, GGX) integrated over both sides' directions and, apart, summed over visible microfacet
+// normals (renderer/src/lib.rs `glass_energy_tests`). The sky is sampled on both sides of the sheet, so the BSDF's
+// value, its density and its sampling are held to each other.
+import { Color, Mesh, MeshPhysicalMaterial, PlaneGeometry, type Object3D } from "@threert/scene";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-enter", features: ["transmission", "refraction", "ggx"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 0.9573, tolerance: 0.015 },
+ spp: 256,
+};
+
+/** The sheet (its normal up; `leaving`: down, so the camera sees it from inside the glass), seen from above at `cos`. */
+export function sheet(o: { roughness: number; leaving?: boolean; cos?: number; sky?: number; color?: number; compensation?: number }, extra: Object3D[] = []) {
+ const scene = sceneWithSky(o.sky ?? 1);
+ const c = o.color ?? 1;
+ const glass = new Mesh(new PlaneGeometry(200, 200), new MeshPhysicalMaterial({ color: new Color().setRGB(c, c, c), transmission: 1, ior: 1.5, roughness: o.roughness, metalness: 0 }));
+ glass.rotation.x = o.leaving ? Math.PI / 2 : -Math.PI / 2;
+ const cos = o.cos ?? Math.SQRT1_2;
+ return result(scene, camera(scene, [0, 3 * cos, 3 * Math.sqrt(1 - cos * cos)], [0, 0, 0], 5), [glass, ...extra], { energyCompensation: o.compensation ?? 0 });
+}
+
+export default () => sheet({ roughness: 0.6 });
diff --git a/tests/render/glass-rough-lamp-wide.ts b/tests/render/glass-rough-lamp-wide.ts
new file mode 100644
index 0000000..fd6d18f
--- /dev/null
+++ b/tests/render/glass-rough-lamp-wide.ts
@@ -0,0 +1,13 @@
+// glass/rough-lamp with a 1 m square: most of the lobe ends on it, 0.836 of its radiance, and the BSDF's own rays
+// find it as often as its light samples do.
+import { sheet } from "./glass-rough-enter.ts";
+import { lamp } from "./glass-rough-lamp.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-lamp-wide", features: ["transmission", "refraction", "ggx", "emissive"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 8.3641, tolerance: 0.02 },
+ spp: 256,
+};
+
+export default () => sheet({ roughness: 0.6, sky: 0 }, [lamp(1)]);
diff --git a/tests/render/glass-rough-lamp.ts b/tests/render/glass-rough-lamp.ts
new file mode 100644
index 0000000..3869174
--- /dev/null
+++ b/tests/render/glass-rough-lamp.ts
@@ -0,0 +1,23 @@
+// A lamp seen through frosted glass: under glass/rough-enter's sheet (roughness 0.6, no sky) a 0.3 m square of
+// radiance 10 lies 1 m below, where the view's refracted ray arrives. The pixel reads the BTDF integrated over the
+// square, 0.404 of the lamp's radiance (Walter et al. 2007 eq. 21 from the view side; lib.rs
+// `the_lamp_through_frosted_glass`). A lamp this small is found by its light samples: their shadow rays start on
+// the sheet's far side.
+import { Color, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-lamp", features: ["transmission", "refraction", "ggx", "emissive"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 4.0415, tolerance: 0.02 },
+ spp: 256,
+};
+
+export function lamp(side: number): Mesh {
+ const m = new Mesh(new PlaneGeometry(side, side), new MeshStandardMaterial({ color: 0x000000, emissive: new Color().setRGB(1, 1, 1), emissiveIntensity: 10 }));
+ m.rotation.x = -Math.PI / 2;
+ m.position.set(0, -1, -0.5345);
+ return m;
+}
+
+export default () => sheet({ roughness: 0.6, sky: 0 }, [lamp(0.3)]);
diff --git a/tests/render/glass-rough-leave-compensated-live.ts b/tests/render/glass-rough-leave-compensated-live.ts
new file mode 100644
index 0000000..1b4c676
--- /dev/null
+++ b/tests/render/glass-rough-leave-compensated-live.ts
@@ -0,0 +1,7 @@
+// glass/rough-leave-compensated in the real-time renderer.
+import def, { test as base } from "./glass-rough-leave-compensated.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "glass/rough-leave-compensated-live", metric: { ...base.metric, tolerance: 0.03 } as TestMeta["metric"], temporal: true, live: 120 };
+
+export default def;
diff --git a/tests/render/glass-rough-leave-compensated.ts b/tests/render/glass-rough-leave-compensated.ts
new file mode 100644
index 0000000..fd1b487
--- /dev/null
+++ b/tests/render/glass-rough-leave-compensated.ts
@@ -0,0 +1,11 @@
+// glass/rough-leave with energy compensation: 0.739 by single scattering, 1 with it.
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-leave-compensated", features: ["transmission", "refraction", "ggx", "energy-conservation"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 1, tolerance: 0.02 },
+ spp: 256,
+};
+
+export default () => sheet({ roughness: 0.6, leaving: true, compensation: 1 });
diff --git a/tests/render/glass-rough-leave-low.ts b/tests/render/glass-rough-leave-low.ts
new file mode 100644
index 0000000..8617911
--- /dev/null
+++ b/tests/render/glass-rough-leave-low.ts
@@ -0,0 +1,11 @@
+// glass/rough-leave at a cosine of 0.4 (66 degrees from the normal): R 0.531 + T 0.116 = 0.6474.
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-leave-low", features: ["transmission", "refraction", "ggx"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 0.6474, tolerance: 0.015 },
+ spp: 256,
+};
+
+export default () => sheet({ roughness: 0.6, leaving: true, cos: 0.4 });
diff --git a/tests/render/glass-rough-leave.ts b/tests/render/glass-rough-leave.ts
new file mode 100644
index 0000000..43e10f1
--- /dev/null
+++ b/tests/render/glass-rough-leave.ts
@@ -0,0 +1,14 @@
+// glass/rough-enter from inside the glass (the sheet's back toward the camera, relative index 1 / 1.5): at 45 degrees,
+// past the critical angle of smooth glass, the rough interface reflects 0.367 and transmits 0.372 by single
+// scattering: 0.739 (lib.rs `glass_energy_tests`). Total internal reflection is reflection at the microfacet, by
+// its Fresnel reflectance.
+import { sheet } from "./glass-rough-enter.ts";
+import { CENTER, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-leave", features: ["transmission", "refraction", "ggx"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 0.739, tolerance: 0.015 },
+ spp: 256,
+};
+
+export default () => sheet({ roughness: 0.6, leaving: true });
diff --git a/tests/render/glass-rough-sphere-furnace.ts b/tests/render/glass-rough-sphere-furnace.ts
new file mode 100644
index 0000000..1d1cb60
--- /dev/null
+++ b/tests/render/glass-rough-sphere-furnace.ts
@@ -0,0 +1,17 @@
+// White furnace, frosted glass: a closed sphere (ior 1.5, roughness 0.5) in a uniform sky of radiance 1, with energy
+// compensation. Each interface returns all it receives, entering and leaving, and the light samples blocked by the
+// sphere's far wall are the refracted paths' to find: 1. (Single scattering alone loses a quarter at each leaving.)
+import { Color, Mesh, MeshPhysicalMaterial, SphereGeometry } from "@threert/scene";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "glass/rough-sphere-furnace", features: ["transmission", "refraction", "ggx", "energy-conservation"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 1, tolerance: 0.02 },
+ spp: 256,
+};
+
+export default function () {
+ const scene = sceneWithSky(1);
+ const s = new Mesh(new SphereGeometry(0.5, 64, 48), new MeshPhysicalMaterial({ color: new Color().setRGB(1, 1, 1), transmission: 1, ior: 1.5, roughness: 0.5, metalness: 0 }));
+ return result(scene, camera(scene, [0, 0, 3], [0, 0, 0]), [s], { maxBounces: 64, energyCompensation: 1 });
+}
diff --git a/tools/bench-window.ts b/tools/bench-window.ts
index 6499de7..982e80d 100644
--- a/tools/bench-window.ts
+++ b/tools/bench-window.ts
@@ -1,10 +1,11 @@
// The play window's picture against what it should be, in the shots the window's quality work of 2026-11 was measured
// by (docs/ROADMAP.md § 1a). Each shot bundles its game, drives one headless live session in lockstep and compares
-// its frames with an offline render of the same moment (rendered once and kept: out/cache/window-truth, keyed by the
-// bundle and the shot; --fresh-truth renders them again), or, for the dusk, with the same moment held.
+// its frames with an offline render of the same moment by the same renderer (rendered once and kept:
+// out/cache/window-truth, keyed by the renderer's binary, the bundle and the shot; --fresh-truth renders them again),
+// or, for the dusk, with the same moment held.
//
-// node tools/bench-window.ts [--shots still-bistro,still-kabukicho,still-rooms,still-rooms-wide,rooms-turn,slice,
-// tokyo-dusk,tokyo-turn,tokyo-orbit]
+// node tools/bench-window.ts [--shots still-bistro,still-kabukicho,still-rooms,still-rooms-wide,still-glass,
+// rooms-turn,slice,tokyo-dusk,tokyo-turn,tokyo-orbit]
// [--tag NAME] [--fresh-truth]
//
// Shots (the bin is THREERT_BIN, else the release build):
@@ -15,6 +16,8 @@
// lamps, most behind walls; scale 0.5; offline at 4096 samples): where a light sampler has to find the lamps a
// point can see, and what its noise does as they multiply. (The offline render chooses among the lamps
// uniformly: with 768 its 4096 samples are still noisy, a floor under every reading of the wide shot.)
+// still-glass the same for scenes/khronos-transmission.ts (clear and frosted glass, thin and solid, before a
+// pattern; scale 0.5).
// rooms-turn lamp-rooms-wide, the camera turning 2 degrees a frame for 24 frames into the scene's view, then still:
// the last moving frame and 1, 6, 30 and 150 frames after it against the same offline render.
// slice the Bistro slice half a second after its explosion (40.5 s, from the start in lockstep, scale 0.375, 1440p):
@@ -29,7 +32,7 @@
// Output: out/bench-window/<tag>/<shot>/*.png, out/bench-window/<tag>/metrics.json, and a table.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import sharp from "sharp";
import { bundleGame } from "./bundle-game.ts";
@@ -38,7 +41,7 @@ import { startLive, type Build, type Live } from "./lib/live.ts";
const args = process.argv.slice(2);
const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);
-const ALL = ["still-bistro", "still-kabukicho", "still-rooms", "still-rooms-wide", "rooms-turn", "slice", "tokyo-dusk", "tokyo-turn", "tokyo-orbit"];
+const ALL = ["still-bistro", "still-kabukicho", "still-rooms", "still-rooms-wide", "still-glass", "rooms-turn", "slice", "tokyo-dusk", "tokyo-turn", "tokyo-orbit"];
const shots = flag("--shots", ALL.join(",")).split(",");
const tag = flag("--tag", new Date().toISOString().replace(/[:.]/g, "-"));
const freshTruth = args.includes("--fresh-truth");
@@ -56,9 +59,11 @@ async function bundle(src: string): Promise<string> {
return bundles.get(src)!;
}
-/** The offline render of a bundle at these settings, rendered once (keyed by the bundle and the settings). */
+/** The offline render of a bundle at these settings, rendered once (keyed by the renderer, the bundle and the
+ * settings: a build that changes the offline picture is held to its own, not to one kept from before it). */
+const binKey = createHash("sha256").update(readFileSync(rendererBin)).digest("hex");
function truth(b: string, o: { width: number; height: number; spp: number; time?: number; room?: string; camera?: { position: number[]; target: number[]; fov: number } }): string {
- const key = createHash("sha256").update(readFileSync(b)).update(JSON.stringify(o)).digest("hex").slice(0, 20);
+ const key = createHash("sha256").update(binKey).update(readFileSync(b)).update(JSON.stringify(o)).digest("hex").slice(0, 20);
const path = join(repoRoot, "out/cache/window-truth", `${key}.png`);
if (existsSync(path) && !freshTruth) return path;
mkdirSync(join(repoRoot, "out/cache/window-truth"), { recursive: true });
@@ -120,6 +125,7 @@ async function still(name: string, src: string, scale: string, env: Record<strin
mkdirSync(dir, { recursive: true });
const b = await bundle(src);
const ref = truth(b, { width: 2560, height: 1440, spp });
+ copyFileSync(ref, join(dir, "ref.png"));
const live = await session(b, { width: 2560, height: 1440, scale, env: { THREERT_FREEZE_TIME: "1", ...env } });
const [a, c] = [join(dir, "a.png"), join(dir, "b.png")];
await frames(live, 300, a);
@@ -239,6 +245,7 @@ for (const s of shots) {
else if (s === "still-kabukicho") await still(s, "games/kabukicho/kabukicho.game.ts", "0.375", { THREERT_NO_GRAIN: "1" });
else if (s === "still-rooms") await still(s, "scenes/lamp-rooms.ts", "0.5", {}, 4096);
else if (s === "still-rooms-wide") await still(s, "scenes/lamp-rooms-wide.ts", "0.5", {}, 4096);
+ else if (s === "still-glass") await still(s, "scenes/khronos-transmission.ts", "0.5", {});
else if (s === "rooms-turn") await roomsTurn(s);
else if (s === "slice") await slice();
else if (s === "tokyo-dusk") await tokyoDusk();