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
Five A/B switches and the uniform tables are removed (#270)
Yujiaac538a9bb640
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 958b8dd..426ed40 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -1601,7 +1601,7 @@ pipeline. The real-time pipeline moves toward Lumen's structure — split signalplus a cosine-sampled ray each, ending in the cache again, so it carries every bounce. Pixels that find their voxelcold trace one vertex and use that meanwhile. Per voxel the history is capped at 256 samples and 32 frames (4 for45 frames after a lighting edit); voxels unused for 120 frames are freed. 2^18 entries, 13.6 MB, resolve 0.14 ms.- `THREERT_CACHE=0` turns it off; `THREERT_CACHE_FLAGS` switches its parts for cost attribution.+ `THREERT_CACHE=0` turns it off.- Diffuse history holds irradiance (lighting / albedo, smooth), remodulated by albedo. Albedo and emission historyis resampled with Catmull-Rom and clamped into this frame's 3 × 3 range (TAA: both are noise-free). It is held to4 frames while the view moves and 16 when still, so texture and sign detail no longer blur through repeated@@ -2879,6 +2879,17 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too lowFound by review: a translucent particle's material given another function kept the kernel's old dispatch for thetranslucency pass, which has its particles' functions alone; the kernel is made again where those are others.+**Five A/B switches and the uniform tables are removed (2026-11-25).** Switches whose question was answered, or+that nothing set: `THREERT_EDIT_BLAS` (an edit mesh's BLAS is built fast), `THREERT_LIGHT_GROUPS` (measured:++4.6 ms of trace without the groups), `THREERT_RIGID_NODES` (measured: 4 to 10 % of GPU time with every node+apart), `THREERT_CACHE_FLAGS` (the radiance cache's four experiment bits, read at four places in the kernel) and+`THREERT_TL_HIDE` (a diagnostic of the translucency pass). And the uniform tables, Android's first way round a+driver that misread four of the kernel's tables (docs/RUNTIME.md "Android"): since the device reads the tables+whole (2026-11-16) no platform had them by default. Their kernel blocks, the per-frame copies, the bounds and+their three tests are gone, with `GpuOptions::uniform_tables` and `THREERT_UNIFORM_TABLES`. The records that+name these switches are of their time. Kept: `THREERT_LTREE` and `THREERT_LT_RIS` (the light+sampler's kind and its candidate count), `THREERT_TABLE_VIEWS`.+**The raster experiment is removed (2026-11-24, after it).** Primary visibility by rasterization (§ 1's decisionexperiment, `THREERT_RASTER=1`) stayed in the code after its verdict: a render pass of the world-space triangles,a texture in the kernel's second bind group, a parameter and a branch at every path's first hit. It drew nothingdiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 59f4a23..27db92e 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1527,13 +1527,13 @@ The path-tracing kernel is one WESL module: `pathtrace.wgsl`, then `records.wgsltranslation (`@if(flag)` on a declaration or a statement, `@if(flag) { .. } @else { .. }` on a block ofdeclarations). wesl-rs (WESL's compiler in Rust, natively and in a browser alike) makes a kernel's WGSL from avariant (gpu.rs `KernelVariant`, `kernel_wgsl`): the traversal (`hwrt`), a device's switches (`strict`,-`cutout_lite`, `cutout_lite2`, `last_direct`, `last_sun`, `light_pick`), software traversal's units (`units`), the binding layout (`merged`, the browser's; `uniform_tables`, Android's) and the loop guard (`guard`).+`cutout_lite`, `cutout_lite2`, `last_direct`, `last_sun`, `light_pick`), software traversal's units (`units`), the binding layout (`merged`, the browser's; `whole_tables`, Android's) and the loop guard (`guard`).pathtrace.wgsl's head names them; a flag the source names that a kernel is not given is an error. A scene's otherfeatures are bits of `FEAT`, a pipeline-overridable constant: one kernel source for all of them (`OBJECT_STRIDE`too is an override, from F_TINT).- The numbers a variant is compiled for are WESL constants, which the source imports (`import constants::..`; gpu.rs- `KernelVariant::constants`): the uniform tables' lengths, the loop guard's limit. One- the source imports and is not given is an error.+ `KernelVariant::constants`): the loop guard's count's words and its limit. One the source imports and is not+ given is an error.- The kernel reads its tables and its group-1 buffers only through functions (`material_at`, `instance_at`,`cache_acc_add`, `refl_store`, ...), declared once in each layout's block, so a layout is its declarations andnothing else of the kernel knows which it is in.@@ -2249,33 +2249,17 @@ on the device", and differs where it says so.its own at offset 0 each frame, the emitters' table hung the same: the binding, not its sharing a buffer with`tables` or its offset. Read whole: no hang.- Without the views the kernel reads all seven from `tables` (binding 4) by the offsets in the parameters- (`Params::table_first`), as the merged layout does (pathtrace.wgsl `@if(merged || whole_tables)`), and there are- no uniform tables (below), so none of their bounds either. On the device the frame costs what it does with the- uniform copies (Foundry at 249 × 140, one bounce: 52 ms read whole, 51 ms with the uniform copies and the other- three read whole). `THREERT_TABLE_VIEWS=1` on the device brings back the views (and the uniform copies), for A/B.+ (`Params::table_first`), as the merged layout does (pathtrace.wgsl `@if(merged || whole_tables)`). On the+ device the frame cost what it did with the uniform copies (below; Foundry at 249 × 140, one bounce: 52 ms read+ whole, 51 ms with the copies and the other three read whole). `THREERT_TABLE_VIEWS=1` on the device brings back+ the views, for A/B.- Elsewhere the views stay; `THREERT_TABLE_VIEWS=0` reads the tables whole on any device, to the same image bitfor bit (`live::instanced_tests::the_tables_read_whole_render_what_the_views_do`, offline and live after a poweredit).-- **Uniform tables** (`GpuOptions::uniform_tables`, `THREERT_UNIFORM_TABLES=1|0`; default on Android with the views,- `THREERT_TABLE_VIEWS=1`; never with the merged layout or the tables read whole). The driver gave the kernel other buffers' contents for four of its read-only storage buffers, each- a binding of its own then: `tex_info` (binding 14), `objects` (15), `instances` (17), `media` (18), all numbered- after the acceleration structure (13). As uniform buffers they read right.- - Since 2026-11-15 the four are views of their sections of the tables' buffer ("The scene's tables"), still at- bindings of their own (15 to 18), and the acceleration structure is the group's last binding (19). The device- did not read those views right either (2026-11-16, `THREERT_TABLE_VIEWS=1 THREERT_UNIFORM_TABLES=0`: Range all- white), and with the uniform copies the other three views were still wrong (above): Android now reads the- tables whole and has no uniform copies; they stay for `THREERT_TABLE_VIEWS=1`.- - The kernel's source has them under `@if(uniform_tables)` (pathtrace.wgsl): four sized uniform arrays at- bindings 15 to 18 (merged.rs `UNIFORM_TABLES`; their lengths WESL constants), and their accessors hold every- index to the array (`min(i, last)`), so nothing is read outside a uniform buffer.- - The renderer writes the tables' buffer. `Gpu::sync_tables` copies the four sections into their uniform buffers- in a frame's encoder, after the particle passes (which write their objects' entries on the GPU) and before the- trace.- - A uniform binding holds 64 KiB, so the arrays are bounded: 2,048 textures, 4,096 object entries (1,365 objects;- 1,024 with instance colours), 409 instance records (model instances, procedural objects, `dynamicGeometry`- meshes), all 32 media. A scene with more reads the last entry for the rest, and the renderer says so on stderr- when it uploads the scene and once when in-place edits pass a bound. `THREERT_UNIFORM_TABLES=0` binds the- views of their sections.+- **Uniform tables** (removed 2026-11-25). The first way round the same driver: four of the tables (`tex_info`,+ `objects`, `instances`, `media`) copied each frame into uniform buffers of 64 KiB, which bounded them (409+ instance records). With the tables read whole no platform had them by default, and they went; the records+ below that name them and `THREERT_UNIFORM_TABLES` are of that time.- **The kernel's other storage buffers stay as they are**, each for its reason:| buffer | size | decision |diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 5b2e590..1bb9084 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -15,13 +15,11 @@// units software traversal's second level (gpu.rs `F_UNITS`); a scene's other features are bits// of `FEAT`, a pipeline-overridable constant// merged the merged binding layout (merged.rs: at most eight storage buffers a stage, a browser's)-// uniform_tables four tables in uniform buffers (merged.rs `UNIFORM_TABLES`: Android's drivers)// whole_tables the seven typed tables read from the tables' buffer whole, as `merged` reads them, and// no views of their sections (gpu.rs `GpuOptions::table_views`: Android's drivers)// guard the loop guard (gpu.rs `loop_guard_of`, `guard_loops`)// The numbers a variant is compiled for are WESL constants (`import constants::`, gpu.rs `KernelVariant::constants`): the-// uniform tables' lengths, the loop guard's limit.-@if(uniform_tables) import constants::{UT_TEX_INFO, UT_OBJECTS, UT_INSTANCES, UT_MEDIA};+// loop guard's words and its limit.@if(merged || guard) import constants::GUARD_WORDS;@if(guard) import constants::LOOP_GUARD_LIMIT;@if(hwrt) enable wgpu_ray_query;@@ -258,28 +256,14 @@ fn emitter_tri_at(i: u32) -> EmitterTri {fn material_at(i: u32) -> Material { return materials[i]; }fn light_at(i: u32) -> Light { return lights[i]; }fn emitter_at(i: u32) -> vec4<f32> { return emitters[i]; }- @if(uniform_tables) {- // The uniform tables (merged.rs `UNIFORM_TABLES`): these four from sized uniform arrays, copies of their- // sections, every index held to the array (a scene with more entries than one holds reads the last for the- // rest; nothing outside the buffer is read).- @group(0) @binding(15) var<uniform> tex_info: array<vec4<f32>, UT_TEX_INFO>;- @group(0) @binding(16) var<uniform> objects: array<vec4<f32>, UT_OBJECTS>;- @group(0) @binding(17) var<uniform> instances: array<Instance, UT_INSTANCES>;- @group(0) @binding(18) var<uniform> media: array<Medium, UT_MEDIA>;- fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[min(i, UT_TEX_INFO - 1u)]; }- fn object_at(i: u32) -> vec4<f32> { return objects[min(i, UT_OBJECTS - 1u)]; }- fn instance_at(i: u32) -> Instance { return instances[min(i, UT_INSTANCES - 1u)]; }- fn medium_at(i: u32) -> Medium { return media[min(i, UT_MEDIA - 1u)]; }- } @else {- @group(0) @binding(15) var<storage, read> tex_info: array<vec4<f32>>;- @group(0) @binding(16) var<storage, read> objects: array<vec4<f32>>;- @group(0) @binding(17) var<storage, read> instances: array<Instance>;- @group(0) @binding(18) var<storage, read> media: array<Medium>;- fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[i]; }- fn object_at(i: u32) -> vec4<f32> { return objects[i]; }- fn instance_at(i: u32) -> Instance { return instances[i]; }- fn medium_at(i: u32) -> Medium { return media[i]; }- }+ @group(0) @binding(15) var<storage, read> tex_info: array<vec4<f32>>;+ @group(0) @binding(16) var<storage, read> objects: array<vec4<f32>>;+ @group(0) @binding(17) var<storage, read> instances: array<Instance>;+ @group(0) @binding(18) var<storage, read> media: array<Medium>;+ fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[i]; }+ fn object_at(i: u32) -> vec4<f32> { return objects[i]; }+ fn instance_at(i: u32) -> Instance { return instances[i]; }+ fn medium_at(i: u32) -> Medium { return media[i]; }}// Density grids (gpu.rs F_GRID, `GridsGpu`): field A of every grid, stacked along z; one cell in scenes without.@group(0) @binding(10) var grid_tex: texture_3d<f32>;@@ -3326,8 +3310,7 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {}fn resolve_bound() -> bool { return LIVE && refl_len() >= 2u * P.size.x * P.size.y; }-// THREERT_CACHE_FLAGS bit 16 turns the resolve off (rays then stay in their pixel's specular, the resolve reads zeros).-fn resolve_on() -> bool { return resolve_bound() && P.motion.y == 0.0 && (u32(P.cache.w) & 16u) == 0u; }+fn resolve_on() -> bool { return resolve_bound() && P.motion.y == 0.0; }// Density of l under the base specular lobe alone (VNDF sampling).fn pdf_spec(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {@@ -3612,7 +3595,7 @@ fn cache_end(s: Surface, d: vec3<f32>, cone: vec2<f32>, thr: vec3<f32>, depth: ucur_depth = depth;var c = thr * cache_reflectance(lb1) * e.rgb;// Resampled lights, not the exact loop camera hits get (that costs 2x here: mirror pixels are scattered).- mirror_path = mirror_path && (u32(P.cache.w) & 8u) != 0u;+ mirror_path = false;// (The lights alone: the sky's light is in the cache's indirect part, whole. Its samples taken afresh// here against the white-lobe ones the cache left out do not add up on a glossy surface: a white metal// ground in a mirror read 0.80 of a uniform sky. The lights' still are: weights of two lobes, right for a@@ -4170,8 +4153,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {}// Live: the path ends in the radiance cache at its first bounce (`cache_end`).if (cache_on() && depth >= 1u && !(has(F_GLASS) && s.transmission > 0.0)) {- let hit_light = spec_lobe && rough0 < 0.4 && depth == 1u && (u32(P.cache.w) & 2u) == 0u;- let train = (((gid.x >> 3u) + 3u * (gid.y >> 2u) + pcg(P.size.z)) & CACHE_TRAIN_MASK) == 0u && (u32(P.cache.w) & 4u) == 0u;+ let hit_light = spec_lobe && rough0 < 0.4 && depth == 1u;+ let train = (((gid.x >> 3u) + 3u * (gid.y >> 2u) + pcg(P.size.z)) & CACHE_TRAIN_MASK) == 0u;@if(merged) { radiance += cache_end(s, d, vec2<f32>(width, cone_a), thr, depth, train, hit_light, straight); }@if(!merged) {// Here only what a warm voxel holds; a pixel with more to trace is left for `finish`.diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgslindex cf33c00..e496a94 100644--- a/renderer/shaders/translucent.wgsl+++ b/renderer/shaders/translucent.wgsl@@ -18,7 +18,7 @@@if(hwrt) struct TP {size: vec4<u32>, // output width, height, -, mode (0 offline: accumulate; 1 live: over the image)view: vec4<u32>, // live: traced width, height (the opaque first hits); training budget (points per frame); 1 = at the traced resolution- misc: vec4<f32>, // live: share of hit pixels that train the volume voxels, 1 = train only (THREERT_TL_HIDE: what is behind), -, -+ misc: vec4<f32>, // live: share of hit pixels that train the volume voxels, -, -, -};@if(hwrt) @group(2) @binding(0) var tacc: acceleration_structure;@@ -176,10 +176,8 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {if (low) {tlow[pix] = vec4<f32>(col, tr);} else if (live) {- if (TPS.misc.y < 0.5) {- let c = timg[pix];- timg[pix] = vec4<f32>(c.rgb * tr + col, c.w);- }+ let c = timg[pix];+ timg[pix] = vec4<f32>(c.rgb * tr + col, c.w);} else {timg[pix] += vec4<f32>(col, tr);}@@ -191,7 +189,7 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {fn translucent_up(@builtin(global_invocation_id) gid: vec3<u32>) {let w = TPS.size.x;let h = TPS.size.y;- if (gid.x >= w || gid.y >= h || TPS.misc.y >= 0.5) { return; }+ if (gid.x >= w || gid.y >= h) { return; }let iw = TPS.view.x;let ih = TPS.view.y;let fx = clamp((f32(gid.x) + 0.5) * f32(iw) / f32(w) - 0.5, 0.0, f32(iw - 1u));diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex a01d7bd..9052c66 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -48,8 +48,6 @@ pub struct Gpu {pub device: wgpu::Device,pub queue: wgpu::Queue,pub adapter_info: wgpu::AdapterInfo,- /// The kernel's bounded tables are uniform buffers (`GpuOptions::uniform_tables`; merged.rs `UNIFORM_TABLES`).- pub uniform_tables: bool,/// The kernel reads its seven typed tables from the tables' buffer whole, not from views of their sections/// (`GpuOptions::table_views`; merged.rs `TABLE_VIEWS`).pub whole_tables: bool,@@ -330,7 +328,6 @@ const ACC_BINDING: u32 = 19;pub(crate) struct LayoutShape {pub hwrt: bool,pub merged: bool,- pub uniform_tables: bool,/// No views of the tables' sections (`Gpu::whole_tables`).pub whole_tables: bool,pub guard: bool,@@ -352,8 +349,8 @@ const ACCELERATION_STRUCTURE: wgpu::BindingType = wgpu::BindingType::Acceleratio/// (what the kernel writes), group 2 (the translucency pass's; hardware traversal). A test holds them to what every/// variant of the kernel's source declares (`the_kernels_layouts_are_its_declarations`).pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLayoutEntry>; 3] {- use crate::merged::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};- let LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard } = shape;+ use crate::merged::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS};+ let LayoutShape { hwrt, merged, whole_tables, guard } = shape;let (read, write) = (storage_buffer(true), storage_buffer(false));// Group 0: the parameters; the vertices; the tables' heap, the words' heap; the previous frame's vertices of// those that move; the texture pages and their sampler, the environment, the density grids' atlas@@ -376,11 +373,9 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLscene.push(layout_entry(3, read));}// The tables the kernel reads at every hit or light, bound again as typed views of their sections (the merged- // layout has no binding for them, nor has a device that reads them from the buffer whole), four of them uniform- // copies where a driver needs it.+ // layout has no binding for them, nor has a device that reads them from the buffer whole).if !merged && !whole_tables {- let copied = |b: u32| uniform_tables && UNIFORM_TABLES.iter().any(|t| t.binding == b);- scene.extend(TABLE_VIEWS.iter().map(|&(_, b)| layout_entry(b, if copied(b) { UNIFORM_BUFFER } else { read })));+ scene.extend(TABLE_VIEWS.iter().map(|&(_, b)| layout_entry(b, read)));}if hwrt {scene.push(layout_entry(ACC_BINDING, ACCELERATION_STRUCTURE));@@ -405,22 +400,6 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL[scene, live, translucent]}-/// A note for each uniform table that a scene has more entries of (`used`, merged.rs `UNIFORM_TABLES`' order) than-/// its array holds: the kernel reads the last entry for the rest.-pub(crate) fn uniform_overflow(used: [u64; 4]) -> Vec<String> {- crate::merged::UNIFORM_TABLES- .iter()- .zip(used)- .filter(|(t, used)| *used > t.len as u64)- .map(|(t, used)| format!("uniform tables: the scene has {used} entries of `{}`, a uniform buffer holds {} (the rest read as the last one; THREERT_UNIFORM_TABLES=0 reads the tables' heap)", t.name, t.len))- .collect()-}--/// The bytes of a table that its uniform copy takes: what both hold, in whole words (a copy's unit).-fn uniform_copy_bytes(table: u64, copy: u64) -> u64 {- table.min(copy) & !3-}-/// What the scene bind group holds besides `Uploaded`'s buffers (`Gpu::rebind_scene` makes it again).pub struct BindParts {@@ -445,7 +424,6 @@ struct SceneBuffers<'a> {accum: &'a wgpu::Buffer,parts: &'a BindParts,accel: Option<&'a Accel>,- uniform: Option<&'a [wgpu::Buffer; 4]>,}/// The scene's buffers a particle pass writes (particles.wgsl, gpu_particles.wgsl: bindings 2 to 6; the objects'@@ -474,9 +452,6 @@ pub struct Uploaded {/// The scene's tables (heap.rs): materials, lights, emitters, objects, instances, media and the rest, each a/// section that edits write in place (`Heap::write`) and grow (`Heap::grow`, then `Gpu::rebind_scene`).pub heap: Heap<Table>,- /// The uniform tables (`Gpu::uniform_tables`): the uniform buffers the kernel reads four tables from (merged.rs- /// `UNIFORM_TABLES`' order; `Gpu::sync_tables` copies their sections there each frame).- pub uniform: Option<[wgpu::Buffer; 4]>,/// The trace's samples, a `Pixel` a pixel: the view's buffer (a live view's targets', an offline render's own:/// `accum_buffer`). A handle of it here, for the scene's bind group, where the kernel's layout has it;/// `Gpu::set_accum` gives it another (a view of another size).@@ -1116,10 +1091,8 @@ pub struct KernelVariant {pub features: u32,/// The merged layout (merged.rs).pub merged: bool,- /// Four tables in uniform buffers (merged.rs `UNIFORM_TABLES`; `GpuOptions::uniform_tables`). Never with `merged`.- pub uniform_tables: bool,/// The seven typed tables read from the tables' buffer whole, as the merged layout reads them, with the layout as- /// written otherwise (`GpuOptions::table_views`). Never with `uniform_tables`.+ /// written otherwise (`GpuOptions::table_views`).pub whole_tables: bool,/// The loop guard's limit, in a kernel with the guard (`loop_guard_of`, `guard_loops`).pub guard: Option<u32>,@@ -1132,7 +1105,7 @@ impl KernelVariant {}/// The flags of the kernel's conditional translation (pathtrace.wgsl's head).- pub fn flags(&self) -> [(&'static str, bool); 12] {+ pub fn flags(&self) -> [(&'static str, bool); 11] {let (k, f) = (&self.switches, |bit: u32| self.features & bit != 0);[("hwrt", self.hwrt),@@ -1144,20 +1117,16 @@ impl KernelVariant {("light_pick", k.light_pick),("units", f(F_UNITS)),("merged", self.merged),- ("uniform_tables", self.uniform_tables),("whole_tables", self.whole_tables),("guard", self.guard.is_some()),]}- /// The numbers the variant is compiled for, WESL constants (`import constants::`): the uniform tables' lengths- /// (`UT_<table>`), the loop guard's count's words and its limit.+ /// The numbers the variant is compiled for, WESL constants (`import constants::`): the loop guard's count's+ /// words and its limit.pub fn constants(&self) -> Vec<(String, u32)> {- use crate::merged::{GUARD_WORDS, UNIFORM_TABLES};+ use crate::merged::GUARD_WORDS;let mut out = vec![];- if self.uniform_tables {- out.extend(UNIFORM_TABLES.iter().map(|t| (format!("UT_{}", t.name.to_uppercase()), t.len)));- }if self.merged || self.guard.is_some() {out.push(("GUARD_WORDS".into(), GUARD_WORDS));}@@ -1176,8 +1145,6 @@ pub fn kernel_wgsl(src: &str, v: &KernelVariant) -> String {/// `kernel_wgsl`, saying what did not compile instead of panicking (a scene's own functions are a game's code).pub fn try_kernel_wgsl(src: &str, v: &KernelVariant) -> Result<String, String> {- assert!(!(v.merged && v.uniform_tables), "the uniform tables are never in the merged layout");- assert!(!(v.whole_tables && v.uniform_tables), "the uniform tables are copies of views the kernel reading the tables whole does not have");let mut out = try_wesl_wgsl(src, &v.flags(), &v.constants())?;if v.guard.is_some() {guard_loops(&mut out);@@ -1372,15 +1339,10 @@ fn guard_room(hwrt: bool) -> bool {/// are without any of this. What a phone's GPU needed and why: docs/RUNTIME.md "Android (Adreno)".#[derive(Clone, Debug, Default, PartialEq)]pub struct GpuOptions {- /// The kernel's bounded tables (texture pages, objects, instances, media) as uniform buffers instead of storage- /// buffers (merged.rs `UNIFORM_TABLES`). None: where a driver needs it, which is Android. Never with the merged- /// layout, whose tables are one buffer of its own.- pub uniform_tables: Option<bool>,/// The seven tables the kernel reads at every hit or light (materials, lights, emitters, texture rects, objects,/// instances, media) as views of their sections, each a binding of its own (merged.rs `TABLE_VIEWS`), or read from/// the tables' buffer whole by the offsets in the parameters, as the merged layout reads them. None: views, but on- /// Android: Adreno 740's driver read the views wrong (docs/RUNTIME.md "Android"). Without views there are no- /// uniform tables either.+ /// Android: Adreno 740's driver read the views wrong (docs/RUNTIME.md "Android").pub table_views: Option<bool>,/// A directory to keep compiled pipelines in between runs (pipeline_cache.rs). None: nothing is kept.pub pipeline_cache: Option<std::path::PathBuf>,@@ -1391,7 +1353,7 @@ pub struct GpuOptions {}impl GpuOptions {- /// THREERT_UNIFORM_TABLES=1|0, THREERT_PIPELINE_CACHE=<directory>, THREERT_APPROX=<bits of `A_*`>, and the+ /// THREERT_TABLE_VIEWS=1|0, THREERT_PIPELINE_CACHE=<directory>, THREERT_APPROX=<bits of `A_*`>, and the/// kernel's switches (`KernelSwitches::from_env`).pub fn from_env() -> GpuOptions {Self::from_vars(&|name| std::env::var(name).ok(), cfg!(target_os = "android"))@@ -1400,7 +1362,6 @@ impl GpuOptions {/// `from_env`, of these variables on this platform.fn from_vars(var: &dyn Fn(&str) -> Option<String>, android: bool) -> GpuOptions {GpuOptions {- uniform_tables: var("THREERT_UNIFORM_TABLES").map(|v| v == "1"),table_views: var("THREERT_TABLE_VIEWS").map(|v| v == "1"),pipeline_cache: var("THREERT_PIPELINE_CACHE").filter(|d| !d.is_empty()).map(std::path::PathBuf::from),kernel: KernelSwitches::from_vars(var, android),@@ -1413,12 +1374,6 @@ impl GpuOptions {fn table_views_on(&self, merged: bool, android: bool) -> bool {!merged && self.table_views.unwrap_or(!android)}-- /// Whether the device has the uniform tables (copies of four of the views): as asked, else on Android; only with- /// the views.- fn uniform_tables_on(&self, merged: bool, android: bool) -> bool {- self.table_views_on(merged, android) && self.uniform_tables.unwrap_or(android)- }}/// The kernel's switches: changes to its source for a GPU that the source as written is wrong or too slow on. Each@@ -2261,17 +2216,16 @@ impl Gpu {#[cfg(not(dlss))]let (device, queue) = adapter.request_device(&device_desc).await?;let pipeline_cache = cache_feature.and_then(|_| crate::pipeline_cache::PipelineCache::open(&device, options.pipeline_cache.as_ref()?, &adapter_info));- let uniform_tables = options.uniform_tables_on(merged, cfg!(target_os = "android"));let whole_tables = !merged && !options.table_views_on(merged, cfg!(target_os = "android"));let switches = options.kernel;let approx = options.approx.unwrap_or(A_LIVE) & A_LIVE;let src = kernel_template();// Bounds checks are not needed: all indices come from our own BVH / scene builder.let module = unsafe {- let wgsl = kernel_wgsl(&src, &KernelVariant { merged, uniform_tables, whole_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });+ let wgsl = kernel_wgsl(&src, &KernelVariant { merged, whole_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });device.create_shader_module_trusted(wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) }, kernel_checks())};- let [entries, live_entries, tl_entries] = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard: guard_room(hwrt) });+ let [entries, live_entries, tl_entries] = kernel_layout_entries(LayoutShape { hwrt, merged, whole_tables, guard: guard_room(hwrt) });let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });let live_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live"), entries: &live_entries });let no_grid_view = grid_texture(&device, "no grid", [1, 1, 1], false).create_view(&Default::default());@@ -2305,7 +2259,7 @@ impl Gpu {dlss_sdk,#[cfg(dlss)]dlss_rr,- instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, live_layout, no_live, no_live_bufs, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),+ instance, adapter, timestamps, device, queue, adapter_info, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, live_layout, no_live, no_live_bufs, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),})}@@ -2381,7 +2335,7 @@ impl Gpu {device: self.device.clone(),source: self.source.clone(),module: self.module.clone(),- variant: KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, whole_tables: self.whole_tables, ..KernelVariant::new(self.hwrt, self.switches, 0) },+ variant: KernelVariant { merged: self.merged, whole_tables: self.whole_tables, ..KernelVariant::new(self.hwrt, self.switches, 0) },layout: self.pipeline_layout.clone(),tl_layout: self.tl_pipeline_layout.clone(),modules: self.modules.clone(),@@ -2544,10 +2498,6 @@ impl Gpu {if let Some(slot) = pages.keys.iter().position(|k| k.0 == t.key) {return Ok(PagesEdit { slot: slot as i32, info: None, view: None });}- let rows = crate::merged::UNIFORM_TABLES.iter().find(|u| u.table == crate::heap::Table::TexInfo).map_or(u32::MAX, |u| u.len);- if self.uniform_tables && (pages.keys.len() as u32 + 1) * 2 > rows {- return Err(anyhow!("more textures than this device's texture table holds ({})", rows / 2));- }let (side, layers) = (pages.atlas.side, pages.atlas.layers());// (On a copy: one that finds no room leaves the pages' record as it was.)let mut atlas = pages.atlas.clone();@@ -2940,17 +2890,8 @@ impl Gpu {fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }}- // The uniform tables: four tables' sections again in uniform buffers (merged.rs `UNIFORM_TABLES`).- let uniform = self.uniform_tables.then(|| {- // What the scene has of each, against what its array holds (the sections have the edits' room after it).- let used = [tex_info.len() as u64, scene.objects.len() as u64, records.len() as u64, scene.media.len() as u64];- for note in uniform_overflow(used) {- eprintln!("threert: {note}");- }- self.uniform_copies(&heap)- });let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, sampler, grid_view };- let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });+ let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref() });let kernel = Kernel { approx: self.approx, ..Kernel::new(scene, groups) };// Translucent particles (hardware RT): the translucency pass's own TLAS, built again after the particle pass:// an instance of it a system's mesh, the instance's record in its custom data as in the scene's TLAS.@@ -3066,7 +3007,7 @@ impl Gpu {Some(_) => EmitterFills { moved: self.emitter_fill(&emitter_runs.moved, &b_vertices, &heap, &words), particles: self.emitter_fill(&emitter_runs.particles, &b_vertices, &heap, &words) },None => EmitterFills::default(),};- Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, vertices: b_vertices, prev_vertices: b_prev, accel, units: scene.units.clone(), particles, gpu_particles, skin, fills, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })+ Ok(Uploaded { bg, bg_parts, heap, accum: b_accum, params: b_params, kernel, vertices: b_vertices, prev_vertices: b_prev, accel, units: scene.units.clone(), particles, gpu_particles, skin, fills, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })}/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None@@ -3825,8 +3766,7 @@ impl Gpu {flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,}).collect();- let flags = if std::env::var("THREERT_EDIT_BLAS").is_ok_and(|v| v == "trace") { wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE } else { wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD };- let blas = self.device.create_blas(&wgpu::CreateBlasDescriptor { label: Some("edit mesh"), flags, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: sizes.clone() });+ let blas = self.device.create_blas(&wgpu::CreateBlasDescriptor { label: Some("edit mesh"), flags: wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: sizes.clone() });(blas, (parts, sizes))}@@ -3834,7 +3774,7 @@ impl Gpu {/// `edit_geometry`), its first `opaque` ones opaque: its BLAS, which the commit's build builds (`TopBuild::meshes`). Returns its index.pub fn add_mesh(&self, accel: &mut Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> u32 {// Built fast rather than traced fast (edits come every frame under destruction; the batches of pieces are rebuilt- // every frame); THREERT_EDIT_BLAS=trace for the A/B (`mesh_blas_for`).+ // every frame): `mesh_blas_for`.let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);accel.meshes.push(blas);accel.mesh_geo.push(geo);@@ -3887,11 +3827,7 @@ impl Gpu {}if !self.merged && !self.whole_tables {for &(table, binding) in &crate::merged::TABLE_VIEWS {- let copy = b.uniform.and_then(|u| u.iter().zip(&crate::merged::UNIFORM_TABLES).find(|(_, t)| t.binding == binding).map(|(c, _)| c));- entries.push(match copy {- Some(c) => buffer_entry(binding, c),- None => wgpu::BindGroupEntry { binding, resource: b.heap.binding(table) },- });+ entries.push(wgpu::BindGroupEntry { binding, resource: b.heap.binding(table) });}}if let Some(a) = b.accel {@@ -3915,7 +3851,7 @@ impl Gpu {if let Some(a) = &mut up.accel {(a.vertices, a.indices, a.index_first) = (up.vertices.clone(), up.words.buffer.clone(), (up.words.at(Stream::Indices) / 4) as u32);}- up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, vertices: &up.vertices, heap: &up.heap, words: &up.words, prev_vertices: &up.prev_vertices, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });+ up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, vertices: &up.vertices, heap: &up.heap, words: &up.words, prev_vertices: &up.prev_vertices, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref() });if up.accel.is_none() {return;}@@ -4032,34 +3968,6 @@ impl Gpu {Ok(Some(n))}- /// The uniform tables' buffers (merged.rs `UNIFORM_TABLES`' order), filled from their sections as they are now.- fn uniform_copies(&self, heap: &Heap<Table>) -> [wgpu::Buffer; 4] {- let copies = crate::merged::UNIFORM_TABLES.each_ref().map(|t| {- // (COPY_SRC: read back by the test that holds them to the tables, and by whoever diagnoses a driver.)- self.device.create_buffer(&wgpu::BufferDescriptor { label: Some(t.name), size: t.stride * t.len as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })- });- let mut e = self.device.create_command_encoder(&Default::default());- Self::copy_uniform(&mut e, heap, &copies);- self.queue.submit([e.finish()]);- copies- }-- fn copy_uniform(e: &mut wgpu::CommandEncoder, heap: &Heap<Table>, copies: &[wgpu::Buffer; 4]) {- for (t, dst) in crate::merged::UNIFORM_TABLES.iter().zip(copies) {- e.copy_buffer_to_buffer(&heap.buffer, heap.at(t.table), dst, 0, uniform_copy_bytes(heap.cap(t.table), dst.size()));- }- }-- /// The uniform tables: their sections as they are now, copied into the four uniform buffers. The renderer writes- /// the tables' heap; the passes that read the scene read these copies, so they are made in their encoder, before- /// them, each frame, after whatever writes a table on the GPU in that encoder (the particle passes write their- /// objects' entries).- pub fn sync_tables(&self, up: &Uploaded, e: &mut wgpu::CommandEncoder) {- if let Some(u) = &up.uniform {- Self::copy_uniform(e, &up.heap, u);- }- }-/// Software traversal's top tree again, over the units as they are now, written to its range of the node buffer/// (what the TLAS's build is to hardware traversal). Err: no tree can be made (more units than its range holds, a/// unit that is nowhere); nothing was written, and the caller rebuilds the scene.@@ -4225,7 +4133,6 @@ impl Gpu {let t1 = Instant::now();let mut enc = d.create_command_encoder(&Default::default());enc.clear_buffer(b_accum, 0, None);- self.sync_tables(&up, &mut enc);self.queue.submit([enc.finish()]);// One dispatch per sample; params are rewritten between submissions. Batch a few per submit.let batch = 4u32;@@ -4515,9 +4422,9 @@ mod tests {out};let mut checked = 0;- for (hwrt, merged, uniform_tables, whole_tables) in [(true, false, false, false), (true, false, true, false), (true, false, false, true), (false, false, false, false), (false, false, true, false), (false, false, false, true), (false, true, false, false)] {+ for (hwrt, merged, whole_tables) in [(true, false, false), (true, false, true), (false, false, false), (false, false, true), (false, true, false)] {for room in [false, true] {- let mut layout: Vec<Entry> = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard: room }).iter().enumerate().flat_map(|(g, es)| es.iter().map(move |e| (g as u32, e.binding, e.ty))).collect();+ let mut layout: Vec<Entry> = kernel_layout_entries(LayoutShape { hwrt, merged, whole_tables, guard: room }).iter().enumerate().flat_map(|(g, es)| es.iter().map(move |e| (g as u32, e.binding, e.ty))).collect();layout.sort_by_key(|e| (e.0, e.1));for guard in [None, Some(1 << 16)] {// (As written, a kernel with the guard needs the room.)@@ -4529,20 +4436,20 @@ mod tests {if guard.is_none() && !merged {want.retain(|e| (e.0, e.1) != (1, crate::merged::GUARD_BINDING));}- let v = KernelVariant { merged, uniform_tables, whole_tables, guard, ..KernelVariant::new(hwrt, KernelSwitches::default(), features) };+ let v = KernelVariant { merged, whole_tables, guard, ..KernelVariant::new(hwrt, KernelSwitches::default(), features) };assert_eq!(declared(&v), want, "{v:?} in a layout {} room for the guard", if room { "with" } else { "without" });checked += 1;}}}}- assert_eq!(checked, 3 * 3 + 3 * 6 + 8);+ assert_eq!(checked, 2 * 3 + 2 * 6 + 8);}/// The native default has no loop guard, and the live passes are their file. Every variant the kernel's flags/// make is valid WGSL (naga, wgpu's front end): each traversal with no switch, each alone and all of them, by no- /// scene feature, each alone and all of them (units are software traversal's), with the uniform tables, with the- /// tables read whole, and with the loop guard. (The merged layout's: merged.rs.) Prints the default variants'+ /// scene feature, each alone and all of them (units are software traversal's), with the tables read whole, and+ /// with the loop guard. (The merged layout's: merged.rs.) Prints the default variants'/// SHA-256 (`--nocapture`).#[test]fn every_kernel_variant_is_valid() {@@ -4572,7 +4479,6 @@ mod tests {naga_valid(&kernel_wgsl(&template, &KernelVariant::new(hwrt, k, if hwrt { f & !F_UNITS } else { f })));}let all_features = KernelVariant::new(hwrt, k, if hwrt { F_SOURCE & !F_UNITS } else { F_SOURCE });- naga_valid(&kernel_wgsl(&template, &KernelVariant { uniform_tables: true, ..all_features }));naga_valid(&kernel_wgsl(&template, &KernelVariant { whole_tables: true, ..all_features }));naga_valid(&kernel_wgsl(&template, &KernelVariant { guard: Some(1 << 16), ..all_features }));}@@ -4625,16 +4531,16 @@ mod tests {}/// With nothing set, every platform but Android opens the device as it was before the options existed: no- /// uniform tables, no pipeline cache, the kernel's source the files (`every_kernel_variant_is_valid` prints the- /// default variants' hashes). Android's defaults are the uniform tables and the switches its GPUs needed; the environment overrides- /// either way, and the merged layout never has the uniform tables.+ /// pipeline cache, the kernel's source the files (`every_kernel_variant_is_valid` prints the default variants'+ /// hashes). Android's defaults are the tables read whole and the switches its GPUs needed; the environment+ /// overrides either way, and the merged layout never has the views.#[test]fn the_options_default_to_the_device_as_written() {let vars = |set: &'static [(&'static str, &'static str)]| move |name: &str| set.iter().find(|(n, _)| *n == name).map(|(_, v)| v.to_string());let desktop = GpuOptions::from_vars(&vars(&[]), false);assert_eq!(desktop, GpuOptions::default());assert_eq!(desktop.kernel, KernelSwitches { strict: false, cutout_lite: 0, last_direct: false, last_sun: false, light_pick: false });- assert!(!desktop.uniform_tables_on(false, false) && desktop.table_views_on(false, false));+ assert!(desktop.table_views_on(false, false));for hwrt in [false, true] {assert!(KernelVariant::new(hwrt, desktop.kernel, 0).flags().iter().all(|&(name, on)| on == (name == "hwrt" && hwrt)));}@@ -4643,21 +4549,19 @@ mod tests {// `sun`: the directional lights alone at the last vertex, in place of all of them, on either platform.let sun = GpuOptions::from_vars(&vars(&[("THREERT_LAST_DIRECT", "sun")]), true);assert_eq!((sun.kernel.last_direct, sun.kernel.last_sun), (false, true));- assert_eq!((android.uniform_tables, android.table_views, android.pipeline_cache.clone()), (None, None, None));- // Android reads the tables whole (no views, so no uniform copies of four of them); with the views asked for,- // the uniform copies as before.- assert!(!android.table_views_on(false, true) && !android.uniform_tables_on(false, true) && !android.uniform_tables_on(true, true));+ assert_eq!((android.table_views, android.pipeline_cache.clone()), (None, None));+ // Android reads the tables whole; with the views asked for, the views.+ assert!(!android.table_views_on(false, true));let views = GpuOptions::from_vars(&vars(&[("THREERT_TABLE_VIEWS", "1")]), true);- assert!(views.table_views_on(false, true) && views.uniform_tables_on(false, true) && !views.table_views_on(true, true));+ assert!(views.table_views_on(false, true) && !views.table_views_on(true, true));// Set: what is asked, on either platform.- let off = GpuOptions::from_vars(&vars(&[("THREERT_UNIFORM_TABLES", "0"), ("THREERT_KERNEL_STRICT", "0"), ("THREERT_CUTOUT_LITE", "0"), ("THREERT_LAST_DIRECT", "0")]), true);- assert_eq!((off.kernel, off.uniform_tables_on(false, true)), (KernelSwitches::default(), false));- let on = GpuOptions::from_vars(&vars(&[("THREERT_UNIFORM_TABLES", "1"), ("THREERT_CUTOUT_LITE", "2"), ("THREERT_LIGHT_PICK", "1"), ("THREERT_PIPELINE_CACHE", "/data/cache/pipelines")]), false);- assert!(on.uniform_tables_on(false, false) && !on.uniform_tables_on(true, false));- // Elsewhere the views unless asked otherwise; without them no uniform tables, whatever is asked.+ let off = GpuOptions::from_vars(&vars(&[("THREERT_KERNEL_STRICT", "0"), ("THREERT_CUTOUT_LITE", "0"), ("THREERT_LAST_DIRECT", "0")]), true);+ assert_eq!(off.kernel, KernelSwitches::default());+ let on = GpuOptions::from_vars(&vars(&[("THREERT_CUTOUT_LITE", "2"), ("THREERT_LIGHT_PICK", "1"), ("THREERT_PIPELINE_CACHE", "/data/cache/pipelines")]), false);+ // Elsewhere the views unless asked otherwise.assert!(on.table_views_on(false, false) && !on.table_views_on(true, false));- let whole = GpuOptions::from_vars(&vars(&[("THREERT_TABLE_VIEWS", "0"), ("THREERT_UNIFORM_TABLES", "1")]), false);- assert!(!whole.table_views_on(false, false) && !whole.uniform_tables_on(false, false));+ let whole = GpuOptions::from_vars(&vars(&[("THREERT_TABLE_VIEWS", "0")]), false);+ assert!(!whole.table_views_on(false, false));assert_eq!(on.kernel, KernelSwitches { strict: false, cutout_lite: 2, last_direct: false, last_sun: false, light_pick: true });assert_eq!(on.pipeline_cache.as_deref(), Some(std::path::Path::new("/data/cache/pipelines")));assert_eq!(GpuOptions::from_vars(&vars(&[("THREERT_PIPELINE_CACHE", "")]), true).pipeline_cache, None);@@ -4731,31 +4635,6 @@ mod tests {}}- /// The uniform tables' buffers: each array fits a uniform binding of 64 KiB, the media's holds every medium a- /// scene may have, and the four are at their own bindings, before the acceleration structure's. A copy takes what- /// the table's section and its uniform buffer both hold, in whole words; a scene with more entries than an array- /// is said, by name.- #[test]- fn the_uniform_tables_fit_their_bindings() {- use crate::merged::UNIFORM_TABLES;- for t in &UNIFORM_TABLES {- assert!(kernel_template().contains(&format!("@group(0) @binding({}) var<uniform> {}: array<", t.binding, t.name)), "{}", t.name);- let bytes = t.stride * t.len as u64;- assert!(bytes <= 65536 && bytes % 16 == 0 && t.binding < ACC_BINDING, "{}: {bytes} bytes", t.name);- }- assert_eq!(UNIFORM_TABLES.each_ref().map(|t| t.table), [Table::TexInfo, Table::Objects, Table::Instances, Table::Media]);- assert_eq!(UNIFORM_TABLES[3].len as usize, crate::scene::MAX_MEDIA);- assert_eq!(UNIFORM_TABLES[2].len as u64, 65536 / UNIFORM_TABLES[2].stride);- assert_eq!([UNIFORM_TABLES[2].stride as usize, UNIFORM_TABLES[3].stride as usize], [std::mem::size_of::<crate::scene::GpuInstance>(), std::mem::size_of::<crate::scene::MediumGpu>()]);- assert!(kernel_template().contains(&format!("@group(0) @binding({ACC_BINDING}) var acc: acceleration_structure;")));- // A table shorter than its array, one with the edits' room past it, one whose size is not the array's multiple.- assert_eq!([uniform_copy_bytes(512, 65536), uniform_copy_bytes(1 << 20, 65536), uniform_copy_bytes(65600, 65440), uniform_copy_bytes(0, 7168), uniform_copy_bytes(7, 64)], [512, 65536, 65440, 0, 4]);- assert!(uniform_overflow([4096, 4096, 409, 32]).is_empty());- let notes = uniform_overflow([4096, 4099, 1024, 32]);- assert_eq!(notes.len(), 2);- assert!(notes[0].contains("4099 entries of `objects`") && notes[0].contains("holds 4096") && notes[1].contains("1024 entries of `instances`"), "{notes:?}");- }-/// The order of a layout's entries and of a bind group's is not the device's to see: wgpu puts both in binding/// order before its backend gets them (wgpu-core 30: `bgl::EntryMap::from_entries` sorts a layout's, and/// `create_bind_group` its entries), and takes two layouts of the same entries as one. So the kernel's layout,diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 40181d9..fb89230 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -392,15 +392,12 @@ pub fn light_order(lights: &[scene::GpuLight]) -> Vec<usize> {/// The light groups' table: per group of LIGHT_GROUP local lights (counted from the first local one) the sphere/// (centre, radius) holding every point its lights reach. Black lights (off, or hidden: `scene::gpu_light_shown`)/// reach nothing and are in no sphere; a group of them alone has radius -1 (no point is in it).-/// THREERT_LIGHT_GROUPS=0: unbounded spheres, every light tested (A/B).pub fn light_groups(lights: &[scene::GpuLight]) -> Vec<[f32; 4]> {- static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- let off = *OFF.get_or_init(|| std::env::var("THREERT_LIGHT_GROUPS").is_ok_and(|v| v == "0"));let nd = lights.iter().take_while(|l| l.pos[3] == 0.0).count();let mut out = vec![];for g in lights[nd..].chunks(LIGHT_GROUP) {let lit = |l: &&scene::GpuLight| l.color[..3].iter().any(|c| *c > 0.0);- if !off && !g.iter().any(|l| lit(&l)) {+ if !g.iter().any(|l| lit(&l)) {out.push([0.0, 0.0, 0.0, -1.0]);continue;}@@ -415,9 +412,6 @@ pub fn light_groups(lights: &[scene::GpuLight]) -> Vec<[f32; 4]> {let reach = light_reach(l);r = if reach == f32::MAX { f32::MAX } else { r.max(c.distance(Vec3::from_slice(&l.pos[..3])) + reach) };}- if off {- r = f32::MAX;- }// Margin for rounding in the kernel's distance (positions up to a few km).if r < f32::MAX {r = r * (1.0 + 1e-5) + 1e-3 * (1.0 + c.abs().max_element() * 1e-3);diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex dbe182c..a9ae806 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -106,9 +106,6 @@ pub(super) struct EditState {/// Times the room grew (frame log `grows`), and whether the scene bind group must be made again.pub(super) grows: u32,pub(super) rebind: bool,- /// The uniform tables (`gpu::Gpu::uniform_tables`): an edit placed entries past what their arrays hold, and it- /// was said (once a scene, as its upload says it of the scene's own).- pub(super) uniform_said: bool,/// (triangles, records, objects, words, TLAS instances) the scene itself has: the room starts there.pub(super) base: (usize, usize, usize, usize, usize),/// The instances' rows (`scene::Row`) edits can place, as the records are, and the run each record an edit placed@@ -3502,14 +3499,6 @@ impl LiveCore {if std::mem::take(&mut edit.rebind) {g.rebind_scene(up);}- // The uniform tables: entries the edits placed past what a uniform buffer holds read as its last one.- if g.uniform_tables && !edit.uniform_said {- let notes = gpu::uniform_overflow([0, (edit.objects.end * tables.stride) as u64, edit.records.end as u64, 0]);- for note in ¬es {- eprintln!("threert: {note}");- }- edit.uniform_said = !notes.is_empty();- }split.objects = ch.added.len() + ch.removed.len();self.edit_split.add(&split);if emitters_changed {diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex 3fa9fbf..f6cc507 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -336,7 +336,7 @@ impl LiveCore {// Light-sampled particles (sparks: Particles emitterArea) move their light every frame: the cache and// the temporal pass keep the short history of a lighting edit while the scene has them.let lit = self.live_lighting();- p.cache = [1.0, CACHE_SAMPLES, if lit { CACHE_FRAMES_LIT } else { CACHE_FRAMES }, cache_flags() as f32];+ p.cache = [1.0, CACHE_SAMPLES, if lit { CACHE_FRAMES_LIT } else { CACHE_FRAMES }, 0.0];}p.time[0] = shader_time(self.time);p.cam_pos = [cam.pos.x, cam.pos.y, cam.pos.z, cam.tan_half_fov];@@ -390,11 +390,6 @@ impl LiveCore {if let (Some(f), 0) = (&self.sc.up.fills.particles, k) {g.fill_emitters(f, &mut e);}- // (The uniform tables: their sections as this frame's edits and the particle passes above left them, where- // the kernel reads them; merged.rs.)- if k == 0 {- g.sync_tables(&self.sc.up, &mut e);- }{let tw = match (&self.profile, &self.timer, timed) {(Some(p), _, _) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) }),@@ -499,7 +494,7 @@ impl LiveCore {let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.buf("sb").buffer } else { &self.targets.buf("fa").buffer };// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).let low = (iw, ih) != (w, h);- let tp = gpu::TranslucentParams { size: [w, h, 0, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, translucent_hidden(self.frame) as u32 as f32, 0.0, 0.0] };+ let tp = gpu::TranslucentParams { size: [w, h, 0, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, 0.0, 0.0, 0.0] };g.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));(pipes, g.translucent_bind_group(t, target, self.targets.translucent_low.as_ref().expect("made at the frame's start")), &t.count)});diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex 9a20026..1fe8bb9 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -322,7 +322,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pdead_meshes: vec![],grows: 0,rebind: false,- uniform_said: false,base: room_base,rows: Holes::new(rows.len(), rows.len() + room.records),row_runs: Default::default(),diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex 919c562..6a2e535 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -423,14 +423,6 @@ fn govern_by_clock() -> bool {*F.get_or_init(|| std::env::var("THREERT_GOVERN_CLOCK").map(|v| v == "1").unwrap_or(cfg!(target_os = "android")))}-/// THREERT_CACHE_FLAGS: experiment switches of the radiance cache (pathtrace.wgsl `cfl`), 0 = defaults: 2 = no hit-/// lighting (reflection hits use the cache's total), 4 = no training tiles, 8 = the exact light loop at reflection-/// hits, 16 = no reflection resolve. THREERT_CACHE=0 turns the cache off.-fn cache_flags() -> u32 {- static F: std::sync::OnceLock<u32> = std::sync::OnceLock::new();- *F.get_or_init(|| std::env::var("THREERT_CACHE_FLAGS").ok().and_then(|v| v.parse().ok()).unwrap_or(0))-}-/// THREERT_FREEZE_TIME=1: animation holds still (shader time 0, the frame script gets dt 0: signs, screens, flicker groups),/// so frames taken at different times compare (tools/bench-ghosting.ts).fn freeze_time() -> bool {@@ -526,17 +518,6 @@ const HISTORY_LIVE: f32 = 24.0;/// The most once the scene has settled: holding still, the frame converges on the offline render.const HISTORY_FRAMES: f32 = 4096.0;-/// THREERT_TL_HIDE (diagnostics): the translucency pass trains the volume voxels but draws nothing, so frames show what is-/// behind translucent particles; `odd` hides them on odd frames only (rain on / off pairs from one run).-fn translucent_hidden(frame: u32) -> bool {- static F: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();- match F.get_or_init(|| std::env::var("THREERT_TL_HIDE").ok().map(|v| v == "odd")) {- None => false,- Some(false) => true,- Some(true) => frame % 2 == 1,- }-}-impl LiveCore {/// Advances the scene time by a frame's dt (the frame script's: at most 0.1 s).pub fn advance_time(&mut self, dt: f32) {@@ -1407,7 +1388,7 @@ mod instanced_tests {if views.merged {return eprintln!("skipped: the merged layout reads the tables whole already");}- assert!(whole.whole_tables && !views.whole_tables && !whole.uniform_tables);+ assert!(whole.whole_tables && !views.whole_tables);let w = lit_world();let presets = crate::default_presets_dir();let offline = |g: &gpu::Gpu| {@@ -1439,78 +1420,4 @@ mod instanced_tests {assert!(x.iter().any(|v| *v != 0), "the live frame has a picture");assert_eq!(x, y, "the live frames differ between the views and the tables read whole");}-- /// The uniform tables (`gpu::GpuOptions::uniform_tables`: what a device is opened with on Android), on this- /// machine's GPU: a lit scene with an instanced mesh renders offline to the default device's image, bit for bit;- /// live, the four uniform buffers hold what their tables hold when a frame is traced, and after an edit in place- /// what the tables hold then. (Skipped without a GPU.)- #[test]- fn the_uniform_tables_render_what_the_tables_do() {- let open = |uniform: bool| gpu::Gpu::new_with(gpu::GpuOptions { uniform_tables: Some(uniform), ..Default::default() });- let (plain, uniform) = match (open(false), open(true)) {- (Ok(a), Ok(b)) => (a, b),- (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),- };- if uniform.merged {- return eprintln!("skipped: the merged layout has no uniform tables");- }- assert!(uniform.uniform_tables && !plain.uniform_tables);- let mut w = lit_world();- let presets = crate::default_presets_dir();-- // Offline: the same bytes.- let offline = |g: &gpu::Gpu| {- let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();- (sc.width, sc.height) = (64, 36);- let prep = crate::prepare(g, &mut sc, &mut vec![]);- let frame = g.render(&sc, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();- frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()- };- let (a, b) = (offline(&plain), offline(&uniform));- let lit = a.iter().filter(|v| f32::from_bits(**v) > 0.0).count();- assert!(lit > a.len() / 16, "the scene is lit ({lit} of {} numbers)", a.len());- let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count();- assert_eq!(differ, 0, "{differ} of {} numbers differ between the storage tables and the uniform ones", a.len());- drop(plain);-- // Live: the uniform buffers follow the tables.- let mut core = LiveCore::new(uniform, &w, Path::new("."), &presets, 64, 36).unwrap();- w.take_changes();- let read = |core: &LiveCore, buf: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {- let d = &core.g.device;- let to = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let mut e = d.create_command_encoder(&Default::default());- e.copy_buffer_to_buffer(buf, at, &to, 0, bytes);- core.g.queue.submit([e.finish()]);- to.slice(..).map_async(wgpu::MapMode::Read, |_| {});- d.poll(wgpu::PollType::wait_indefinitely()).unwrap();- let bytes = to.slice(..).get_mapped_range().unwrap().to_vec();- bytes- };- // Each table's section and its uniform copy, over what both hold.- let pairs = |core: &LiveCore| -> Vec<(Vec<u8>, Vec<u8>)> {- let up = &core.sc.up;- let copies = up.uniform.as_ref().expect("the uniform tables' buffers");- crate::merged::UNIFORM_TABLES.iter().zip(copies).map(|(t, c)| {- let n = up.heap.cap(t.table).min(c.size()) & !3;- (read(core, &up.heap.buffer, up.heap.at(t.table), n), read(core, c, 0, n))- }).collect()- };- core.render(1, |_, _| {});- let first = pairs(&core);- for (k, (table, copy)) in first.iter().enumerate() {- assert!(!table.is_empty() && table == copy, "table {k} and its uniform buffer differ after a frame");- }- assert!(first[1].0.iter().any(|b| *b != 0), "the objects' table has the scene's objects");- // The panel moves in place: its object's entry and its instance's record change, and the next frame's- // uniform buffers have them.- w.set_transform(11, Vec3::new(0.3, 0.2, 0.75), glam::Quat::IDENTITY, Vec3::ONE).unwrap();- assert!(!core.commit(&mut w).unwrap(), "moved in place");- core.render(1, |_, _| {});- let moved = pairs(&core);- for (k, (table, copy)) in moved.iter().enumerate() {- assert!(table == copy, "table {k} and its uniform buffer differ after an edit");- }- assert!(moved[1].1 != first[1].1 || moved[2].1 != first[2].1, "the move reached the uniform buffers");- }}diff --git a/renderer/src/merged.rs b/renderer/src/merged.rsindex e2a8e36..6213db3 100644--- a/renderer/src/merged.rs+++ b/renderer/src/merged.rs@@ -42,38 +42,6 @@ pub const GUARD_WORDS: u32 = 4;/// written only.pub const DEFERRED_BINDING: u32 = 9;-/// The uniform tables (`gpu::GpuOptions::uniform_tables`; docs/RUNTIME.md "Android"): the tables the kernel reads-/// from uniform buffers, copies of their sections, instead of from views of the sections. Qualcomm's Adreno 740 driver-/// (Vulkan, Android 13) gave the kernel other buffers' contents for these four when each was a read-only storage-/// buffer: a model's textures came out as another table's numbers, instance records sent hits to the wrong-/// triangles, an emissive object's power read as something else's and lit nothing. As uniform buffers they read-/// right. (Whether they read right as views of the tables' buffer, which no device has run yet, is not known:-/// until one has, Android keeps the copies.)-///-/// In the kernel (pathtrace.wgsl, `@if(uniform_tables)`) the four are sized uniform arrays at their own bindings, and-/// every index into them is held to the array (`tex_info_at` and the others: `min(i, last)`). A scene with more-/// entries than an array holds reads the last one for the rest (the renderer says so when it uploads one,-/// `Gpu::upload`); nothing is read outside the buffer, which the kernel's unchecked indexing would otherwise do.-///-/// An array's length (a uniform buffer's array is sized) is what 64 KiB hold, the size every device gives a uniform-/// binding (WebGPU's `maxUniformBufferBindingSize`, Vulkan's least `maxUniformBufferRange` on the phones this is-/// for), and for the media what a scene may have (`scene::MAX_MEDIA`). In a scene's terms: 2,048 textures, 1,365-/// objects (1,024 with instance colours), 409 instance records, every medium.-pub struct UniformTable {- pub table: Table,- /// Its array in the kernel, the array's binding (group 0) and length, and its element's bytes.- pub name: &'static str,- pub binding: u32,- pub len: u32,- pub stride: u64,-}-pub const UNIFORM_TABLES: [UniformTable; 4] = [- UniformTable { table: Table::TexInfo, name: "tex_info", binding: 15, len: 4096, stride: 16 },- UniformTable { table: Table::Objects, name: "objects", binding: 16, len: 4096, stride: 16 },- UniformTable { table: Table::Instances, name: "instances", binding: 17, len: 409, stride: 160 },- UniformTable { table: Table::Media, name: "media", binding: 18, len: 32, stride: 224 },-];-#[cfg(test)]mod tests {use super::*;@@ -137,48 +105,6 @@ mod tests {}}- /// Every kernel variant with the uniform tables: valid WGSL; the four tables are uniform buffers at their own- /// bindings, sized as the Rust side makes their buffers; the storage buffers are as written; and each of the- /// four is indexed once, in its accessor, held to its array, so nothing is read outside a uniform buffer.- #[test]- fn the_uniform_tables_are_four_sized_uniform_arrays() {- let globals = |m: &naga::Module, uniform: bool| -> Vec<(String, u32, u32)> {- let mut out: Vec<(String, u32, u32)> = m- .global_variables- .iter()- .filter(|(_, v)| if uniform { v.space == naga::AddressSpace::Uniform } else { matches!(v.space, naga::AddressSpace::Storage { .. }) })- .map(|(_, v)| {- let b = v.binding.as_ref().expect("a bound global");- let bytes = match &m.types[v.ty].inner {- naga::TypeInner::Array { size: naga::ArraySize::Constant(n), stride, .. } => n.get() * stride,- _ => 0,- };- (v.name.clone().unwrap_or_default(), b.group * 100 + b.binding, bytes)- })- .collect();- out.sort_by_key(|g| g.1);- out- };- let (written, _) = parse(&variant(0, false));- for features in [0, crate::gpu::F_VCOLOR, crate::gpu::F_GRID, crate::gpu::F_TINT | crate::gpu::F_UNLIT | crate::gpu::F_BACKGROUND, crate::gpu::F_SOURCE] {- let src = kernel_wgsl(&kernel_template(), &KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), features) });- let (m, info) = parse(&src);- assert_eq!(storage_buffers(&m, &info).1, 18, "features {features:#x}");- let tables: Vec<(String, u32, u32)> = globals(&m, true).into_iter().filter(|g| g.0 != "P").collect();- let want: Vec<(String, u32, u32)> = UNIFORM_TABLES.iter().map(|t| (t.name.to_string(), t.binding, (t.stride * t.len as u64) as u32)).collect();- assert_eq!(tables, want, "features {features:#x}");- // The storage buffers that stay: the same names at the same bindings as the kernel as written.- let kept = |m: &naga::Module| globals(m, false).into_iter().map(|g| (g.0, g.1)).filter(|g| !want.iter().any(|w| w.0 == g.0)).collect::<Vec<_>>();- assert_eq!(kept(&m), kept(&written), "features {features:#x}");- for t in &UNIFORM_TABLES {- let name = t.name;- let upper = name.to_uppercase();- assert_eq!(src.matches(&format!("{name}[")).count(), 1, "{name}: indexed in its accessor only (features {features:#x})");- assert!(src.contains(&format!("{name}[min(i, UT_{upper} - 1u)]")), "{name}: held to its array");- }- }- }-/// The kernel reads a record from as many vec4s of the tables as the Rust side's record has, and makes of them/// a struct of that size.#[test]@@ -260,15 +186,13 @@ mod tests {assert_eq!(first("for (var k"), "if (e) {", "{g}");}- /// The constants a variant imports are the ones it is given, by name: a guard's limit, the uniform tables'- /// lengths. The merged layout has none of its own.+ /// The constants a variant imports are the ones it is given, by name: the guard's words and its limit. The+ /// merged layout has none of its own.#[test]fn the_variant_gives_what_it_imports() {let v = KernelVariant { merged: true, guard: Some(9), ..KernelVariant::new(false, Default::default(), 0) };assert_eq!(v.constants(), vec![("GUARD_WORDS".into(), GUARD_WORDS), ("LOOP_GUARD_LIMIT".into(), 9)]);assert_eq!(KernelVariant { merged: true, ..Default::default() }.constants(), vec![("GUARD_WORDS".into(), GUARD_WORDS)]);- let u = KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), 0) }.constants();- assert_eq!(u, vec![("UT_TEX_INFO".into(), 4096), ("UT_OBJECTS".into(), 4096), ("UT_INSTANCES".into(), 409), ("UT_MEDIA".into(), 32)]);assert!(KernelVariant::default().constants().is_empty());}diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 8d2f57a..a2c33bf 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -1880,10 +1880,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet pkey = (key.clone(), rigid_pose_key(a));if !rigid_parts.contains_key(&pkey) {let moving = glb.moving_nodes(a)?;- // (THREERT_RIGID_NODES=all: no node merged, every one an instance of a mesh of its own: the A/B- // against the merged still part.)- let all = std::env::var("THREERT_RIGID_NODES").is_ok_and(|v| v == "all");- let apart = |ni: usize| all || moving[ni];+ let apart = |ni: usize| moving[ni];// The nodes left alone, in the model's space as the pose has them (the pose does not move// them); then each node apart, in its own (the order within a node is the file's).let mut lists: Vec<(usize, Vec<crate::skin::ModelTri>)> = vec![];