@woosh/meep-engine 3.35.0 → 3.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/package.json +1 -1
  2. package/src/engine/Engine.d.ts +2 -0
  3. package/src/engine/Engine.d.ts.map +1 -1
  4. package/src/engine/Engine.js +5 -1
  5. package/src/engine/input/devices/XRInputDevice.d.ts +91 -0
  6. package/src/engine/input/devices/XRInputDevice.d.ts.map +1 -0
  7. package/src/engine/input/devices/XRInputDevice.js +479 -0
  8. package/src/engine/input/devices/xr/XRGamepadMapping.d.ts +14 -0
  9. package/src/engine/input/devices/xr/XRGamepadMapping.d.ts.map +1 -0
  10. package/src/engine/input/devices/xr/XRGamepadMapping.js +9 -0
  11. package/src/engine/input/devices/xr/XRHandedness.d.ts +15 -0
  12. package/src/engine/input/devices/xr/XRHandedness.d.ts.map +1 -0
  13. package/src/engine/input/devices/xr/XRHandedness.js +10 -0
  14. package/src/engine/input/devices/xr/XRInputAction.d.ts +50 -0
  15. package/src/engine/input/devices/xr/XRInputAction.d.ts.map +1 -0
  16. package/src/engine/input/devices/xr/XRInputAction.js +116 -0
  17. package/src/engine/input/devices/xr/XRInputButton.d.ts +26 -0
  18. package/src/engine/input/devices/xr/XRInputButton.d.ts.map +1 -0
  19. package/src/engine/input/devices/xr/XRInputButton.js +53 -0
  20. package/src/engine/input/devices/xr/XRInputCoordinates.d.ts +23 -0
  21. package/src/engine/input/devices/xr/XRInputCoordinates.d.ts.map +1 -0
  22. package/src/engine/input/devices/xr/XRInputCoordinates.js +35 -0
  23. package/src/engine/input/devices/xr/XRInputHandle.d.ts +93 -0
  24. package/src/engine/input/devices/xr/XRInputHandle.d.ts.map +1 -0
  25. package/src/engine/input/devices/xr/XRInputHandle.js +268 -0
  26. package/src/engine/input/devices/xr/XRInputPose.d.ts +59 -0
  27. package/src/engine/input/devices/xr/XRInputPose.d.ts.map +1 -0
  28. package/src/engine/input/devices/xr/XRInputPose.js +77 -0
  29. package/src/engine/input/devices/xr/XRInputTypes.d.ts +76 -0
  30. package/src/engine/input/devices/xr/XRInputTypes.d.ts.map +1 -0
  31. package/src/engine/input/devices/xr/XRInputTypes.js +31 -0
  32. package/src/engine/input/devices/xr/XRInputValueSource.d.ts +11 -0
  33. package/src/engine/input/devices/xr/XRInputValueSource.d.ts.map +1 -0
  34. package/src/engine/input/devices/xr/XRInputValueSource.js +11 -0
  35. package/src/engine/input/devices/xr/XRTargetRayMode.d.ts +17 -0
  36. package/src/engine/input/devices/xr/XRTargetRayMode.d.ts.map +1 -0
  37. package/src/engine/input/devices/xr/XRTargetRayMode.js +12 -0
  38. package/src/engine/input/devices/xr/XRVisibilityState.d.ts +15 -0
  39. package/src/engine/input/devices/xr/XRVisibilityState.d.ts.map +1 -0
  40. package/src/engine/input/devices/xr/XRVisibilityState.js +10 -0
  41. package/src/engine/input/ecs/ism/coordinate/InputCoordinateChannel.d.ts +15 -1
  42. package/src/engine/input/ecs/ism/coordinate/InputCoordinateChannel.d.ts.map +1 -1
  43. package/src/engine/input/ecs/ism/coordinate/InputCoordinateChannel.js +9 -0
  44. package/src/engine/input/ecs/ism/coordinate/InputCoordinateDevice.d.ts +17 -4
  45. package/src/engine/input/ecs/ism/coordinate/InputCoordinateDevice.d.ts.map +1 -1
  46. package/src/engine/input/ecs/ism/coordinate/InputCoordinateDevice.js +26 -0
  47. package/src/engine/input/ecs/ism/coordinate/InputCoordinateSwitches.d.ts +17 -2
  48. package/src/engine/input/ecs/ism/coordinate/InputCoordinateSwitches.d.ts.map +1 -1
  49. package/src/engine/input/ecs/ism/device/GamepadInputDeviceAdapter.d.ts +5 -0
  50. package/src/engine/input/ecs/ism/device/GamepadInputDeviceAdapter.d.ts.map +1 -1
  51. package/src/engine/input/ecs/ism/device/InputDeviceAdapter.d.ts +2 -0
  52. package/src/engine/input/ecs/ism/device/InputDeviceAdapter.d.ts.map +1 -1
  53. package/src/engine/input/ecs/ism/device/InputDeviceAdapter.js +2 -0
  54. package/src/engine/input/ecs/ism/device/KeyboardInputDeviceAdapter.d.ts +7 -0
  55. package/src/engine/input/ecs/ism/device/KeyboardInputDeviceAdapter.d.ts.map +1 -1
  56. package/src/engine/input/ecs/ism/device/ManualInputDeviceAdapter.d.ts +5 -0
  57. package/src/engine/input/ecs/ism/device/ManualInputDeviceAdapter.d.ts.map +1 -1
  58. package/src/engine/input/ecs/ism/device/PointerInputDeviceAdapter.d.ts +5 -0
  59. package/src/engine/input/ecs/ism/device/PointerInputDeviceAdapter.d.ts.map +1 -1
  60. package/src/engine/input/ecs/ism/device/XRInputDeviceAdapter.d.ts +30 -0
  61. package/src/engine/input/ecs/ism/device/XRInputDeviceAdapter.d.ts.map +1 -0
  62. package/src/engine/input/ecs/ism/device/XRInputDeviceAdapter.js +87 -0
  63. package/src/engine/input/ecs/ism/device/XR_INPUT_DEVICE_IDS.d.ts +15 -0
  64. package/src/engine/input/ecs/ism/device/XR_INPUT_DEVICE_IDS.d.ts.map +1 -0
  65. package/src/engine/input/ecs/ism/device/XR_INPUT_DEVICE_IDS.js +22 -0
  66. package/src/engine/input/ecs/ism/trigger/InputTrigger.d.ts +11 -1
  67. package/src/engine/input/ecs/ism/trigger/InputTrigger.d.ts.map +1 -1
  68. package/src/engine/input/ecs/ism/trigger/InputTrigger.js +7 -0
  69. package/src/engine/input/ecs/ism/trigger/InputTriggerChord.d.ts +16 -2
  70. package/src/engine/input/ecs/ism/trigger/InputTriggerChord.d.ts.map +1 -1
  71. package/src/engine/input/ecs/ism/trigger/InputTriggerHold.d.ts +22 -2
  72. package/src/engine/input/ecs/ism/trigger/InputTriggerHold.d.ts.map +1 -1
  73. package/src/engine/input/ecs/ism/trigger/InputTriggerRelease.d.ts +16 -2
  74. package/src/engine/input/ecs/ism/trigger/InputTriggerRelease.d.ts.map +1 -1
  75. package/src/engine/input/ecs/ism/trigger/InputTriggerSequence.d.ts +24 -4
  76. package/src/engine/input/ecs/ism/trigger/InputTriggerSequence.d.ts.map +1 -1
  77. package/src/engine/input/ecs/ism/trigger/InputTriggerSwitch.d.ts +6 -8
  78. package/src/engine/input/ecs/ism/trigger/InputTriggerSwitch.d.ts.map +1 -1
  79. package/src/engine/input/ecs/ism/trigger/InputTriggerSwitch.js +5 -0
  80. package/src/engine/input/ecs/ism/trigger/InputTriggerXRButton.d.ts +15 -0
  81. package/src/engine/input/ecs/ism/trigger/InputTriggerXRButton.d.ts.map +1 -0
  82. package/src/engine/input/ecs/ism/trigger/InputTriggerXRButton.js +25 -0
  83. package/src/engine/physics/fluid/ecs/FluidObstacleSystem.d.ts +4 -4
  84. package/src/shade/renderer/animation/chunk_pose_accumulator.js +14 -24
  85. package/src/shade/renderer/animation/skinning/bounds_refresh/shader_meshlet_bounds_reduce.js +16 -15
  86. package/src/shade/renderer/deferred/indirect/chunk_lpv_sample_light.js +1 -1
  87. package/src/shade/renderer/gpu_primitive/bvh/GPU_BVH_BUILD_PLAN.md +1123 -1122
  88. package/src/shade/renderer/gpu_primitive/bvh/PHASE1_HANDOVER.md +202 -201
  89. package/src/shade/renderer/light/environment/chunk_roughness_to_mip_ratio.js +24 -0
  90. package/src/shade/renderer/light/environment/chunk_sphere_probe_roughness_to_lod.js +2 -25
  91. package/src/shade/renderer/light/environment/shader_project_environment_sh.d.ts +2 -2
  92. package/src/shade/renderer/light/environment/shader_project_environment_sh.d.ts.map +1 -1
  93. package/src/shade/renderer/light/environment/shader_project_environment_sh.js +50 -19
  94. package/src/shade/renderer/loader/gltf/tiny-gltf.d.ts +1 -1
  95. package/src/shade/renderer/particles/DESIGN.md +1 -1
  96. package/src/shade/renderer/particles/bounds/chunk_particle_bounds.js +10 -9
  97. package/src/shade/renderer/scene/shader_bvh_extract_instance_leaves.js +10 -8
  98. package/src/shade/renderer/shader/chunk/atomic/chunk_atomic_add_f32_storage.js +25 -0
  99. package/src/shade/renderer/shader/chunk/atomic/chunk_atomic_max_f32_storage.js +28 -0
  100. package/src/shade/renderer/shader/chunk/atomic/chunk_atomic_min_f32_storage.js +28 -0
  101. package/src/shade/renderer/shader/chunk/geometry/plane/{plane_ray_raycast.js → chunk_plane_ray_raycast.js} +1 -1
  102. package/src/shade/renderer/shadow/map/csm/shader/shader_csm_caster_range.js +3 -3
  103. package/src/shade/renderer/animation/skinning/bounds_refresh/chunk_aabb_atomic_f32.js +0 -59
