The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
A cutout's map answers an emitter's shadow ray (#304)
YX1296b99ab739
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 48b328e..a40c142 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -728,8 +728,6 @@ Earlier direction (2026-11-05, kept for the history below): finish the three.js- Carried over from the dynamic phase (taken up when they block a step, or between steps):- live quality in motion: the crowd's ΔE at 10 s is 10.4 against static Bistro's 5.8, and the vans' roofs stillsparkle;- - the unbiased replacement for the foliage-shadow bias (an opacity micromap, or emitter shadow rays compacted into a- pass of their own);- the perf suite's first-frame recheck (alternate the two builds before reporting a first-frame regression).### History: the dynamic content phase (2026-11-08 → 2026-11-09)@@ -1066,6 +1064,7 @@ What is left is carried over in § 0. The phase's plan and results, as they were- an opacity micromap: per masked triangle, cells known opaque or transparent skip the texture and mixedones test it;- or the cutout continuation rays compacted into a pass of their own.+ - (Done 2026-12-02 by the first, in one query: "A cutout's map answers an emitter's shadow ray", below.)- The specular filters' luminance edge stop, widened (2026-11-09, branch `spec-edge`): it weighed each tap by itsdistance from the local mean at 2 x strength, so a sparse bright reflection was kept out of its neighbours'means and, as a centre far from its own mean, out of its own: its energy was lost, not spread. At 8 x:@@ -2543,6 +2542,67 @@ up over a history's length (the bounds on a moving history's length, `moving_fraNot done: the bounds on a moving history's length were set for the bilinear tap's blur and are as they were. Notchecked on Vulkan, nor in a browser.+**A cutout's map answers an emitter's shadow ray (2026-12-02, after it).** The entry before the last found Bistro's+potted bushes and its hedge at 0.78 and 0.71 of the offline render's light, moving or held: to an emitter's shadow ray+a cutout was a whole card (`A_CUTOUT_EMITTERS`, a trade of 2026-11-09). With their alpha tested they read 0.97 and+0.99, for 18 % more of the frame at the street's first view and 24 % over its walk (an M4 at half resolution, as+every figure here).++Where that cost lies. Bistro has 285,355 cutout triangles, a tenth of the scene; 3,195 of them have texture+coordinates of their own (a few sprites, placed thousands of times). Their longest edge is 2,200 texels in the median+and three fifths of their area is hole: whole branches on a card. A shadow ray through a crown crosses dozens of+cards, mostly through their holes, and on the hardware path each hole is a new query from where the last one ended.+Two measurements said otherwise before they were understood. A coin in place of the alpha's reads, the stepping kept,+cost a fifth to a third of the test: but a coin stops a ray at its second or third card, which a real card's holes do+not. And one query with the alpha tested in its candidate loop had saved nothing on 2026-11-16 (docs/RUNTIME.md). With+maps in place of the reads and the stepping kept, the frame cost what the test costs (18.3 and 20.8 ms for 18.2 and+20.6). Both have to go: the reads and the queries.++- The maps (renderer/src/cutout.rs). A cutout's triangle is laid over with a lattice of cells about two texels of+ its base texture wide, 4^7 at most (Bistro's cards: cells of 17 texels), and a cell's state is two bits: nothing+ there, all there, or a part with which is the larger. They are made where the scene is prepared, in parallel;+ triangles with the same texture coordinates and material share one. Bistro's are 7.8 MB of the words' heap and+ its preparation takes what it took (1.5 s); Zero-Day's 126,600 cutout triangles, most of them whole, 2.0 MB.+- A part cell's larger part is found at nine points inside it. By the six points that say whether a cell is whole+ (its corners and its edges' middles), three of six counting as solid, a disc's cells came to 2 % more than its+ area and Bistro's foliage read 0.7 to 1.2 % darker offline than by the alpha test; by the nine, 0.9999 and 0.9994+ of it (six levels: 0.9993 and 0.9980; eight: 1.0001 and 0.9997).+- Hardware traversal. The sections that have maps are not flagged opaque. Every other ray forces opacity, as all did;+ an emitter's shadow ray at a camera hit does not, is handed each of those triangles in its one query, and confirms+ it or passes it by its map: its instance's record and three words, no corner, no material, no texture, no second+ query. The candidate loop had lost hits on Metal when every ray's cutouts went through it with their alpha tested+ (0.1 % of rays near foliage, differently from run to run). In this form: two offline renders of Bistro's walk, 64+ samples, every emitter ray by the maps, differ in 2 of 921,600 pixels (with the alpha tested and stepped, 32), and+ from the same rays stepped in order in 0.19 % of the pixels, their mean within 1e-5.+- Software traversal asks the map where it tested the alpha (`shadow/cutout-emitter-live` and `-side-live` pass+ under it).+- Edits. A material or a texture changed in place drops the maps of the rows drawn with it: the cutout is then+ opaque to these rays, as before the maps, until the scene is prepared again. An instance placed at run time takes+ its mesh's.+- Measured. The bushes and the hedge beside the walk, the kernel's samples against offline: 0.966 and 0.992, which+ is what the alpha test reads there (0.966, 0.992). In the walking frame the upscaled picture there has 0.91 and+ 0.99 of the offline one's light for 0.73 and 0.70. The frame, three alternated runs: the street's first view+ 15.4-15.5 → 16.0-16.1 ms, the walk 16.7-16.9 → 17.9-18.1 (with the alpha tested 18.2 and 20.6). Bistro's+ recording against offline renders of the same instants: ΔE standing still 2.15 → 2.05, mid-strafe 3.18 → 3.11, at+ the stop 3.60 → 3.52, walking 3.86 → 3.77, 3.98 → 3.73 and 4.79 → 4.64; the darkest tenth of the frame six seconds+ into the walk 0.86 → 0.97 of the offline light. `bench-object-ghosting` and `bench-ghosting --quick --check` as+ they were. Three clips: a night street with its crowd ΔE 3.41 → 3.34 and 4.3 % more of its frame (9.74 → 10.16+ ms); the hall and the room of lamps the same. Twelve clips against offline: that street ΔE 3.41 → 3.34 with 4.5 %+ more of its frame, the others within 0.01 and within 2 % of their frame time; scenes are prepared in the time they+ took (the hall 1.8 s, a city of 23 million triangles 11 s).+- Render tests: `shadow/cutout-emitter-live` (a card cut out everywhere under an emissive panel: the offline value;+ it read 0.0007 before) and `shadow/cutout-emitter-side`, `-side-live` (a card solid on one side: which side is+ which). Unit suite 296, render suite 276.++Not done. The rays of deeper vertices still take a cutout as a card (`A_CUTOUT_PATHS`), and the analytic lights' and+the sky's shadow rays at a camera hit still test the alpha and step: both could go by the maps. A cell is found to be+a part by six points: where the levels' limit makes a cell wide (17 texels on Bistro's cards) a twig thinner than the+points' spacing can leave its cell whole or empty. The light is the alpha test's all the same (0.9999 and 0.9994+above); to decide every cell exactly is work at the rate of the texture's texels, for a bake that does not hold up the+scene's preparation. In the same walking frame the upper middle of the picture, whose light is its lamps and its+string of lights, has 0.67 of the offline light after the upscaler in both builds: small bright things lose light+there while the camera moves, and their glow with it. Not checked on Vulkan, nor in a browser.+**The live passes from one place (2026-11-14, after it).** A buffer and a pass more (the locks' carry, above) tookseven edits that had to agree: the declaration in live.wgsl, the bind group layout's entries, the pass list, thebuffers' sizes and order, the bind group's entries, the dispatch grid (in two copies), and the merged layout's table.diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 3fa7bac..adf1235 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1759,11 +1759,14 @@ view, the way to hold a live picture to the offline one).| 1 `A_GLASS_SHADOWS` | shadow rays to the analytic lights and the sky pass glass in full, untinted | light under tinted glass 4.3 x (`shadow/glass-tint`) | a glass scene +34 % (khronos-transmission 5.20 -> 6.97 ms) || 2 `A_MEDIA_SHADOWS` | only homogeneous media dim shadow rays: smoke and fire cast no shadow | light behind optical depth 1: e x (`shadow/medium`) | the Bistro slice +0.84 ms (9 %), the fire scene +0.10 || 4 `A_CUTOUT_PATHS` | cutouts are opaque to rays past a camera hit's own, off mirror paths | a camera hit's own light is whole (`sky/cutout-clear-live`: its samples take the share those rays cannot bring, `light_mis`); what a cutout lights sends nothing on (`sky/cutout-bounce`: black) | Bistro +1.63 ms of 8.54 |-| 8 `A_CUTOUT_EMITTERS` | cutouts are opaque to emitters' shadow rays | an emitter behind a clear card: black (`shadow/cutout-emitter`) | Bistro +1.35 ms |+| 8 `A_CUTOUT_EMITTERS` | at a camera hit, emitters' shadow rays ask a cutout's map (its triangles' cells, solid or hole, made once from its alpha: renderer/src/cutout.rs) in one query and read no texture; a cutout without maps is opaque to them | a camera hit's light past a cutout is whole (`shadow/cutout-emitter-live`, `shadow/cutout-emitter-side-live`); a cell is two texels wide, sixteen on Bistro's widest cards, and offline by the maps its foliage reads 0.9999 and 0.9994 of the light the alpha test gives | Bistro's frame +14 % (16.0 -> 18.2 ms at the street's first view, 17.9 -> 20.6 over its walk) || 16 `A_FAR_EMITTERS` | the light tree proposes no emitter beyond 120 m; without a tree, the emitter cull (60 m, 120 m in view) | panels 150 m up: 3 % of their light (`light/emitter-far`); Kabukichō's and Tokyo's shots unchanged | Tokyo from the air 4.7 -> 9.2 ms; the 3 x 3 district +0.15 |Measured 2026-11-15 and 16 with the loop guard on. Bistro held still, ΔE against the offline render: 1.82 asshipped, 1.66 without the two cutout bits (+3.5 ms; Zero Day, with few cutouts, +0.3).+The emitters' row is of 2026-12-02 (an M4 at half resolution). Until then every cutout was opaque to those rays: an+emitter behind a clear card read black, and beside Bistro's potted bushes and its hedge the picture had 0.78 and 0.71+of the offline render's light for 0.97 and 0.99.Two more were removed that day: a single-query shadow ray past cutouts (it saved nothing: Bistro 10.13 ms with it,10.09 without, Tokyo +0.05) and the switch for the sampler below.diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 6eff489..34541ca 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -30,7 +30,8 @@ const TRI_NO_SHADOW: u32 = 1u;const TRACE_CLOSEST: u32 = 0u;const TRACE_SHADOW: u32 = 1u;const TRACE_ANY: u32 = 2u;-// Any hit on any surface, alpha-cutout triangles taken as opaque (live emitter shadow rays: `emitter_tr`).+// Any hit on any surface, an alpha-cutout's triangles by their maps, with no read of their texture (live emitter+// shadow rays: `emitter_tr`; one without a map is opaque).const TRACE_ANY_OPAQUE: u32 = 3u;const TRI_MASKED: u32 = 2u;// Highest texture-page mip (texpack::MIPS - 1) and the ray-cone LOD bias (negative = sharper; accumulation antialiases).@@ -62,7 +63,7 @@ override APPROX: u32 = 0u;const A_GLASS_SHADOWS: u32 = 1u; // shadow rays to the analytic lights and the sky pass glass in full, untinted (`shadow_tr`)const A_MEDIA_SHADOWS: u32 = 2u; // of the media only the homogeneous ones dim shadow rays (`media_shadows`)const A_CUTOUT_PATHS: u32 = 4u; // cutouts are opaque to rays past a camera hit's own, off mirror paths (`cutouts_opaque`)-const A_CUTOUT_EMITTERS: u32 = 8u; // cutouts are opaque to emitters' shadow rays (`emitter_tr`)+const A_CUTOUT_EMITTERS: u32 = 8u; // emitters' shadow rays ask a cutout's map and read no texture; one without maps is opaque to them (`emitter_tr`)const A_FAR_EMITTERS: u32 = 16u; // the light tree proposes no emitter beyond LT_FAR (`lt_imp`; without a tree: the emitter cull)fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.@@ -123,7 +124,7 @@ struct Params {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, uptable_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, emitter triangles- word_first: array<vec4<u32>, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows+ word_first: array<vec4<u32>, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows; the triangles' indices, the cutouts' mapslive_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, first hits, (the first hits' vec4s), -live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists};@@ -304,6 +305,38 @@ const ROW_GLASS: u32 = 0x2000000u;const NO_EMITTER: u32 = 0xffffffffu;fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first[0].w + (first + section) * 4u + k]; }+// A cutout's map (cutout.rs): whether a point of one of its triangles is solid or a hole, for a ray that only asks+// whether something stands in its way, without the triangle's corners, its material or its texture. A stream of the+// words (`P.word_first[1].y`): a word a triangle of the section, from where its instance's row says (its last word,+// above its lowest bit, plus one), then the triangles' lattices of cells, two bits a cell.+const CUTOUT_NO_MAP: u32 = 0u;+const CUTOUT_NOTHING: u32 = 14u;+const CUTOUT_WHOLE: u32 = 15u;+// The cell of a lattice of n cells an edge that the point (u, v) lies in (cutout.rs `cell_of`, the same).+fn cutout_cell(u: f32, v: f32, n: u32) -> u32 {+ let x = clamp(u, 0.0, 1.0) * f32(n);+ let y = clamp(v, 0.0, 1.0) * f32(n);+ let j = min(u32(y), n - 1u);+ let i = min(u32(x), n - 1u - j);+ let across = (x - f32(i)) + (y - f32(j)) > 1.0 && i + j + 1u < n;+ return j * (2u * n - j) + 2u * i + u32(across);+}+// What the map says of the point (u, v) of triangle `rank` of section `part` of an instance whose rows begin at+// `rows`: 1 solid, 0 a hole, -1 the section has no map (a material whose function may change its opacity, a+// section an edit made). A cell that is a part of both counts as the larger part (its state's low bit).+fn cutout_mapped(rows: u32, part: u32, rank: u32, u: f32, v: f32) -> i32 {+ let run = row_word(rows, part, 3u) >> 1u;+ if (run == 0u) { return -1; }+ let first = P.word_first[1].y;+ let w = words[first + run - 1u + rank];+ let tag = w & 15u;+ if (tag == CUTOUT_WHOLE) { return 1; }+ if (tag == CUTOUT_NOTHING) { return 0; }+ if (tag == CUTOUT_NO_MAP) { return -1; }+ let k = cutout_cell(u, v, 1u << tag);+ return i32((words[first + (w >> 4u) + (k >> 4u)] >> ((k & 15u) * 2u)) & 1u);+}+// The material of a triangle, given its attributes and the instance that places it. Every read of a hit's material// goes through here: where the material is kept is this function's alone. In the row of the triangle's section,// which its instance has.@@ -1056,13 +1089,18 @@ fn media_shadows() -> bool { return (!approx(A_MEDIA_SHADOWS) || media_voxels) &// emitters (their MIS partner; a pass-through here counted light that no path can reach, and more of it the larger// the emitter's sampling share). UE's path tracer, too, reaches emissive surfaces only through rays that every mesh// blocks.-// Shadow ray to an emitter sample (any surface blocks). A_CUTOUT_EMITTERS: alpha-cutout triangles are opaque to it at camera hits too-// (deeper vertices take them as opaque anyway, `cutouts_opaque`): the leaves of a tree block as whole cards. A bias,-// accepted by the user on 2026-11-09 to bring the Bistro crowd within its 60 fps budget: the alpha tests of these rays-// were ~0.9 ms of the frame (crowd GPU p50 15.06 -> 14.16 ms, frame start p95 17.14 -> 16.67 ms), and cost the live-// image under foliage ~1.7 % of its light (static Bistro at 25 s along its path; layer B Bistro ΔE 3.23 -> 3.30).-// Removing the bias without the cost (an opacity micromap, or these rays compacted into a pass of their own) is a-// follow-up item (ROADMAP § 0). Offline rendering always tests.+// Shadow ray to an emitter sample (any surface blocks). A_CUTOUT_EMITTERS: at a camera hit it asks an alpha-cutout's+// triangles of their maps (cutout.rs: a lattice of cells a triangle, each solid or a hole, made once from the+// texture's alpha), in the one query it is: no read of a triangle's corners, its material or its texture, and no+// second query past a hole (trace_hw.wgsl). A cutout without maps is opaque to it, as every cutout is to the rays of+// deeper vertices (`cutouts_opaque`). Offline rendering always tests the alpha.+// Until 2026-12-02 every cutout was opaque to these rays at camera hits too, the leaves of a tree blocking as whole+// cards: a bias accepted on 2026-11-09 for the Bistro crowd's 60 fps (the alpha tests of these rays were ~0.9 ms of+// its frame), measured then at ~1.7 % of the light under foliage at one pose. Beside the potted bushes and the hedge+// of Bistro's walk it was more: 0.78 and 0.71 of the offline render's light there (an M4 at half resolution), and+// by the maps 0.97 and 0.99, which is what the alpha test itself reads. The frame at the street's first view and+// over the walk: 15.5 and 16.8 ms as it was, 16.0 and 17.9 by the maps, 18.2 and 20.6 with the alpha tested, each+// hole then passed by a query of its own (Bistro's leaf cards are 2,200 texels across and three fifths hole).fn emitter_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> f32 {shadow_hole = false;if (trace(o, d, tmax, select(TRACE_ANY, TRACE_ANY_OPAQUE, approx(A_CUTOUT_EMITTERS))).tri != 0xffffffffu) { return 0.0; }diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgslindex c004c7b..2e32faf 100644--- a/renderer/shaders/trace_hw.wgsl+++ b/renderer/shaders/trace_hw.wgsl@@ -1,7 +1,8 @@// Hardware ray tracing (wgpu ray query). A TLAS instance a model instance or a procedural object: shadow casters// mask 1, the rest mask 2 (glass among them; an instance's glass among its other sections is stepped through by its-// row). Every geometry is flagged opaque: none reports candidates, and a cutout's hit is confirmed by `alpha_pass`.-// instance_custom_data holds the instance's record.+// row). Every query forces opacity and a cutout's hit is confirmed by `alpha_pass`, but for a ray that goes by the+// cutouts' maps (cutout.rs): the sections that have maps are not flagged opaque, and that ray is handed their+// triangles one by one. instance_custom_data holds the instance's record.@if(hwrt) @group(0) @binding(19) var acc: acceleration_structure;@if(hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {@@ -11,11 +12,22 @@let any = mode != TRACE_CLOSEST;// (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both. Glass among an// instance's other sections is stepped through as a cutout is: `passes`.)- if (!has(F_MASKED) && !has(F_IGLASS)) { return trace_opaque(o, d, tmax_in, mask, any); }- // Whether a cutout stops this ray as any triangle does: A_CUTOUT_PATHS, A_CUTOUT_EMITTERS (TRACE_ANY_OPAQUE)- // (pathtrace.wgsl `cutouts_opaque`, `emitter_tr`).- @if(!cutout_lite) let solid = cutouts_opaque() || mode == TRACE_ANY_OPAQUE;+ if (!has(F_MASKED) && !has(F_IGLASS)) { return trace_opaque(o, d, tmax_in, mask, any, false); }+ // Whether a cutout stops this ray as any triangle does: A_CUTOUT_PATHS (pathtrace.wgsl `cutouts_opaque`).+ @if(!cutout_lite) let solid = cutouts_opaque();@if(cutout_lite) let solid = cutouts_opaque() || any;+ // A ray by the cutouts' maps (TRACE_ANY_OPAQUE: A_CUTOUT_EMITTERS, `emitter_tr`): one query, which hands it each+ // triangle of a cutout that has maps to ask the map of (`trace_opaque`); whatever else it meets stops it. No+ // texture is read and no second query starts where a map says a hole. (The candidate loop this is lost hits+ // on Metal when every ray's cutouts went through it and their hits were confirmed by `alpha_pass`, see below;+ // for these rays, on the sections with maps alone, two offline renders of Bistro agree in all but 2 of 921,600+ // pixels and with the same rays stepped in order in all but 0.2 %, their mean within 1e-5.)+ @if(!cutout_lite) if (mode == TRACE_ANY_OPAQUE && !solid && has(F_MASKED)) {+ map_hole = false;+ let h = trace_opaque(o, d, tmax_in, mask, true, true);+ if (h.tri == 0xffffffffu && map_hole) { shadow_hole = true; }+ return h;+ }// Alpha-cutout triangles: every query forces opacity, and a cutout hit that fails its alpha test is stepped// through. The ray query's own candidate loop (non-opaque traversal) lost hits on Metal: ~0.1 % of rays near// cutout foliage missed even the opaque ground behind it or found it unlit (black pixels on the ground; the@@ -40,7 +52,7 @@var t0 = 0.0;var hole = false;for (var k = 0u; k < steps + u32(any); k++) {- let h = trace_opaque(o + d * t0, d, tmax_in - t0, mask, first);+ let h = trace_opaque(o + d * t0, d, tmax_in - t0, mask, first, false);if (h.tri == 0xffffffffu) {// (A shadow ray comes here in order only past a cutout that let it through, `shadow_hole`, or past glass.)if (any && !first && hole) { shadow_hole = true; }@@ -60,16 +72,20 @@return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);}-// The closest (or with `any`, the first found) hit, every triangle opaque.-@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool) -> Hit {+// The closest (or with `any`, the first found) hit, every triangle opaque; or, `by_maps`, the triangles of the+// cutouts that have maps (their geometries are not flagged opaque: gpu.rs) each asked of its map where the ray meets+// it and passed where the map says a hole (`map_hole`): a section without maps is flagged opaque and stops the ray,+// as every cutout stopped such a ray before there were maps.+@if(hwrt) var<private> map_hole: bool;+@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool, by_maps: bool) -> Hit {hit_row = NO_ROW;@if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }var rq: ray_query;- let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_FORCE_OPAQUE | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);+ let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_NONE, by_maps) | select(RAY_FLAG_NONE, RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);rayQueryInitialize(&rq, acc, RayDesc(flags, mask, 0.0, tmax_in, o, d));var pg = GOut(-1.0, vec3<f32>(0.0, 1.0, 0.0), 0u, vec2<f32>(0.0));var pprim = 0u;- if (!has(F_PROC)) {+ if (!has(F_PROC) && !(has(F_MASKED) && by_maps)) {rayQueryProceed(&rq);} else {// Procedural boxes come up as candidates although the query forces opacity (that applies to triangles; checked@@ -78,6 +94,15 @@// triangle committed after it.while (rayQueryProceed(&rq)) {let c = rayQueryGetCandidateIntersection(&rq);+ if (c.kind == RAY_QUERY_INTERSECTION_TRIANGLE) {+ // (A cutout's, of a ray by the maps: no other triangle and no other ray comes here.)+ if (cutout_mapped(instance_at(c.instance_custom_data).info.w, c.geometry_index, c.primitive_index, c.barycentrics.x, c.barycentrics.y) != 0) {+ rayQueryConfirmIntersection(&rq);+ } else {+ map_hole = true;+ }+ continue;+ }if (c.kind != RAY_QUERY_INTERSECTION_AABB) { continue; }let cur = rayQueryGetCommittedIntersection(&rq);let tmax = select(tmax_in, cur.t, cur.kind != RAY_QUERY_INTERSECTION_NONE);diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgslindex 158be12..63dff1e 100644--- a/renderer/shaders/trace_units.wgsl+++ b/renderer/shaders/trace_units.wgsl@@ -41,6 +41,13 @@ const UNIT_SHIFTED: u32 = 2u;return select(0u, TRI_MASKED, (x & ROW_CUTOUT) != 0u) | select(0u, TRI_NO_SHADOW, (x & ROW_GLASS) != 0u);}+// Whether a cutout's triangle stops the ray where it is hit: by its map for a ray that reads no texture+// (TRACE_ANY_OPAQUE; a section without one stops it), else by its alpha.+@if(units) fn unit_cutout_stops(ti: u32, rec: u32, rows: u32, part: u32, u: f32, v: f32, t: f32, mode: u32) -> bool {+ if (mode == TRACE_ANY_OPAQUE) { return cutout_mapped(rows, part, leaf_id(ti, 1u), u, v) != 0; }+ return alpha_pass(ti, rec, part, u, v, t);+}+@if(units) fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {var hit = hit_in;if (bitcast<u32>(P.motion.w) == 0u) { return hit; }@@ -113,7 +120,7 @@ const UNIT_SHIFTED: u32 = 2u;var flags = 0u;if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags = row_flags(urows, part); }if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }- if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, part, x.y, x.z, x.x)) { shadow_hole = true; continue; }+ if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && !unit_cutout_stops(ti, rec, urows, part, x.y, x.z, x.x, mode)) { shadow_hole = true; continue; }hit = Hit(x.x, ti, x.y, x.z, rec, part);if (mode != TRACE_CLOSEST) { return hit; }}diff --git a/renderer/src/cutout.rs b/renderer/src/cutout.rsnew file mode 100644index 0000000..2f3d71f--- /dev/null+++ b/renderer/src/cutout.rs@@ -0,0 +1,380 @@+//! Cutout maps: what an alpha-tested material keeps of each of its triangles, made once, for the rays that only ask+//! whether something stands in their way.+//!+//! A cutout (`scene::mesh_class` 1) keeps of a triangle what its base texture's alpha says at or above the+//! material's cutoff. A ray finds that out with a read of the triangle's corners, its material and its texture at a+//! hit. A shadow ray needs less: is the point solid or a hole. A triangle's map answers that from two words: the+//! triangle is laid over with a lattice of 4^level cells, each about `CELL` texels of the texture across (`LEVELS`+//! levels at most), and a cell's state is two bits: nothing of it is there, all of it, or a part (less than half, or+//! half and more). The low bit is what a ray that reads no texture takes the cell for.+//!+//! The maps are a stream of the words' heap (heap.rs `Stream::Cutouts`):+//! - a run a section of a mesh drawn with a cutout material: a word a triangle, in the section's order: the map's+//! first word in the stream and, in its low four bits, the map's level (1 ..= `LEVELS`), `WHOLE` (every cell is+//! solid: no map), `NOTHING` (none is) or `NO_MAP`;+//! - the maps, sixteen cells a word, in `cell_of`'s order. Triangles with the same texture coordinates and material+//! have one map (a tree's leaves are a few sprites, placed thousands of times: of Bistro's 285,355 cutout triangles+//! 3,195 have texture coordinates of their own).+//!+//! An instance's row of the section has where the run begins (`scene::Row`'s last word, `row_run`); a row without one+//! (a material with a function that may change its opacity, a section an edit made) is a cutout the kernel takes as+//! it did before there were maps.++use crate::scene::{GpuMaterial, Scene, ROW_CUTOUT, ROW_MATERIAL};+use glam::Vec2;+use rayon::prelude::*;+use std::collections::HashMap;++/// A cell's width in texels of the material's base texture, where the levels allow it; and the most levels (a cell+/// of a triangle 2048 texels wide is then 16 texels: its leaves' outlines, not their veins).+pub const CELL: f32 = 2.0;+pub const LEVELS: u32 = 7;++/// A triangle's word's low four bits when they are not a level.+pub const NO_MAP: u32 = 0;+pub const NOTHING: u32 = 14;+pub const WHOLE: u32 = 15;++/// A cell's state.+pub const CELL_EMPTY: u32 = 0;+pub const CELL_SOLID: u32 = 1;+pub const CELL_PART_EMPTY: u32 = 2;+pub const CELL_PART_SOLID: u32 = 3;++/// In a row's last word (`scene::Row`), above `scene::ROW_UNSAMPLED`: the section's run in the stream, plus one+/// (0: it has none).+pub const ROW_RUN_SHIFT: u32 = 1;++/// The run of a row, if it has one.+pub fn row_run(row: &crate::scene::Row) -> Option<u32> {+ (row[3] >> ROW_RUN_SHIFT).checked_sub(1)+}++/// The runs of the rows `mine` of an instance of `mesh` that an edit places: those of an instance the scene has of+/// that mesh, section by section where the material is the same (its maps are of the mesh's triangles and that+/// material, whichever instance asks).+pub fn adopt_runs(mine: &mut [crate::scene::Row], mesh: u32, instances: &[crate::scene::Instance], rows: &[crate::scene::Row]) {+ if !mine.iter().any(|r| r[0] & ROW_CUTOUT != 0) {+ return;+ }+ let of = |i: &crate::scene::Instance| rows.get(i.rows as usize..i.rows as usize + mine.len());+ let Some(theirs) = instances.iter().filter(|i| i.mesh == mesh).filter_map(of).find(|o| o.iter().any(|r| row_run(r).is_some())) else { return };+ let low = (1 << ROW_RUN_SHIFT) - 1;+ for (m, o) in mine.iter_mut().zip(theirs) {+ if m[0] == o[0] {+ m[3] = m[3] & low | o[3] & !low;+ }+ }+}++/// What reads a cutout's alpha at a point of its texture: the material's opacity times its base texture's alpha,+/// bilinear between texel centres, repeated or clamped as the texture is.+pub struct Alpha<'a> {+ pub image: Option<&'a image::RgbaImage>,+ pub wrap: bool,+ pub opacity: f32,+ pub cutoff: f32,+}++impl Alpha<'_> {+ /// The texture's size in texels (one by one without a texture).+ pub fn texels(&self) -> Vec2 {+ self.image.map_or(Vec2::ONE, |i| Vec2::new(i.width() as f32, i.height() as f32))+ }++ /// Whether the material is there at `uv`: its alpha is at or above the cutoff (the kernel's `alpha_pass`).+ pub fn pass(&self, uv: Vec2) -> bool {+ let Some(img) = self.image else { return self.opacity >= self.cutoff };+ let (w, h) = (img.width() as i64, img.height() as i64);+ let p = uv * Vec2::new(w as f32, h as f32) - 0.5;+ let (x0, y0) = (p.x.floor(), p.y.floor());+ let (fx, fy) = (p.x - x0, p.y - y0);+ let at = |x: i64, y: i64| {+ let (x, y) = if self.wrap { (x.rem_euclid(w), y.rem_euclid(h)) } else { (x.clamp(0, w - 1), y.clamp(0, h - 1)) };+ img.get_pixel(x as u32, y as u32).0[3] as f32 / 255.0+ };+ let (x0, y0) = (x0 as i64, y0 as i64);+ let a = (at(x0, y0) * (1.0 - fx) + at(x0 + 1, y0) * fx) * (1.0 - fy) + (at(x0, y0 + 1) * (1.0 - fx) + at(x0 + 1, y0 + 1) * fx) * fy;+ a * self.opacity >= self.cutoff+ }+}++/// What a triangle's alpha left of it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kept {+ Whole,+ Nothing,+ Part,+}++/// The lattice's level for a triangle whose longest edge is `texels` long in its texture: cells about `cell` texels+/// across, `most` levels at most.+pub fn level_for(texels: f32, cell: f32, most: u32) -> u32 {+ if !(texels > cell) {+ return 0;+ }+ ((texels / cell).log2().ceil() as u32).min(most)+}++/// The cell of a lattice of `n` cells an edge that the point (u, v) of a triangle lies in (u towards its second+/// corner, v towards its third): row v, two cells a lattice square (the one at the square's origin, then the one+/// across its diagonal), a row holding 2 (n - row) - 1. The kernel's `cutout_cell` is the same.+pub fn cell_of(u: f32, v: f32, n: u32) -> u32 {+ let (x, y) = (u.clamp(0.0, 1.0) * n as f32, v.clamp(0.0, 1.0) * n as f32);+ let j = (y as u32).min(n - 1);+ let i = (x as u32).min(n - 1 - j);+ let across = (x - i as f32) + (y - j as f32) > 1.0 && i + j + 1 < n;+ j * (2 * n - j) + 2 * i + u32::from(across)+}++/// The state of cell `k` in a map's words.+pub fn cell_state(words: &[u32], k: u32) -> u32 {+ (words[(k / 16) as usize] >> ((k % 16) * 2)) & 3+}++/// The map of the triangle whose corners have the texture coordinates `uv`: its 4^level cells' states in+/// `cell_of`'s order. The alpha is read at the points of a lattice twice as fine: a cell has six of them, its+/// corners and its edges' middles, and they say whether it is all there or all gone. Of a cell that is a part, the+/// larger part is found at nine points more, the middles of its nine parts a third its width: five of nine, no tie.+/// (By the six alone, three of six for solid, a disc's cells came to 2 % more than its area; by the three middles,+/// two of three, to 5 % less where the disc was five cells across.)+pub fn map(uv: [Vec2; 3], alpha: &Alpha, level: u32) -> (Kept, Vec<u32>) {+ let n = 1usize << level;+ let m = 2 * n;+ // The fine lattice's points (i, j), i + j <= m, row by row.+ let row = |j: usize| j * (m + 1) - j * (j.max(1) - 1) / 2;+ let mut pass = vec![false; (m + 1) * (m + 2) / 2];+ let (e1, e2) = (uv[1] - uv[0], uv[2] - uv[0]);+ for j in 0..=m {+ for i in 0..=m - j {+ pass[row(j) + i] = alpha.pass(uv[0] + e1 * (i as f32 / m as f32) + e2 * (j as f32 / m as f32));+ }+ }+ let at = |i: usize, j: usize| pass[row(j) + i] as u32;+ let mut words = vec![0u32; (n * n).div_ceil(16)];+ let (mut solid, mut empty) = (0usize, 0usize);+ // How many of the nine points of the cell with the lattice corners a, b, c (fine lattice units) pass: its+ // thirds' six cells that stand as it does and three that stand the other way, each at its middle.+ let inside = |a: (f32, f32), b: (f32, f32), c: (f32, f32)| -> u32 {+ let at = |s: f32, t: f32| {+ let (x, y) = (a.0 + (b.0 - a.0) * s + (c.0 - a.0) * t, a.1 + (b.1 - a.1) * s + (c.1 - a.1) * t);+ alpha.pass(uv[0] + e1 * (x / m as f32) + e2 * (y / m as f32)) as u32+ };+ let mut count = 0;+ for q in 0..3 {+ for p in 0..3 - q {+ count += at((p as f32 + 1.0 / 3.0) / 3.0, (q as f32 + 1.0 / 3.0) / 3.0);+ if p + q < 2 {+ count += at((p as f32 + 2.0 / 3.0) / 3.0, (q as f32 + 2.0 / 3.0) / 3.0);+ }+ }+ }+ count+ };+ let mut put = |k: usize, six: u32, corners: [(usize, usize); 3]| {+ let state = match six {+ 0 => CELL_EMPTY,+ 6 => CELL_SOLID,+ _ => {+ let c = corners.map(|(x, y)| (x as f32, y as f32));+ if inside(c[0], c[1], c[2]) >= 5 {+ CELL_PART_SOLID+ } else {+ CELL_PART_EMPTY+ }+ }+ };+ solid += usize::from(state == CELL_SOLID);+ empty += usize::from(state == CELL_EMPTY);+ words[k / 16] |= state << ((k % 16) * 2);+ };+ for j in 0..n {+ for i in 0..n - j {+ // The cell at the square's origin: corners (2i, 2j), (2i + 2, 2j), (2i, 2j + 2); the one across its+ // diagonal: (2i + 2, 2j + 2), (2i, 2j + 2), (2i + 2, 2j). Each with its three edges' middles.+ let (a, b) = (2 * i, 2 * j);+ let k = j * (2 * n - j) + 2 * i;+ put(k, at(a, b) + at(a + 2, b) + at(a, b + 2) + at(a + 1, b) + at(a, b + 1) + at(a + 1, b + 1), [(a, b), (a + 2, b), (a, b + 2)]);+ if i + j + 1 < n {+ put(k + 1, at(a + 2, b + 2) + at(a, b + 2) + at(a + 2, b) + at(a + 1, b + 2) + at(a + 2, b + 1) + at(a + 1, b + 1), [(a + 2, b + 2), (a, b + 2), (a + 2, b)]);+ }+ }+ }+ let kept = if solid == n * n {+ Kept::Whole+ } else if empty == n * n {+ Kept::Nothing+ } else {+ Kept::Part+ };+ (kept, words)+}++/// What of a material a map is made from: its base texture, how the texture coordinates are placed in it, its+/// opacity and its cutoff. `None`: no map can be made (a material function may change the opacity).+pub fn map_key(m: &GpuMaterial) -> Option<[u32; 7]> {+ (m.tex1[3] <= 0).then(|| [m.tex0[0] as u32, m.uv[0].to_bits(), m.uv[1].to_bits(), m.uv2[0].to_bits(), m.uv2[1].to_bits(), m.base_color[3].to_bits(), m.uv2[3].to_bits()])+}++/// The scene's cutout maps: the stream, and what each run was made from (`map_key`: a material edited since is no+/// longer the maps', live/edits.rs `forget_stale_maps`).+#[derive(Default)]+pub struct Maps {+ pub words: Vec<u32>,+ pub runs: HashMap<u32, [u32; 7]>,+}++/// The scene's cutout maps, each cutout row's run set in the row (`row_run`). After the rows are laid out (lib.rs+/// `prepare_as`); a row that had a run loses it when no map can be made for it now.+pub fn maps(sc: &mut Scene) -> Maps {+ let mut words: Vec<u32> = vec![];+ // A run a (mesh, section, material as `map_key`); a map a (texture coordinates, material); a map's words once.+ let mut runs: HashMap<(u32, u32, [u32; 7]), u32> = HashMap::new();+ let mut alike: HashMap<([u32; 6], [u32; 7]), u32> = HashMap::new();+ let mut shared: HashMap<Vec<u32>, u32> = HashMap::new();+ for k in 0..sc.instances.len() {+ let (mesh_k, first_row) = (sc.instances[k].mesh, sc.instances[k].rows as usize);+ let mesh = sc.meshes[mesh_k as usize];+ for si in 0..mesh.sect_count as usize {+ let Some(row) = sc.rows.get(first_row + si).copied() else { continue };+ let clear = row[3] & ((1 << ROW_RUN_SHIFT) - 1);+ sc.rows[first_row + si][3] = clear;+ if row[0] & ROW_CUTOUT == 0 {+ continue;+ }+ let Some(m) = sc.materials.get((row[0] & ROW_MATERIAL) as usize) else { continue };+ let Some(key) = map_key(m) else { continue };+ let sec = sc.sections[mesh.sect_first as usize + si];+ let run = match runs.get(&(mesh_k, si as u32, key)) {+ Some(&r) => r,+ None => {+ let tex = (m.tex0[0] >= 0).then(|| sc.textures.get(m.tex0[0] as usize)).flatten();+ let alpha = Alpha { image: tex.map(|t| &*t.rgba), wrap: tex.is_some_and(|t| t.wrap), opacity: m.base_color[3], cutoff: m.uv2[3] };+ let (texels, repeat, offset) = (alpha.texels(), Vec2::new(m.uv[0], m.uv[1]), Vec2::new(m.uv2[0], m.uv2[1]));+ let tris = (mesh.first + sec.first) as usize..(mesh.first + sec.first + sec.count) as usize;+ let raw: Vec<[f32; 6]> = sc.pool_attrs[tris].iter().map(|a| [a.n0[3], a.n1[3], a.n2[3], a.uv[0], a.uv[1], a.uv[2]]).collect();+ // The triangles whose map is not made yet, each once.+ let mut todo: Vec<[f32; 6]> = vec![];+ let mut queued: std::collections::HashSet<[u32; 6]> = Default::default();+ for r in &raw {+ let bits = r.map(f32::to_bits);+ if !alike.contains_key(&(bits, key)) && queued.insert(bits) {+ todo.push(*r);+ }+ }+ let made: Vec<(Kept, u32, Vec<u32>)> = todo+ .par_iter()+ .map(|r| {+ let uv = [Vec2::new(r[0], r[1]), Vec2::new(r[2], r[3]), Vec2::new(r[4], r[5])].map(|c| c * repeat + offset);+ let edge = [uv[1] - uv[0], uv[2] - uv[1], uv[0] - uv[2]].iter().map(|e| (*e * texels).length()).fold(0.0f32, f32::max);+ let level = level_for(edge, CELL, LEVELS);+ let (kept, map) = map(uv, &alpha, level);+ (kept, level, map)+ })+ .collect();+ for (r, (kept, level, map)) in todo.iter().zip(made) {+ let word = match kept {+ Kept::Whole => WHOLE,+ Kept::Nothing => NOTHING,+ // (A triangle of one cell that is a part: what its low bit says.)+ Kept::Part if level == 0 => [NOTHING, WHOLE][(cell_state(&map, 0) & 1) as usize],+ Kept::Part => {+ let at = *shared.entry(map).or_insert_with_key(|map| {+ let at = words.len() as u32;+ words.extend_from_slice(map);+ at+ });+ (at << 4) | level+ }+ };+ alike.insert((r.map(f32::to_bits), key), word);+ }+ let run = words.len() as u32;+ words.extend(raw.iter().map(|r| alike[&(r.map(f32::to_bits), key)]));+ // (A map made before this run lies before it; one made for it too: the words above.)+ runs.insert((mesh_k, si as u32, key), run);+ run+ }+ };+ sc.rows[first_row + si][3] = clear | ((run + 1) << ROW_RUN_SHIFT);+ }+ }+ Maps { words, runs: runs.into_iter().map(|(k, run)| (run, k.2)).collect() }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_cell_of_a_lattice_is_reached_once() {+ for n in [1u32, 2, 4, 8, 16] {+ // (A point well inside each cell: a third of the way in from its corner, both ways.)+ let mut seen = vec![0u32; (n * n) as usize];+ for j in 0..n {+ for i in 0..n - j {+ seen[cell_of((i as f32 + 0.3) / n as f32, (j as f32 + 0.3) / n as f32, n) as usize] += 1;+ if i + j + 1 < n {+ seen[cell_of((i as f32 + 0.7) / n as f32, (j as f32 + 0.7) / n as f32, n) as usize] += 1;+ }+ }+ }+ assert!(seen.iter().all(|&c| c == 1), "n = {n}: {seen:?}");+ }+ // The triangle's corners and the middle of its far edge lie in cells of the lattice.+ for (u, v) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.5, 0.5), (1.0, 1.0)] {+ assert!(cell_of(u, v, 8) < 64, "({u}, {v})");+ }+ }++ /// A texture with a disc of radius 0.3 about (0.4, 0.4).+ fn disc(size: u32) -> image::RgbaImage {+ image::RgbaImage::from_fn(size, size, |x, y| {+ let (dx, dy) = ((x as f32 + 0.5) / size as f32 - 0.4, (y as f32 + 0.5) / size as f32 - 0.4);+ image::Rgba([255, 255, 255, if dx * dx + dy * dy < 0.09 { 255 } else { 0 }])+ })+ }++ #[test]+ fn a_disc_keeps_its_area_and_its_place() {+ let img = disc(256);+ let alpha = Alpha { image: Some(&img), wrap: false, opacity: 1.0, cutoff: 0.5 };+ // A triangle over the texture and as much again: the disc lies inside it.+ let uv = [Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(0.0, 2.0)];+ for (level, tolerance) in [(5u32, 0.04f32), (7, 0.01)] {+ let n = 1u32 << level;+ let (kept, words) = map(uv, &alpha, level);+ assert_eq!(kept, Kept::Part);+ // The cells a ray takes for solid, against the disc's share of the triangle (its area is 2).+ let solid = (0..n * n).filter(|&k| cell_state(&words, k) & 1 == 1).count() as f32 / (n * n) as f32;+ let disc = std::f32::consts::PI * 0.09 / 2.0;+ assert!((solid / disc - 1.0).abs() < tolerance, "level {level}: {solid} of {disc}");+ // A point's cell says what the texture says there, away from the disc's rim.+ for (u, v, inside) in [(0.2, 0.2, true), (0.15, 0.2, true), (0.4, 0.4, false), (0.02, 0.6, false), (0.25, 0.15, true)] {+ let state = cell_state(&words, cell_of(u, v, n));+ assert_eq!(state, if inside { CELL_SOLID } else { CELL_EMPTY }, "level {level} at ({u}, {v})");+ assert_eq!(alpha.pass(uv[0] + (uv[1] - uv[0]) * u + (uv[2] - uv[0]) * v), inside);+ }+ }+ }++ #[test]+ fn a_solid_and_an_empty_triangle_have_no_map() {+ let img = image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 0, 0, if x < 4 { 255 } else { 0 }]));+ let alpha = Alpha { image: Some(&img), wrap: false, opacity: 1.0, cutoff: 0.5 };+ assert_eq!(map([Vec2::new(0.1, 0.1), Vec2::new(0.3, 0.1), Vec2::new(0.1, 0.9)], &alpha, 3).0, Kept::Whole);+ assert_eq!(map([Vec2::new(0.7, 0.1), Vec2::new(0.9, 0.1), Vec2::new(0.7, 0.9)], &alpha, 3).0, Kept::Nothing);+ // Without a texture the opacity alone says.+ let plain = Alpha { image: None, wrap: false, opacity: 0.4, cutoff: 0.5 };+ assert_eq!(map([Vec2::ZERO, Vec2::X, Vec2::Y], &plain, 0).0, Kept::Nothing);+ }++ #[test]+ fn a_level_for_an_edge() {+ assert_eq!(level_for(1.0, 2.0, 7), 0);+ assert_eq!(level_for(2.0, 2.0, 7), 0);+ assert_eq!(level_for(3.0, 2.0, 7), 1);+ assert_eq!(level_for(64.0, 2.0, 7), 5);+ assert_eq!(level_for(2200.0, 2.0, 7), 7);+ }+}diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex c7cee56..88735de 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -2715,6 +2715,13 @@ impl Gpu {let mesh_parts: Vec<Vec<(u32, u32)>> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count)| (m.first + at, count)).collect()).collect();// (A translucent particle system's is not flagged opaque: the translucency pass asks for every hit.)let layered: std::collections::HashSet<usize> = scene.particles.iter().filter(|p| p.translucent).map(|p| p.mesh as usize).collect();+ // Nor is a section that an instance draws as a cutout with maps (cutout.rs): a ray that goes by the maps+ // is given its triangles one by one to ask the map of (trace_hw.wgsl); every other ray forces opacity.+ let mapped: std::collections::HashSet<(usize, usize)> = scene+ .instances+ .iter()+ .flat_map(|i| (0..scene.meshes[i.mesh as usize].sect_count as usize).filter(|&s| scene.rows.get(i.rows as usize + s).is_some_and(|r| crate::cutout::row_run(r).is_some())).map(|s| (i.mesh as usize, s)))+ .collect();let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts.iter().zip(&ix.meshes)@@ -2722,12 +2729,13 @@ impl Gpu {.map(|(mesh, (parts, &(_, vertices)))| {parts.iter()- .map(|&(_, count)| wgpu::BlasTriangleGeometrySizeDescriptor {+ .enumerate()+ .map(|(section, &(_, count))| wgpu::BlasTriangleGeometrySizeDescriptor {vertex_format: wgpu::VertexFormat::Float32x3,vertex_count: vertices.max(1),index_format: Some(wgpu::IndexFormat::Uint32),index_count: Some(count * 3),- flags: if layered.contains(&mesh) { wgpu::AccelerationStructureGeometryFlags::empty() } else { wgpu::AccelerationStructureGeometryFlags::OPAQUE },+ flags: if layered.contains(&mesh) || mapped.contains(&(mesh, section)) { wgpu::AccelerationStructureGeometryFlags::empty() } else { wgpu::AccelerationStructureGeometryFlags::OPAQUE },}).collect()})@@ -3048,7 +3056,9 @@ impl Gpu {// The triangles' indices.let ix = &scene.indexed;let index_bytes = (ix.indices.len() + room_tris) * 12;- let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64, row_bytes as u64, index_bytes as u64];+ // The cutouts' maps: as they are (an edit's cutout has none: cutout.rs).+ let maps: &[u8] = bytemuck::cast_slice(&scene.cutout_maps);+ let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64, row_bytes as u64, index_bytes as u64, maps.len() as u64];let (used, limit) = (Heap::<Stream>::size_for(&sizes(0)), self.device.limits().max_storage_buffer_binding_size as u64);if used > limit {return Err(anyhow!("procedural geometry: {} MB of data, more than this device binds in one buffer ({} MB)", used >> 20, limit >> 20));@@ -3073,6 +3083,7 @@ impl Gpu {heap.write(&self.queue, Stream::VertexColors, 0, colors);heap.write(&self.queue, Stream::Rows, 0, rows);heap.write(&self.queue, Stream::Indices, 0, bytemuck::cast_slice(&ix.indices));+ heap.write(&self.queue, Stream::Cutouts, 0, maps);let mut e = self.device.create_command_encoder(&Default::default());e.copy_buffer_to_buffer(&c.buf, c.offset, &heap.buffer, heap.at(Stream::Procs) + blob_at, c.bytes);self.queue.submit([e.finish()]);@@ -3083,6 +3094,7 @@ impl Gpu {put(Stream::VertexColors, 0, colors);put(Stream::Rows, 0, rows);put(Stream::Indices, 0, bytemuck::cast_slice(&ix.indices));+ put(Stream::Cutouts, 0, maps);let Some(l) = l else { return };put(Stream::Procs, 0, bytemuck::cast_slice(&l.head));for (blob, off) in &l.blobs {diff --git a/renderer/src/heap.rs b/renderer/src/heap.rsindex 3dcb6d6..1d0807d 100644--- a/renderer/src/heap.rs+++ b/renderer/src/heap.rs@@ -77,10 +77,12 @@ pub enum Stream {/// The triangles' vertices (indexed.rs): three words a triangle, in the triangles' GPU order. What a hit and a/// candidate's test read, and what the BLASes are built from.Indices,+ /// The cutouts' maps (cutout.rs): a word a triangle of each cutout section, then the maps' cells.+ Cutouts,}impl Section for Stream {- const COUNT: usize = 5;+ const COUNT: usize = 6;const UNIT: u64 = 4;const LABEL: &'static str = "words";fn index(self) -> usize {diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 094dd2c..5c141cf 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -9,6 +9,7 @@ pub mod bvh;pub mod compare;#[cfg(not(target_arch = "wasm32"))]pub mod denoise;+pub mod cutout;pub mod desc;pub mod files;pub mod gpu;@@ -600,6 +601,11 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,// Vertex colours (scene.rs `tri_colors`), with the triangles.sc.gpu_vcolors = if sc.pool_vcolors.is_empty() { vec![] } else { (0..sc.pool_tris.len()).flat_map(|k| sc.pool_vcolors.get(k).copied().unwrap_or(scene::WHITE)).collect() };timings.push(("bvh_ms".into(), t.elapsed().as_secs_f64() * 1000.0));+ // The cutouts' maps (cutout.rs), and in each cutout row where its section's are.+ let tc = Instant::now();+ let maps = cutout::maps(sc);+ (sc.cutout_maps, sc.cutout_runs) = (maps.words, maps.runs);+ timings.push(("cutout_maps_ms".into(), tc.elapsed().as_secs_f64() * 1000.0));// The light list (an emitter's weight = area x luminance of the emissive factor x object power): an instance at a// time, those of its triangles that emit: a run of the list an instance, its first in its record, its triangles'diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex b1b9de1..f76b6b7 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -1629,6 +1629,9 @@ impl LiveCore {let shared = self.sc.tables.retained.textures.iter().any(|(k, s)| *s == slot && k.0 != tid);if shared || !self.g.rewrite_texture(slot, &scene::Texture::of_world(t, srgb_default, &self.assets)?) {self.sc.tables.retained.textures.remove(&(tid, srgb_default));+ } else {+ // (Its texels are others now: the maps made from them are not this texture's.)+ self.forget_stale_maps(&[slot]);}}let known = &self.sc.tables.retained.materials;@@ -1794,6 +1797,28 @@ impl LiveCore {self.g.rebind_scene(&mut self.sc.up);}self.sc.up.heap.write(&self.g.queue, Table::Materials, 0, bytes);+ self.forget_stale_maps(&[]);+ }++ /// A cutout's maps (cutout.rs) are of the material they were made from. A row whose material now gives its+ /// alpha otherwise (its texture, the texture coordinates' place in it, its opacity, its cutoff, a function), or+ /// reads a texture that has been written again (`rewritten`: the textures' slots), loses its run: the kernel+ /// then takes its cutout as one without maps. A rebuild makes the maps again.+ pub(super) fn forget_stale_maps(&mut self, rewritten: &[i32]) {+ let sc = &mut self.sc;+ let mut stale = vec![];+ for (k, row) in sc.rows.iter_mut().enumerate() {+ let Some(run) = crate::cutout::row_run(row) else { continue };+ let material = sc.tables.materials.get(scene::row_material(row) as usize);+ if material.is_some_and(|m| !rewritten.contains(&m.tex0[0]) && crate::cutout::map_key(m).as_ref() == sc.cutout_runs.get(&run)) {+ continue;+ }+ row[3] &= (1 << crate::cutout::ROW_RUN_SHIFT) - 1;+ stale.push(k);+ }+ for k in stale {+ sc.up.words.write(&self.g.queue, Stream::Rows, (k * 16) as u64, bytemuck::cast_slice(&sc.rows[k..k + 1]));+ }}/// `update_instanced` with its fallback (the reason in the frame log, the scene rebuilt) and its CPU time; whether it@@ -3060,7 +3085,9 @@ impl LiveCore {return Err("a model whose mesh is no unit (software traversal has no tree for it)".into());}// (Its rows, the mesh's own, are placed with its record below.)- let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();+ let mut mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();+ // (A cutout section's maps: those the scene's instances of the mesh have, cutout.rs.)+ crate::cutout::adopt_runs(&mut mine, mesh, instances, rows);if glass_caster(&mine) {more.set(more.get() | gpu::F_IGLASS);}@@ -3233,7 +3260,9 @@ impl LiveCore {}// (Its rows, which say its materials, are placed with its record below; its bits and whether it casts// are theirs.)- let mine = scene::section_rows(im.sections(sections), &mats, &tables.materials);+ let mut mine = scene::section_rows(im.sections(sections), &mats, &tables.materials);+ // (A cutout section's maps: those the scene's instances of the mesh have, cutout.rs.)+ crate::cutout::adopt_runs(&mut mine, mesh, instances, rows);// (Shadow rays pass the glass among a caster's other sections under a kernel feature.)if scene::rows_bits(&mine) & scene::INST_GLASS != 0 && scene::rows_cast(&mine, o.cast_shadow) && features & gpu::F_IGLASS == 0 {more.set(more.get() | gpu::F_IGLASS);diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex e1b11a8..3cdec75 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -27,6 +27,9 @@ pub(super) struct LoadedScene {/// edit places takes its rows from the room (`EditState::take_rows`).pub(super) sections: Vec<scene::Section>,pub(super) rows: Vec<scene::Row>,+ /// What each run of the cutouts' maps was made from (`cutout::Maps::runs`): a row whose material has changed in+ /// that loses its run (live/edits.rs `forget_stale_maps`).+ pub(super) cutout_runs: std::collections::HashMap<u32, [u32; 7]>,/// The instances' kernel records as uploaded (movable ones are rewritten when they move), then the procedural/// objects' (from `proc_first`).pub(super) gpu_instances: Vec<scene::GpuInstance>,@@ -193,6 +196,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet ix = std::mem::take(&mut sc.indexed);let (vertices, dynamic_verts, skins) = (ix.vertices.len(), ix.dynamic, ix.skins);let (sections, rows) = (std::mem::take(&mut sc.sections), std::mem::take(&mut sc.rows));+ let cutout_runs = std::mem::take(&mut sc.cutout_runs);let mut gpu_instances = std::mem::take(&mut sc.gpu_instances);let proc_first = gpu_instances.len();gpu_instances.extend_from_slice(&sc.proc_records);@@ -231,5 +235,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pverts: Holes::new(vertices, vertices + room.tris * 3),free_skinned: vec![],};- Ok((LoadedScene { timings, triangles, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, edit, codes_sent }, view, env))+ Ok((LoadedScene { timings, triangles, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, cutout_runs, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, edit, codes_sent }, view, env))}diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 20eb1cc..bfdc918 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -95,7 +95,8 @@ pub const MESH_SECTIONS: usize = 1 << 16;/// An instance's row for a section of its mesh, as the kernel reads it (the words' heap, heap.rs `Stream::Rows`):/// the material with the class bits `ROW_*`, the section's first triangle in the triangles' table, its first emitter in-/// the light list (`NO_EMITTER`: it does not emit), and a word the kernel does not read (`ROW_UNSAMPLED`).+/// the light list (`NO_EMITTER`: it does not emit), and a word of `ROW_UNSAMPLED` and, above it, where a cutout+/// section's maps are (cutout.rs `row_run`).pub type Row = [u32; 4];pub const ROW_MATERIAL: u32 = 0xff_ffff;/// The material is alpha-tested; it is glass (shadow rays pass).@@ -597,6 +598,10 @@ pub struct Scene {/// The vertex colours as the GPU reads them (`prepare`): three words per triangle in GPU order, none in a scene/// without them (gpu.rs F_VCOLOR).pub gpu_vcolors: Vec<u32>,+ /// The cutouts' maps (cutout.rs: the words' stream `heap::Stream::Cutouts`), made where the scene is prepared,+ /// and what each run of them was made from (`cutout::Maps::runs`).+ pub cutout_maps: Vec<u32>,+ pub cutout_runs: HashMap<u32, [u32; 7]>,/// The triangles' attributes in the GPU's order (`prepare`: `pool_attrs`, as the trees left them).pub attrs: Vec<GpuTriAttr>,pub materials: Vec<GpuMaterial>,@@ -2088,6 +2093,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seheight: st.height,pool_vcolors,gpu_vcolors: vec![],+ cutout_maps: vec![],+ cutout_runs: HashMap::new(),attrs: vec![],materials,textures: texcache.textures,diff --git a/tests/render/shadow-cutout-emitter-live.ts b/tests/render/shadow-cutout-emitter-live.tsnew file mode 100644index 0000000..f89521f--- /dev/null+++ b/tests/render/shadow-cutout-emitter-live.ts@@ -0,0 +1,11 @@+// shadow/cutout-emitter in the real-time renderer as it ships: the offline value. The panel's shadow rays ask the+// card's map (renderer/src/cutout.rs: every cell of it a hole) and pass, and its samples keep the whole of its light+// there, because the rays the plane sends on take the card as solid (`APPROX.cutoutPaths`) and bring none of it+// (pathtrace.wgsl `light_mis`). Until 2026-12-02 the card was solid to those shadow rays too and the plane read+// 0.0004.+import def, { test as base } from "./shadow-cutout-emitter.ts";+import type { TestMeta } from "./lib.ts";++export const test: TestMeta = { ...base, id: "shadow/cutout-emitter-live", metric: { ...base.metric, tolerance: 0.03 }, temporal: true, live: 120 };++export default def;diff --git a/tests/render/shadow-cutout-emitter-side-live.ts b/tests/render/shadow-cutout-emitter-side-live.tsnew file mode 100644index 0000000..610b1af--- /dev/null+++ b/tests/render/shadow-cutout-emitter-side-live.ts@@ -0,0 +1,8 @@+// shadow/cutout-emitter-side in the real-time renderer as it ships: the panel's shadow rays ask the card's map+// (renderer/src/cutout.rs) where they meet it, and it says what the texture says there.+import def, { test as base } from "./shadow-cutout-emitter-side.ts";+import type { TestMeta } from "./lib.ts";++export const test: TestMeta = { ...base, id: "shadow/cutout-emitter-side-live", temporal: true, live: 120 };++export default def;diff --git a/tests/render/shadow-cutout-emitter-side.ts b/tests/render/shadow-cutout-emitter-side.tsnew file mode 100644index 0000000..de71a86--- /dev/null+++ b/tests/render/shadow-cutout-emitter-side.ts@@ -0,0 +1,31 @@+// An emitter's shadow ray at a card that is solid on one side and cut out on the other: a 0.2 m emissive panel 2 m+// above an albedo-0.5 Lambert plane at x = 2.05, and at 1 m a black card that is there from x = 0.75 on and cut out+// before it. The ray from the plane's middle meets the card at x = 1.025, in its solid part: no light. The ray from+// 1.1 m to the left meets it at x = 0.475, in the hole: lit. The middle against that reads 0.+// (Which side is which is what this holds: a card read mirrored, or with its two texture coordinates the other way+// round, lets the middle's ray through.)+import { Color, DataTexture, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";++export const test: TestMeta = {+ id: "shadow/cutout-emitter-side", features: ["emissive", "alpha-test", "shadows"], reference: "analytic", temporal: false,+ metric: { kind: "ratio", a: [0.48, 0.48, 0.52, 0.52], b: [0.1, 0.48, 0.14, 0.52], expected: 0, tolerance: 0.02 },+ spp: 256,+ note: "the card 12 x 12 m at y = 1, its texture 96 texels wide: solid from the 54th on; the camera at y = 0.6 under it",+};++export default function () {+ const scene = sceneWithSky(0);+ const panel = new Mesh(new PlaneGeometry(0.2, 0.2), new MeshStandardMaterial({ name: "panel", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 20000, roughness: 1 }));+ panel.name = "panel";+ panel.rotation.x = Math.PI / 2;+ panel.position.set(2.05, 2, 0);+ // (Texel k lies at x = (k + 0.5) / 96 * 12 - 6: between the 53rd and the 54th the alpha crosses a half at 0.75.)+ const texels = new Uint8Array(96 * 4);+ for (let k = 0; k < 96; k++) texels.set([255, 255, 255, k >= 54 ? 255 : 0], k * 4);+ const card = new Mesh(new PlaneGeometry(12, 12), new MeshStandardMaterial({ name: "card", color: 0x000000, map: new DataTexture(96, 1, texels), alphaTest: 0.5, roughness: 1, side: "double" }));+ card.name = "card";+ card.rotation.x = -Math.PI / 2;+ card.position.set(0, 1, 0);+ return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0]), [panel, card, plane(20, lambert(0.5))]);+}