@@ -1,201 +1,202 @@
1
- # Hand-over: implement Phase 1 of the GPU BVH builder
2
-
3
- You are implementing **Phase 1 only** of `GPU_BVH_BUILD_PLAN.md` (same directory — read it in
4
- full before writing any code; it is the authoritative design, this file is the execution brief).
5
- Phase 1 = two deliverables, in this order:
6
-
7
- 1. **A key-value radix sort** built around CSDLDF, re-founding `src/shade/renderer/gpu_primitive/sort/`.
8
- 2. **A GPU TLAS build** (LBVH: extract → morton → sort → Karras emission → refit) replacing the
9
- CPU-side work in `GPUInstancesAccelerationStructure.push_to_gpu()`.
10
-
11
- Do **not** start phases 2–4 (treelets, BLAS, BVH8), do not redesign node formats, do not add
12
- frameworks. Everything you need exists in the tree or in git history; this project's explicit
13
- standard is *port and reuse, don't invent*.
14
-
15
- ## Read these before writing code
16
-
17
- In order, each for a stated reason:
18
-
19
- 1. `src/shade/renderer/gpu_primitive/bvh/GPU_BVH_BUILD_PLAN.md` — the design. §2.1 is the byte
20
- contract, §4 is what you are building, §4.2.1 is the sort, §4.5 is the test plan you must
21
- satisfy, §6/§7 explain decisions — do not relitigate them.
22
- 2. `src/core/bvh2/bvh3/ebvh_build_hierarchy_radix.js` (+ its `.spec.js`) — the CPU oracle your
23
- emission kernel transliterates: `delta` with the `32 + clz32(i^j)` duplicate-key tiebreak,
24
- `determineRange`, `find_split`. Read the comment block at `find_split` about why duplicate
25
- codes must NOT be midpoint-split — that bug produces a shared-node non-tree.
26
- 3. `src/shade/renderer/gpu_primitive/prefix_sum/v1/shader_prefix_scan_csdldf.js` and
27
- `graph_prefix_scan_csdldf.js` — the blessed scan you reuse as the sort's spine, and the house
28
- subgroup idioms (`subgroup_size` builtin, `MIN_SUBGROUP_SIZE = 4`,
29
- `@diagnostic(off, subgroup_uniformity)` helpers, split flag words, bounded spin + fallback).
30
- 4. Git history of the deleted OneSweep port — orchestration + scatter/ranking reference:
31
- `git show 370542c3f:src/shade/renderer/gpu_primitive/sort/one_sweep/graph_radix_sort.js`
32
- (graph orchestration template), `...shader_digit_binning_pass_pairs.js` (workgroup ranking
33
- machinery + two pinned WebGPU lessons), `...one_sweep.spec.js` and
34
- `...verify_radix_sort_one_sweep.js` (spec/verify templates). List the directory with
35
- `git show 370542c3f:src/shade/renderer/gpu_primitive/sort/one_sweep/ 2>$null` or
36
- `git ls-tree 370542c3f -- src/shade/renderer/gpu_primitive/sort/one_sweep/`.
37
- 5. `src/shade/renderer/animation/skinning/bounds_refresh/shader_meshlet_bounds_reduce.js` +
38
- `chunk_aabb_atomic_f32.js` — the reduce-then-atomic-merge pattern for the scene-bounds pass,
39
- and the "same buffer bound as `array<atomic<u32>>` in one pass, typed in another" idiom the
40
- refit pass needs. Note its comment about `bitcast<f32>(0x7F800000u)` not const-folding.
41
- 6. `src/shade/renderer/scene/GPUInstancesAccelerationStructure.js`,
42
- `src/shade/renderer/scene/GPUSceneContext.js` (how `instance_add/remove/update` and
43
- `update()` drive it), `src/shade/renderer/geometry/bvh/bvh_to_gpu_buffer.js` +
44
- `bvh2_compress.js` (the legacy path you keep behind a flag),
45
- `src/shade/renderer/scene/MESH_INSTANCE_METADATA_STRUCT.js` (where per-row world AABBs live).
46
- 7. `src/shade/renderer/shader/chunk/geometry/ray/chunk_ray_query_nearest.js` — the traversal
47
- consumer; internalize its leaf/root conventions before emitting a single node.
48
- 8. Testing machinery: `src/shade/wgsl/emulator/ComputeShaderEmulator.js` + its `.spec.js` and a
49
- couple of existing chunk specs under `src/shade/renderer/shader/chunk/math/` (the established
50
- pattern for emulator-testing individual WGSL functions);
51
- `src/shade/device/mock/SoftwareGPUDevice.js` + `SoftwareGPUComputePassEncoder.js` (a
52
- **recording** device — executes no shaders; assert on what was encoded and on host-written
53
- bytes only); `src/shade/renderer/gpu_primitive/prefix_sum/v1/test_prefix_sum.js` and
54
- `src/shade/renderer/buffer/graph_inspect_gpu_buffer.js` (browser verify pattern);
55
- `src/shade/playground/bvh_repro/` — the standalone page where the `verify_*` functions get
56
- registered and run against a real device (`npm run dev`, then
57
- <http://localhost:5173/src/shade/playground/bvh_repro/index.html>).
58
-
59
- ## Non-negotiable contracts
60
-
61
- **Output bytes** (every RT consumer depends on this; there is no versioning):
62
- - Node = 32 bytes: `[min.x, min.y, min.z, max.x, max.y, max.z] : f32` then `child_1 : u32`,
63
- `child_2 : u32`.
64
- - Leaf ⇔ `child_1 == 0xFFFFFFFF` (`BVH_NULL_NODE`); then `child_2` = scene-database `meshes`
65
- row. Internal ⇒ both children are valid node indices with meaningful bounds.
66
- - TLAS buffer = `u32 root` at byte 0, nodes from byte 4. Your layout: root is node 0
67
- (Karras internal 0), internals `[0, N-2]`, leaves `[N-1, 2N-2]`. Still write the root word.
68
- - `N == 0` ⇒ write `root = BVH_NULL_NODE` host-side. `N == 1` ⇒ single leaf as node 0, root 0.
69
-
70
- **House rules:**
71
- - **Subgroups are a baseline engine requirement.** Use them wherever they pay. But do not bake
72
- wave-*width* assumptions into algorithm structure — subgroup size is a runtime value 4–128;
73
- workgroup memory is the correctness layer across subgroup boundaries.
74
- - **CSDLDF discipline:** no unbounded cross-workgroup waiting, ever. Bounded spin + fallback
75
- (the csdldf shader) or no spin at all (arrival counters where the loser exits — the refit).
76
- All cross-workgroup-communicated state goes through `array<atomic<u32>>` accesses exclusively.
77
- - **A vitest spec may never stand up a real GPU device.** Shade specs run under vitest
78
- (`npm test`); the four validation tiers of plan §4.5 are all mandatory.
79
- - Match existing code style exactly: `assert.*` guards on public entry points, `#private`
80
- fields, `chunk_*`/`shader_*`/`graph_*` naming, `CodeChunk.from(wgsl, [deps])` composition,
81
- `ShaderResourceSetDescriptor` for bindings, JSDoc in the house voice. Read neighbours, write
82
- like them.
83
- - Commit directly to `master`, conventional style with scope (`feat(shade): …`), incremental —
84
- one commit per milestone below is about right. Do not amend, do not branch.
85
-
86
- ## Milestones, in order
87
-
88
- **M1 — the sort.** `src/shade/renderer/gpu_primitive/sort/`:
89
- `graph_radix_sort({graph, keys, values, element_count}) → {keys, values}` — u32 keys + u32
90
- values, ascending, stable, result back in the caller's buffers. Reduce-then-scan LSD, 8-bit
91
- digits × 4 passes; per pass: (a) per-tile 256-bin histogram; (b) spine scan through
92
- `graph_prefix_scan_csdldf` **reused as-is** — adopt its `{count: u32, elements: array<vec4u>}`
93
- 16-byte-aligned layout, write the count word host-side or in the histogram pass, size with
94
- `element_max_count = tiles × 256`, flatten column-major (bin-major) so one scan yields global
95
- digit offsets and per-tile offsets together; (c) rank-and-scatter. The scan is **in-place and
96
- inclusive-only**: the scatter recomputes its own tile's local histogram and ranks in workgroup
97
- memory anyway (it must, for stability), so the global exclusive offset is
98
- `spine_value − own_tile_count` — do not try to preserve pre-scan counts. Include a
99
- `warn_limited` guard on workgroup counts like the scan has. Definition of done: WGSL validity
100
- spec green; chunk-level emulator specs for the pure helpers (digit extraction, rank math);
101
- a `SoftwareGPUDevice` spec asserting the encoded dispatch sequence; a browser
102
- `verify_radix_sort.js` (template in history) registered in the playground; `npm test` green.
103
-
104
- **M2 — morton + emission chunks.** New `chunk_v3_morton_encode` in
105
- `src/shade/renderer/shader/chunk/bvh/morton/` composing the existing
106
- `shader/chunk/binary/chunk_split_by_3.js` as `split_by_3(x) | split_by_3(y)<<1 | split_by_3(z)<<2`
107
- — bit-exact with `src/core/geom/3d/morton/v3_morton_encode_magicbits.js`. The emission logic
108
- (`delta`, `determine_range`, `find_split`) goes into separate `chunk_bvh_*` files under
109
- `gpu_primitive/bvh/` so tier-2 tests can execute each function directly against its CPU
110
- counterpart (`Math.clz32` ⇔ `countLeadingZeros`). DoD: emulator specs proving bit-parity on
111
- randomized inputs **salted with duplicate-key runs**.
112
-
113
- **M3 — builder shaders + recorder.** In `gpu_primitive/bvh/`: `shader_bvh_morton`,
114
- `shader_bvh_emit_hierarchy`, `shader_bvh_refit`, plus `graph_bvh_build_lbvh({graph, leaf_bounds,
115
- leaf_payload, element_count, nodes, root…})` per plan §4.2 (pass table) and §4.3 (layout,
116
- transient sizing). The scene-aware extraction shader (`shader_bvh_extract_instance_leaves`,
117
- reads the rows list + `meshes` table, subgroup pre-reduce → workgroup reduce →
118
- `chunk_aabb_atomic_f32` merge into the scene-bounds cell) lives with the scene code in
119
- `src/shade/renderer/scene/`, not in the primitive (plan AR10). Emission: thread `i` writes leaf
120
- `(N-1)+i` from `leaf_bounds[values[i]]` / `leaf_payload[values[i]]`; threads `i < N-1` also emit
121
- internal `i` and write `parents[]` for both children; write `parents[0] = NULL_NODE`. Refit: one
122
- thread per leaf climbs `parents`, `atomicAdd` arrival counter per internal node, first arrival
123
- exits, second recomputes bounds; bind the node buffer as flat `array<atomic<u32>>` in this pass.
124
- DoD: WGSL validity for all; emulator executes morton + emission kernels end-to-end point-wise
125
- against the CPU oracle (they are pure — keep them barrier/atomic-free); refit gets validity +
126
- tier 3/4 only.
127
-
128
- **M4 — integration.** `GPUInstancesAccelerationStructure`: keep the CPU dynamic tree and all
129
- `instance_*` methods untouched (CPU consumers query `tlas.bvh` — see
130
- `DirectionalLightShadowmap`); add a compact live-rows `Uint32Array` mirror + persistent GPU
131
- buffer re-uploaded only on membership churn; `push_to_gpu()` gains the GPU path — grow the
132
- output buffer via `ensure_buffer_capacity` to `4 + 32·(2N−1)`, build a `FrameGraph`, import
133
- rows/scene-database/output, record extraction + `graph_bvh_build_lbvh`, encode + submit via
134
- `ShadeGPUCommandContext` (the `test_prefix_sum.js` idiom); handle N ∈ {0, 1} host-side. The GPU
135
- path is the default; the legacy CPU path (treelet + flatten + upload, verbatim, treelet call
136
- included) stays behind a module flag `USE_GPU_TLAS_BUILD` for A/B only. `GPUSceneContext` and
137
- all consumers: zero changes. DoD: a `SoftwareGPUDevice` orchestration spec asserting dispatch
138
- sequence, bindings resolving to the right buffers, transient sizes/clears, rows upload only on
139
- churn, and the N=0/1 short-circuits (host-written bytes only — the mock runs no shaders).
140
-
141
- **M5 — locking specs + verify harness.** `bvh_format.spec.js` pinning the §2.1 byte contract
142
- for BOTH the legacy compressor and the GPU layout against the same golden bytes.
143
- `verify_gpu_bvh_build.js` in the playground "review checks": randomized instance sets
144
- (duplicates, degenerate AABBs, N ∈ {0,1,2,3, 2^k±1, ~100k}), readback, assert structural
145
- validity (every leaf exactly once, both children valid, parent AABB ⊇ children, root word),
146
- payload permutation, **depth histogram**, SAH cost vs the CPU oracle fed the same sorted order
147
- (topology must match node-for-node modulo the index mapping). Wire GPU timings for the build via
148
- `encoder.enable_profiling` and a `GPUFrameRecorder` (the `timer` param on `graph_compute_pass` is
149
- silently dropped — known quirk, don't use it).
150
-
151
- **M6 — hand back.** You cannot run the browser playground (meep is a library; the host repo
152
- mounts it). When `npm test` is green and everything above is in place: update
153
- `GPU_BVH_BUILD_PLAN.md`'s status header (PLANNED → phase 1 landed, note any deviations), then
154
- stop and hand over with exact instructions for the human: which playground buttons to run
155
- (sort verify, BVH verify), and that path-tracer/RTX-shadows A/B via the flag is the final gate.
156
- **Never report browser-tier or on-device results you did not observe.**
157
-
158
- ## Traps (each of these has already cost someone a day)
159
-
160
- - Duplicate morton codes: the index tiebreak must be in `delta`, and there must be **no**
161
- midpoint-split special case. Test with long runs of identical keys.
162
- - Scene-bounds seeding: pool-cleared buffers are **zeroed**, and zero is not ±inf. Seed the
163
- 6-word cell with the ±inf u32 bit patterns (`0x7F800000` / `0xFF800000`) via a tiny init pass
164
- or `writeBuffer`. In-shader accumulators can't const-fold `bitcast<f32>(0x7F800000u)` — use
165
- `±3.4028234e38` there (see the meshlet bounds shader's comment).
166
- - Refit counters must be zero every build: declare the transient with
167
- `BufferResourceDescriptor.from(size, usage, 0, size)` so pool-reused buffers get cleared
168
- (fresh ones arrive zeroed already).
169
- - Tint uniformity: conditions guarding `workgroupBarrier` must derive from uniform builtins, not
170
- `var<private>` copies; the deleted binning shader's `subgroup_size`/`sg_size` fix and manual
171
- unrolls are the worked example. Use the `@diagnostic(off, subgroup_uniformity)` wrapper idiom
172
- from the csdldf shader only where the analysis over-approximates, never to silence a real race.
173
- - The csdldf scan reads its element count from `data[0]` and dispatches indirectly; it is
174
- inclusive-only and 16-byte-aligned — do not "fix" it, adapt to it.
175
- - `ensure_buffer_capacity` may return a **new** `GPUBuffer` (old one destroyed) — consumers are
176
- safe because they read `tlas.buffer` per frame at execute time; just make sure the class field
177
- is reassigned before the graph imports it.
178
- - WGSL `if (someU32)` is invalid (needs `!= 0`) — the old adaptive-morton chunks in
179
- `shader/chunk/bvh/morton/` contain exactly this bug; they are dead code, do not import them.
180
- - `SOURCE_STRIDE = 10` (CPU node, words) vs `TARGET_STRIDE = 8` (GPU) — only relevant in the
181
- legacy path and `bvh_format.spec.js`; don't confuse the two layouts.
182
-
183
- ## Deviation protocol
184
-
185
- The plan was verified against the tree on 2026-08-26, but the tree moves. Where plan and code
186
- disagree, **the code wins** — verify, implement against reality, and record the deviation in the
187
- plan doc (one line, in place). If you hit a genuine design fork the plan doesn't cover (not a
188
- detail — a fork), stop and ask rather than inventing. Do not delete anything beyond what a
189
- milestone explicitly requires; the cleanup backlog (§8) is not phase-1 scope except where a
190
- milestone touches it. Pre-existing unrelated test failures: note them, don't fix them, don't
191
- let them block you.
192
-
193
- ## Definition of done (phase 1)
194
-
195
- - [ ] Sort: all four tiers green, verify harness registered.
196
- - [ ] Builder: emulator parity with `ebvh_build_hierarchy_radix` (duplicates included), WGSL
197
- validity everywhere, orchestration spec green.
198
- - [ ] Integration: GPU path default, legacy verbatim behind flag, consumers untouched,
199
- `npm test` fully green.
200
- - [ ] `bvh_format.spec.js` + `verify_gpu_bvh_build.js` in place.
201
- - [ ] Plan doc status updated; hand-over message with the human's browser checklist.
1
+ # Hand-over: implement Phase 1 of the GPU BVH builder
2
+
3
+ You are implementing **Phase 1 only** of `GPU_BVH_BUILD_PLAN.md` (same directory — read it in
4
+ full before writing any code; it is the authoritative design, this file is the execution brief).
5
+ Phase 1 = two deliverables, in this order:
6
+
7
+ 1. **A key-value radix sort** built around CSDLDF, re-founding `src/shade/renderer/gpu_primitive/sort/`.
8
+ 2. **A GPU TLAS build** (LBVH: extract → morton → sort → Karras emission → refit) replacing the
9
+ CPU-side work in `GPUInstancesAccelerationStructure.push_to_gpu()`.
10
+
11
+ Do **not** start phases 2–4 (treelets, BLAS, BVH8), do not redesign node formats, do not add
12
+ frameworks. Everything you need exists in the tree or in git history; this project's explicit
13
+ standard is *port and reuse, don't invent*.
14
+
15
+ ## Read these before writing code
16
+
17
+ In order, each for a stated reason:
18
+
19
+ 1. `src/shade/renderer/gpu_primitive/bvh/GPU_BVH_BUILD_PLAN.md` — the design. §2.1 is the byte
20
+ contract, §4 is what you are building, §4.2.1 is the sort, §4.5 is the test plan you must
21
+ satisfy, §6/§7 explain decisions — do not relitigate them.
22
+ 2. `src/core/bvh2/bvh3/ebvh_build_hierarchy_radix.js` (+ its `.spec.js`) — the CPU oracle your
23
+ emission kernel transliterates: `delta` with the `32 + clz32(i^j)` duplicate-key tiebreak,
24
+ `determineRange`, `find_split`. Read the comment block at `find_split` about why duplicate
25
+ codes must NOT be midpoint-split — that bug produces a shared-node non-tree.
26
+ 3. `src/shade/renderer/gpu_primitive/prefix_sum/v1/shader_prefix_scan_csdldf.js` and
27
+ `graph_prefix_scan_csdldf.js` — the blessed scan you reuse as the sort's spine, and the house
28
+ subgroup idioms (`subgroup_size` builtin, `MIN_SUBGROUP_SIZE = 4`,
29
+ `@diagnostic(off, subgroup_uniformity)` helpers, split flag words, bounded spin + fallback).
30
+ 4. Git history of the deleted OneSweep port — orchestration + scatter/ranking reference:
31
+ `git show 370542c3f:src/shade/renderer/gpu_primitive/sort/one_sweep/graph_radix_sort.js`
32
+ (graph orchestration template), `...shader_digit_binning_pass_pairs.js` (workgroup ranking
33
+ machinery + two pinned WebGPU lessons), `...one_sweep.spec.js` and
34
+ `...verify_radix_sort_one_sweep.js` (spec/verify templates). List the directory with
35
+ `git show 370542c3f:src/shade/renderer/gpu_primitive/sort/one_sweep/ 2>$null` or
36
+ `git ls-tree 370542c3f -- src/shade/renderer/gpu_primitive/sort/one_sweep/`.
37
+ 5. `src/shade/renderer/animation/skinning/bounds_refresh/shader_meshlet_bounds_reduce.js` +
38
+ `src/shade/renderer/shader/chunk/atomic/chunk_atomic_min_f32_storage.js` /
39
+ `chunk_atomic_max_f32_storage.js` — the reduce-then-atomic-merge pattern for the scene-bounds pass,
40
+ and the "same buffer bound as `array<atomic<u32>>` in one pass, typed in another" idiom the
41
+ refit pass needs. Note its comment about `bitcast<f32>(0x7F800000u)` not const-folding.
42
+ 6. `src/shade/renderer/scene/GPUInstancesAccelerationStructure.js`,
43
+ `src/shade/renderer/scene/GPUSceneContext.js` (how `instance_add/remove/update` and
44
+ `update()` drive it), `src/shade/renderer/geometry/bvh/bvh_to_gpu_buffer.js` +
45
+ `bvh2_compress.js` (the legacy path you keep behind a flag),
46
+ `src/shade/renderer/scene/MESH_INSTANCE_METADATA_STRUCT.js` (where per-row world AABBs live).
47
+ 7. `src/shade/renderer/shader/chunk/geometry/ray/chunk_ray_query_nearest.js` — the traversal
48
+ consumer; internalize its leaf/root conventions before emitting a single node.
49
+ 8. Testing machinery: `src/shade/wgsl/emulator/ComputeShaderEmulator.js` + its `.spec.js` and a
50
+ couple of existing chunk specs under `src/shade/renderer/shader/chunk/math/` (the established
51
+ pattern for emulator-testing individual WGSL functions);
52
+ `src/shade/device/mock/SoftwareGPUDevice.js` + `SoftwareGPUComputePassEncoder.js` (a
53
+ **recording** device — executes no shaders; assert on what was encoded and on host-written
54
+ bytes only); `src/shade/renderer/gpu_primitive/prefix_sum/v1/test_prefix_sum.js` and
55
+ `src/shade/renderer/buffer/graph_inspect_gpu_buffer.js` (browser verify pattern);
56
+ `src/shade/playground/bvh_repro/` — the standalone page where the `verify_*` functions get
57
+ registered and run against a real device (`npm run dev`, then
58
+ <http://localhost:5173/src/shade/playground/bvh_repro/index.html>).
59
+
60
+ ## Non-negotiable contracts
61
+
62
+ **Output bytes** (every RT consumer depends on this; there is no versioning):
63
+ - Node = 32 bytes: `[min.x, min.y, min.z, max.x, max.y, max.z] : f32` then `child_1 : u32`,
64
+ `child_2 : u32`.
65
+ - Leaf ⇔ `child_1 == 0xFFFFFFFF` (`BVH_NULL_NODE`); then `child_2` = scene-database `meshes`
66
+ row. Internal ⇒ both children are valid node indices with meaningful bounds.
67
+ - TLAS buffer = `u32 root` at byte 0, nodes from byte 4. Your layout: root is node 0
68
+ (Karras internal 0), internals `[0, N-2]`, leaves `[N-1, 2N-2]`. Still write the root word.
69
+ - `N == 0` ⇒ write `root = BVH_NULL_NODE` host-side. `N == 1` ⇒ single leaf as node 0, root 0.
70
+
71
+ **House rules:**
72
+ - **Subgroups are a baseline engine requirement.** Use them wherever they pay. But do not bake
73
+ wave-*width* assumptions into algorithm structure — subgroup size is a runtime value 4–128;
74
+ workgroup memory is the correctness layer across subgroup boundaries.
75
+ - **CSDLDF discipline:** no unbounded cross-workgroup waiting, ever. Bounded spin + fallback
76
+ (the csdldf shader) or no spin at all (arrival counters where the loser exits — the refit).
77
+ All cross-workgroup-communicated state goes through `array<atomic<u32>>` accesses exclusively.
78
+ - **A vitest spec may never stand up a real GPU device.** Shade specs run under vitest
79
+ (`npm test`); the four validation tiers of plan §4.5 are all mandatory.
80
+ - Match existing code style exactly: `assert.*` guards on public entry points, `#private`
81
+ fields, `chunk_*`/`shader_*`/`graph_*` naming, `CodeChunk.from(wgsl, [deps])` composition,
82
+ `ShaderResourceSetDescriptor` for bindings, JSDoc in the house voice. Read neighbours, write
83
+ like them.
84
+ - Commit directly to `master`, conventional style with scope (`feat(shade): …`), incremental —
85
+ one commit per milestone below is about right. Do not amend, do not branch.
86
+
87
+ ## Milestones, in order
88
+
89
+ **M1 — the sort.** `src/shade/renderer/gpu_primitive/sort/`:
90
+ `graph_radix_sort({graph, keys, values, element_count}) → {keys, values}` — u32 keys + u32
91
+ values, ascending, stable, result back in the caller's buffers. Reduce-then-scan LSD, 8-bit
92
+ digits × 4 passes; per pass: (a) per-tile 256-bin histogram; (b) spine scan through
93
+ `graph_prefix_scan_csdldf` **reused as-is** — adopt its `{count: u32, elements: array<vec4u>}`
94
+ 16-byte-aligned layout, write the count word host-side or in the histogram pass, size with
95
+ `element_max_count = tiles × 256`, flatten column-major (bin-major) so one scan yields global
96
+ digit offsets and per-tile offsets together; (c) rank-and-scatter. The scan is **in-place and
97
+ inclusive-only**: the scatter recomputes its own tile's local histogram and ranks in workgroup
98
+ memory anyway (it must, for stability), so the global exclusive offset is
99
+ `spine_value − own_tile_count` — do not try to preserve pre-scan counts. Include a
100
+ `warn_limited` guard on workgroup counts like the scan has. Definition of done: WGSL validity
101
+ spec green; chunk-level emulator specs for the pure helpers (digit extraction, rank math);
102
+ a `SoftwareGPUDevice` spec asserting the encoded dispatch sequence; a browser
103
+ `verify_radix_sort.js` (template in history) registered in the playground; `npm test` green.
104
+
105
+ **M2 — morton + emission chunks.** New `chunk_v3_morton_encode` in
106
+ `src/shade/renderer/shader/chunk/bvh/morton/` composing the existing
107
+ `shader/chunk/binary/chunk_split_by_3.js` as `split_by_3(x) | split_by_3(y)<<1 | split_by_3(z)<<2`
108
+ — bit-exact with `src/core/geom/3d/morton/v3_morton_encode_magicbits.js`. The emission logic
109
+ (`delta`, `determine_range`, `find_split`) goes into separate `chunk_bvh_*` files under
110
+ `gpu_primitive/bvh/` so tier-2 tests can execute each function directly against its CPU
111
+ counterpart (`Math.clz32` ⇔ `countLeadingZeros`). DoD: emulator specs proving bit-parity on
112
+ randomized inputs **salted with duplicate-key runs**.
113
+
114
+ **M3 — builder shaders + recorder.** In `gpu_primitive/bvh/`: `shader_bvh_morton`,
115
+ `shader_bvh_emit_hierarchy`, `shader_bvh_refit`, plus `graph_bvh_build_lbvh({graph, leaf_bounds,
116
+ leaf_payload, element_count, nodes, root…})` per plan §4.2 (pass table) and §4.3 (layout,
117
+ transient sizing). The scene-aware extraction shader (`shader_bvh_extract_instance_leaves`,
118
+ reads the rows list + `meshes` table, subgroup pre-reduce → workgroup reduce →
119
+ `chunk_atomic_min_f32_storage` / `chunk_atomic_max_f32_storage` merge into the scene-bounds cell) lives with the scene code in
120
+ `src/shade/renderer/scene/`, not in the primitive (plan AR10). Emission: thread `i` writes leaf
121
+ `(N-1)+i` from `leaf_bounds[values[i]]` / `leaf_payload[values[i]]`; threads `i < N-1` also emit
122
+ internal `i` and write `parents[]` for both children; write `parents[0] = NULL_NODE`. Refit: one
123
+ thread per leaf climbs `parents`, `atomicAdd` arrival counter per internal node, first arrival
124
+ exits, second recomputes bounds; bind the node buffer as flat `array<atomic<u32>>` in this pass.
125
+ DoD: WGSL validity for all; emulator executes morton + emission kernels end-to-end point-wise
126
+ against the CPU oracle (they are pure — keep them barrier/atomic-free); refit gets validity +
127
+ tier 3/4 only.
128
+
129
+ **M4 — integration.** `GPUInstancesAccelerationStructure`: keep the CPU dynamic tree and all
130
+ `instance_*` methods untouched (CPU consumers query `tlas.bvh` — see
131
+ `DirectionalLightShadowmap`); add a compact live-rows `Uint32Array` mirror + persistent GPU
132
+ buffer re-uploaded only on membership churn; `push_to_gpu()` gains the GPU path — grow the
133
+ output buffer via `ensure_buffer_capacity` to `4 + 32·(2N−1)`, build a `FrameGraph`, import
134
+ rows/scene-database/output, record extraction + `graph_bvh_build_lbvh`, encode + submit via
135
+ `ShadeGPUCommandContext` (the `test_prefix_sum.js` idiom); handle N ∈ {0, 1} host-side. The GPU
136
+ path is the default; the legacy CPU path (treelet + flatten + upload, verbatim, treelet call
137
+ included) stays behind a module flag `USE_GPU_TLAS_BUILD` for A/B only. `GPUSceneContext` and
138
+ all consumers: zero changes. DoD: a `SoftwareGPUDevice` orchestration spec asserting dispatch
139
+ sequence, bindings resolving to the right buffers, transient sizes/clears, rows upload only on
140
+ churn, and the N=0/1 short-circuits (host-written bytes only — the mock runs no shaders).
141
+
142
+ **M5 — locking specs + verify harness.** `bvh_format.spec.js` pinning the §2.1 byte contract
143
+ for BOTH the legacy compressor and the GPU layout against the same golden bytes.
144
+ `verify_gpu_bvh_build.js` in the playground "review checks": randomized instance sets
145
+ (duplicates, degenerate AABBs, N ∈ {0,1,2,3, 2^k±1, ~100k}), readback, assert structural
146
+ validity (every leaf exactly once, both children valid, parent AABB ⊇ children, root word),
147
+ payload permutation, **depth histogram**, SAH cost vs the CPU oracle fed the same sorted order
148
+ (topology must match node-for-node modulo the index mapping). Wire GPU timings for the build via
149
+ `encoder.enable_profiling` and a `GPUFrameRecorder` (the `timer` param on `graph_compute_pass` is
150
+ silently dropped — known quirk, don't use it).
151
+
152
+ **M6 — hand back.** You cannot run the browser playground (meep is a library; the host repo
153
+ mounts it). When `npm test` is green and everything above is in place: update
154
+ `GPU_BVH_BUILD_PLAN.md`'s status header (PLANNED → phase 1 landed, note any deviations), then
155
+ stop and hand over with exact instructions for the human: which playground buttons to run
156
+ (sort verify, BVH verify), and that path-tracer/RTX-shadows A/B via the flag is the final gate.
157
+ **Never report browser-tier or on-device results you did not observe.**
158
+
159
+ ## Traps (each of these has already cost someone a day)
160
+
161
+ - Duplicate morton codes: the index tiebreak must be in `delta`, and there must be **no**
162
+ midpoint-split special case. Test with long runs of identical keys.
163
+ - Scene-bounds seeding: pool-cleared buffers are **zeroed**, and zero is not ±inf. Seed the
164
+ 6-word cell with the ±inf u32 bit patterns (`0x7F800000` / `0xFF800000`) via a tiny init pass
165
+ or `writeBuffer`. In-shader accumulators can't const-fold `bitcast<f32>(0x7F800000u)` — use
166
+ `±3.4028234e38` there (see the meshlet bounds shader's comment).
167
+ - Refit counters must be zero every build: declare the transient with
168
+ `BufferResourceDescriptor.from(size, usage, 0, size)` so pool-reused buffers get cleared
169
+ (fresh ones arrive zeroed already).
170
+ - Tint uniformity: conditions guarding `workgroupBarrier` must derive from uniform builtins, not
171
+ `var<private>` copies; the deleted binning shader's `subgroup_size`/`sg_size` fix and manual
172
+ unrolls are the worked example. Use the `@diagnostic(off, subgroup_uniformity)` wrapper idiom
173
+ from the csdldf shader only where the analysis over-approximates, never to silence a real race.
174
+ - The csdldf scan reads its element count from `data[0]` and dispatches indirectly; it is
175
+ inclusive-only and 16-byte-aligned — do not "fix" it, adapt to it.
176
+ - `ensure_buffer_capacity` may return a **new** `GPUBuffer` (old one destroyed) — consumers are
177
+ safe because they read `tlas.buffer` per frame at execute time; just make sure the class field
178
+ is reassigned before the graph imports it.
179
+ - WGSL `if (someU32)` is invalid (needs `!= 0`) — the old adaptive-morton chunks in
180
+ `shader/chunk/bvh/morton/` contain exactly this bug; they are dead code, do not import them.
181
+ - `SOURCE_STRIDE = 10` (CPU node, words) vs `TARGET_STRIDE = 8` (GPU) — only relevant in the
182
+ legacy path and `bvh_format.spec.js`; don't confuse the two layouts.
183
+
184
+ ## Deviation protocol
185
+
186
+ The plan was verified against the tree on 2026-08-26, but the tree moves. Where plan and code
187
+ disagree, **the code wins** — verify, implement against reality, and record the deviation in the
188
+ plan doc (one line, in place). If you hit a genuine design fork the plan doesn't cover (not a
189
+ detail — a fork), stop and ask rather than inventing. Do not delete anything beyond what a
190
+ milestone explicitly requires; the cleanup backlog (§8) is not phase-1 scope except where a
191
+ milestone touches it. Pre-existing unrelated test failures: note them, don't fix them, don't
192
+ let them block you.
193
+
194
+ ## Definition of done (phase 1)
195
+
196
+ - [ ] Sort: all four tiers green, verify harness registered.
197
+ - [ ] Builder: emulator parity with `ebvh_build_hierarchy_radix` (duplicates included), WGSL
198
+ validity everywhere, orchestration spec green.
199
+ - [ ] Integration: GPU path default, legacy verbatim behind flag, consumers untouched,
200
+ `npm test` fully green.
201
+ - [ ] `bvh_format.spec.js` + `verify_gpu_bvh_build.js` in place.
202
+ - [ ] Plan doc status updated; hand-over message with the human's browser checklist.
@@ -0,0 +1,24 @@
1
+ import { CodeChunk } from "../../shader/compiler/CodeChunk.js";
2
+ import { SPHERE_PROBE_MIP_MAX_ROUGHNESS } from "./DEFINES.js";
3
+
4
+ /**
5
+ * Input roughness is linear (blender calls it "UI roughness")
6
+ * @see https://projects.blender.org/blender/blender/src/commit/866ef5b468589587395b1ee7480ea75b4c0fbc26/source/blender/draw/engines/eevee_next/shaders/eevee_lightprobe_sphere_mapping_lib.glsl#L102
7
+ * @type {CodeChunk}
8
+ */
9
+ export const chunk_roughness_to_mip_ratio = CodeChunk.from(
10
+ //language=WGSL
11
+ `
12
+ fn roughness_to_mip_ratio(roughness: f32) -> f32 {
13
+ /* From "Moving Frostbite to Physically Based Rendering 3.0" eq 53. */
14
+ let ratio = saturate( roughness / ${SPHERE_PROBE_MIP_MAX_ROUGHNESS} );
15
+
16
+ let ratio_sqrt = sqrt(ratio);
17
+
18
+ /* Mix with linear to avoid mip 1 being too sharp. */
19
+ let mip_ratio = mix(ratio, ratio_sqrt, 0.4);
20
+
21
+ return mip_ratio;
22
+ }
23
+ `, []
24
+ );
@@ -1,29 +1,6 @@
1
- import { chunk_fast_sqrt } from "../../shader/chunk/math/fast/chunk_fast_sqrt.js";
2
1
  import { CodeChunk } from "../../shader/compiler/CodeChunk.js";
3
- import { SPHERE_PROBE_MIP_MAX_ROUGHNESS, SPHERE_PROBE_MIPMAP_LEVELS } from "./DEFINES.js";
4
-
5
- /**
6
- * Input roughness is linear (blender calls it "UI roughness")
7
- * @see https://projects.blender.org/blender/blender/src/commit/866ef5b468589587395b1ee7480ea75b4c0fbc26/source/blender/draw/engines/eevee_next/shaders/eevee_lightprobe_sphere_mapping_lib.glsl#L102
8
- * @type {CodeChunk}
9
- */
10
- export const chunk_roughness_to_mip_ratio = CodeChunk.from(
11
- //language=WGSL
12
- `
13
- fn roughness_to_mip_ratio(roughness: f32) -> f32 {
14
- /* From "Moving Frostbite to Physically Based Rendering 3.0" eq 53. */
15
- let ratio = saturate( roughness / ${SPHERE_PROBE_MIP_MAX_ROUGHNESS} );
16
-
17
- let ratio_sqrt = sqrt(ratio);
18
-
19
- /* Mix with linear to avoid mip 1 being too sharp. */
20
- let mip_ratio = mix(ratio, ratio_sqrt, 0.4);
21
-
22
- return mip_ratio;
23
- }
24
- `, [
25
- ]
26
- );
2
+ import { chunk_roughness_to_mip_ratio } from "./chunk_roughness_to_mip_ratio.js";
3
+ import { SPHERE_PROBE_MIPMAP_LEVELS } from "./DEFINES.js";
27
4
 
28
5
  /**
29
6
  * Input roughness is linear (blender calls it "UI roughness")
@@ -10,8 +10,8 @@
10
10
  export const ENVIRONMENT_SH_TYPE: WebGPUArray;
11
11
  /**
12
12
  * Directions the projection samples, spread evenly over the sphere (`sphere_fibonacci_point`).
13
- * The field is the environment at the roughness diffuse reads it at, so this is far more than its
14
- * two bands can hold, and it costs nothing that recurs: the pass runs when the environment changes.
13
+ * The field is already prefiltered at the roughness diffuse reads it at; these samples project
14
+ * that smooth field into two bands. The pass runs only when the environment changes.
15
15
  *
16
16
  * @type {number}
17
17
  */
@@ -1 +1 @@
1
- {"version":3,"file":"shader_project_environment_sh.d.ts","sourceRoot":"","sources":["../../../../../../src/shade/renderer/light/environment/shader_project_environment_sh.js"],"names":[],"mappings":"AAUA;;;;;;;;GAQG;AACH,kCAFU,WAAW,CAEyC;AAE9D;;;;;;GAMG;AACH,0CAFU,MAAM,CAEgC;AAyDhD;;;;;;;;;;;;;;GAcG;AACH,4CAFU,aAAa,CAMpB;4BAjGyB,kCAAkC;8BAFhC,+BAA+B"}
1
+ {"version":3,"file":"shader_project_environment_sh.d.ts","sourceRoot":"","sources":["../../../../../../src/shade/renderer/light/environment/shader_project_environment_sh.js"],"names":[],"mappings":"AAWA;;;;;;;;GAQG;AACH,kCAFU,WAAW,CAEyC;AAE9D;;;;;;GAMG;AACH,0CAFU,MAAM,CAE+B;AAuF/C;;;;;;;;;;;;;;GAcG;AACH,4CAFU,aAAa,CAMpB;4BA/HyB,kCAAkC;8BAFhC,+BAA+B"}