@vibegameengine/magma-path-tracer 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vibe Game Engine
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @vibegameengine/magma-path-tracer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Real-time WebGPU PBR Path Tracer with **Canonical Falcor SVGF**, **1080p TAAU** (5-tap Catmull-Rom + Blackman-Harris + relative dilated velocity + YCoCg Clip-to-AABB), and **AMD FidelityFX RCAS**, powered by [`magma-ray-query-shim`](https://github.com/vibegameengine/magma-ray-query-shim).
4
+
5
+ Works with zero code changes on:
6
+ - **Magma / MegaBrowser** (native DXR 1.1 hardware ray tracing via `ray-query`)
7
+ - **Chrome / Edge / Safari** (automatic 2-level SAH BVH software compute fallback)
8
+
9
+ ## Pipeline
10
+
11
+ 1. **Pass 1 — PBR Path Tracer + SVGF Reproject (`ptShader.js`)**: Heitz 2018 GGX VNDF, Jimenez IGN + Roberts R2 sampling, fast opaque shadow rays with alpha-mask pass-through, Direct/Indirect split, Short-Range Contact AO, canonical Falcor temporal reprojection.
12
+ 2. **Pass 2 — SVGF FilterMoments (`svgfShaders.js`)**: 7×7 spatial variance estimation when history length `< 4`.
13
+ 3. **Pass 3 — 4-Pass Variance-Guided SVGF À-Trous (`svgfShaders.js`)**: step sizes `1, 2, 4, 8` with 1st-pass History Tap and roughness-aware `phiL`.
14
+ 4. **Pass 4 — Compose (`postShaders.js`)**: Direct + Contact-AO-modulated SVGF Indirect, AgX (Blender 4.0) & ACES Filmic tone mapping, 7 Debug AOV views.
15
+ 5. **Pass 5 — TAAU (`postShaders.js`)**: temporal super-resolution (`960×540 → 1920×1080`) with 5-tap Catmull-Rom history sampling, Blackman-Harris sub-pixel coverage weighting, closest-depth relative velocity dilation, and YCoCg Clip-to-AABB.
16
+ 6. **Pass 6 — Present + AMD FidelityFX RCAS (`postShaders.js`)**: 1:1 native 1080p integer load with contrast-adaptive anti-ringing sharpening.
17
+
18
+ ## Quick Start
19
+
20
+ ```js
21
+ import { installMagmaRayQueryShim } from "@vibegameengine/magma-ray-query-shim";
22
+ import { createMagmaPathTracer, loadGltfScene } from "@vibegameengine/magma-path-tracer";
23
+
24
+ const adapter = await navigator.gpu.requestAdapter();
25
+ const device = await adapter.requestDevice({
26
+ requiredLimits: { maxStorageTexturesPerShaderStage: 8 },
27
+ });
28
+ installMagmaRayQueryShim(device, { tlasBufferBytes: 32 * 1024 * 1024 });
29
+
30
+ const scene = await loadGltfScene(device, {
31
+ baseUrl: "https://cdn.jsdelivr.net/gh/KhronosGroup/glTF-Sample-Assets@main/Models/Sponza/glTF/",
32
+ gltfFile: "Sponza.gltf",
33
+ binFile: "Sponza.bin",
34
+ scale: 0.008,
35
+ });
36
+
37
+ const tracer = createMagmaPathTracer(device, canvas, scene, {
38
+ renderWidth: 960,
39
+ renderHeight: 540,
40
+ outputWidth: 1920,
41
+ outputHeight: 1080,
42
+ });
43
+
44
+ tracer.renderFrame({
45
+ camera: { pos: [-9.2, 1.85, -0.35], fwd: [1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
46
+ sunDir: [0.28, 0.95, 0.09],
47
+ });
48
+ ```
49
+
50
+ ## Live Showcase
51
+
52
+ See it running live on 262,267-triangle Crytek Sponza: https://vibegameengine.github.io/magma-ray-query-shim/demos/sponza.html
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@vibegameengine/magma-path-tracer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "description": "Real-time WebGPU PBR Path Tracer with Canonical Falcor SVGF, 1080p TAAU (Catmull-Rom + Blackman-Harris + Clip-to-AABB), and AMD FidelityFX RCAS, powered by magma-ray-query-shim.",
9
+ "main": "src/index.js",
10
+ "types": "types/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./types/index.d.ts",
14
+ "import": "./src/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "src/",
19
+ "types/",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "test": "node --test test/*.test.mjs"
25
+ },
26
+ "keywords": [
27
+ "webgpu",
28
+ "ray-tracing",
29
+ "path-tracing",
30
+ "svgf",
31
+ "taau",
32
+ "rcas",
33
+ "pbr",
34
+ "gltf",
35
+ "magma"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/vibegameengine/magma-path-tracer.git"
40
+ },
41
+ "homepage": "https://github.com/vibegameengine/magma-path-tracer#readme",
42
+ "license": "MIT",
43
+ "dependencies": {
44
+ "@vibegameengine/magma-ray-query-shim": "^0.1.0"
45
+ }
46
+ }
@@ -0,0 +1,200 @@
1
+ async function fetchWithRetry(url, attempts = 4) {
2
+ let lastErr;
3
+ for (let i = 0; i < attempts; i++) {
4
+ try {
5
+ const resp = await fetch(url);
6
+ if (resp.ok) return resp;
7
+ lastErr = new Error(`HTTP ${resp.status} for ${url}`);
8
+ } catch (err) {
9
+ lastErr = err;
10
+ }
11
+ if (i + 1 < attempts) await new Promise((r) => setTimeout(r, 300 * (i + 1)));
12
+ }
13
+ throw lastErr;
14
+ }
15
+
16
+ function readAccessor(gltf, bin, accIdx) {
17
+ const acc = gltf.accessors[accIdx];
18
+ const bv = gltf.bufferViews[acc.bufferView];
19
+ const byteOffset = (bv.byteOffset || 0) + (acc.byteOffset || 0);
20
+ const numComp = acc.type === "SCALAR" ? 1 : acc.type === "VEC2" ? 2 : acc.type === "VEC3" ? 3 : 4;
21
+ const stride = bv.byteStride || 0;
22
+ const ct = acc.componentType;
23
+ const Ctor = ct === 5126 ? Float32Array : ct === 5125 ? Uint32Array : Uint16Array;
24
+ const elemBytes = Ctor.BYTES_PER_ELEMENT;
25
+ if (!stride || stride === numComp * elemBytes) return new Ctor(bin, byteOffset, acc.count * numComp);
26
+
27
+ const out = new Ctor(acc.count * numComp);
28
+ const dv = new DataView(bin, byteOffset);
29
+ for (let i = 0; i < acc.count; i++) {
30
+ const base = i * stride;
31
+ for (let c = 0; c < numComp; c++) {
32
+ const off = base + c * elemBytes;
33
+ out[i * numComp + c] =
34
+ ct === 5126 ? dv.getFloat32(off, true) : ct === 5125 ? dv.getUint32(off, true) : dv.getUint16(off, true);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+
40
+ async function uploadTexLayer(device, opts) {
41
+ const { baseUrl, texArray, layer, size, uri, fallbackRgba } = opts;
42
+ if (uri) {
43
+ try {
44
+ const resp = await fetchWithRetry(baseUrl + uri);
45
+ const bmp = await createImageBitmap(await resp.blob(), { resizeWidth: size, resizeHeight: size, resizeQuality: "medium" });
46
+ device.queue.copyExternalImageToTexture({ source: bmp }, { texture: texArray, origin: [0, 0, layer] }, [size, size]);
47
+ bmp.close();
48
+ return true;
49
+ } catch (err) {
50
+ console.warn("Texture fallback:", uri, err);
51
+ }
52
+ }
53
+ const solid = new Uint8Array(size * size * 4);
54
+ for (let i = 0; i < size * size * 4; i += 4) {
55
+ solid[i] = fallbackRgba[0]; solid[i + 1] = fallbackRgba[1];
56
+ solid[i + 2] = fallbackRgba[2]; solid[i + 3] = fallbackRgba[3];
57
+ }
58
+ device.queue.writeTexture({ texture: texArray, origin: [0, 0, layer] }, solid, { bytesPerRow: size * 4, rowsPerImage: size }, [size, size, 1]);
59
+ return false;
60
+ }
61
+
62
+ function createInitialMaterialBuffer(device, gltf) {
63
+ const matCount = gltf.materials.length;
64
+ const initMatData = new Float32Array(matCount * 8);
65
+ for (let mi = 0; mi < matCount; mi++) {
66
+ const mat = gltf.materials[mi];
67
+ const pbr = mat.pbrMetallicRoughness || {};
68
+ const bf = pbr.baseColorFactor || [1, 1, 1, 1];
69
+ initMatData[mi * 8 + 0] = bf[0];
70
+ initMatData[mi * 8 + 1] = bf[1];
71
+ initMatData[mi * 8 + 2] = bf[2];
72
+ initMatData[mi * 8 + 3] = mat.alphaMode === "MASK" ? (mat.alphaCutoff !== undefined ? mat.alphaCutoff : 0.5) : 0.0;
73
+ initMatData[mi * 8 + 4] = pbr.metallicFactor !== undefined ? pbr.metallicFactor : 0.0;
74
+ initMatData[mi * 8 + 5] = pbr.roughnessFactor !== undefined ? pbr.roughnessFactor : 0.85;
75
+ }
76
+ const matBuf = device.createBuffer({ size: initMatData.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
77
+ device.queue.writeBuffer(matBuf, 0, initMatData);
78
+ return matBuf;
79
+ }
80
+
81
+ function loadPbrTextureArrays(device, gltf, opts) {
82
+ const { baseUrl, albedoSize = 512, pbrSize = 256, onProgress } = opts;
83
+ const matCount = gltf.materials.length;
84
+ const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT;
85
+ const albedoArr = device.createTexture({ size: [albedoSize, albedoSize, matCount], format: "rgba8unorm-srgb", usage });
86
+ const normalArr = device.createTexture({ size: [pbrSize, pbrSize, matCount], format: "rgba8unorm", usage });
87
+ const mrArr = device.createTexture({ size: [pbrSize, pbrSize, matCount], format: "rgba8unorm", usage });
88
+ const matBuf = createInitialMaterialBuffer(device, gltf);
89
+
90
+ let doneCount = 0;
91
+ const streamOne = async (mi) => {
92
+ const mat = gltf.materials[mi];
93
+ const pbr = mat.pbrMetallicRoughness || {};
94
+ const bf = pbr.baseColorFactor || [1, 1, 1, 1];
95
+ const metalF = pbr.metallicFactor !== undefined ? pbr.metallicFactor : 0.0;
96
+ const roughF = pbr.roughnessFactor !== undefined ? pbr.roughnessFactor : 0.85;
97
+ const albedoUri = pbr.baseColorTexture !== undefined ? gltf.images[gltf.textures[pbr.baseColorTexture.index].source].uri : null;
98
+ const normalUri = mat.normalTexture !== undefined ? gltf.images[gltf.textures[mat.normalTexture.index].source].uri : null;
99
+ const mrUri = pbr.metallicRoughnessTexture !== undefined ? gltf.images[gltf.textures[pbr.metallicRoughnessTexture.index].source].uri : null;
100
+
101
+ const [, hasNorm, hasMr] = await Promise.all([
102
+ uploadTexLayer(device, { baseUrl, texArray: albedoArr, layer: mi, size: albedoSize, uri: albedoUri, fallbackRgba: [Math.round(bf[0] * 255), Math.round(bf[1] * 255), Math.round(bf[2] * 255), 255] }),
103
+ uploadTexLayer(device, { baseUrl, texArray: normalArr, layer: mi, size: pbrSize, uri: normalUri, fallbackRgba: [128, 128, 255, 255] }),
104
+ uploadTexLayer(device, { baseUrl, texArray: mrArr, layer: mi, size: pbrSize, uri: mrUri, fallbackRgba: [255, Math.round(roughF * 255), Math.round(metalF * 255), 255] }),
105
+ ]);
106
+ device.queue.writeBuffer(matBuf, (mi * 8 + 4) * 4, new Float32Array([hasMr ? 1.0 : metalF, hasMr ? 1.0 : roughF, hasNorm ? 1.0 : 0.0, 0.0]));
107
+ doneCount++;
108
+ if (onProgress) onProgress(`Streaming PBR textures (${doneCount}/${matCount})…`, doneCount === matCount);
109
+ };
110
+
111
+ const queue = Array.from({ length: matCount }, (_, i) => i);
112
+ const workers = Array.from({ length: 6 }, async () => { while (queue.length) await streamOne(queue.shift()); });
113
+ return { albedoArr, normalArr, mrArr, matBuf, streamDone: Promise.all(workers) };
114
+ }
115
+
116
+ function unpackGeometry(gltf, bin, scale) {
117
+ let totalVerts = 0;
118
+ let totalIndices = 0;
119
+ for (const mesh of gltf.meshes) {
120
+ for (const prim of mesh.primitives) {
121
+ totalVerts += gltf.accessors[prim.attributes.POSITION].count;
122
+ totalIndices += gltf.accessors[prim.indices].count;
123
+ }
124
+ }
125
+ const totalTris = totalIndices / 3;
126
+ const allPos = new Float32Array(totalVerts * 3);
127
+ const allVAttr = new Float32Array(totalVerts * 12);
128
+ const allIndices = new Uint32Array(totalIndices);
129
+ const triMatIds = new Uint32Array(totalTris);
130
+
131
+ let vOff = 0, iOff = 0, tOff = 0;
132
+ for (const mesh of gltf.meshes) {
133
+ for (const prim of mesh.primitives) {
134
+ const mi = prim.material !== undefined ? prim.material : 0;
135
+ const pos = readAccessor(gltf, bin, prim.attributes.POSITION);
136
+ const nrm = prim.attributes.NORMAL !== undefined ? readAccessor(gltf, bin, prim.attributes.NORMAL) : null;
137
+ const tan = prim.attributes.TANGENT !== undefined ? readAccessor(gltf, bin, prim.attributes.TANGENT) : null;
138
+ const uv = prim.attributes.TEXCOORD_0 !== undefined ? readAccessor(gltf, bin, prim.attributes.TEXCOORD_0) : null;
139
+ const ind = readAccessor(gltf, bin, prim.indices);
140
+ const vCount = pos.length / 3;
141
+ for (let i = 0; i < vCount; i++) {
142
+ const vp = (vOff + i) * 3;
143
+ allPos[vp + 0] = pos[i * 3 + 0] * scale;
144
+ allPos[vp + 1] = pos[i * 3 + 1] * scale;
145
+ allPos[vp + 2] = pos[i * 3 + 2] * scale;
146
+ const va = (vOff + i) * 12;
147
+ allVAttr[va + 0] = nrm ? nrm[i * 3 + 0] : 0;
148
+ allVAttr[va + 1] = nrm ? nrm[i * 3 + 1] : 1;
149
+ allVAttr[va + 2] = nrm ? nrm[i * 3 + 2] : 0;
150
+ allVAttr[va + 3] = uv ? uv[i * 2 + 0] : 0;
151
+ allVAttr[va + 4] = tan ? tan[i * 4 + 0] : 1;
152
+ allVAttr[va + 5] = tan ? tan[i * 4 + 1] : 0;
153
+ allVAttr[va + 6] = tan ? tan[i * 4 + 2] : 0;
154
+ allVAttr[va + 7] = tan ? tan[i * 4 + 3] : 1;
155
+ allVAttr[va + 8] = uv ? uv[i * 2 + 1] : 0;
156
+ }
157
+ for (let i = 0; i < ind.length; i++) allIndices[iOff++] = vOff + ind[i];
158
+ const pTris = ind.length / 3;
159
+ triMatIds.fill(mi, tOff, tOff + pTris);
160
+ tOff += pTris;
161
+ vOff += vCount;
162
+ }
163
+ }
164
+ return { allPos, allVAttr, allIndices, triMatIds, totalVerts, totalIndices, totalTris };
165
+ }
166
+
167
+ export async function loadGltfScene(device, opts) {
168
+ const { baseUrl, gltfFile, binFile, scale = 1.0, onProgress } = opts;
169
+ if (onProgress) onProgress(`Fetching ${gltfFile}…`);
170
+ const [gltfResp, binResp] = await Promise.all([fetchWithRetry(baseUrl + gltfFile), fetchWithRetry(baseUrl + binFile)]);
171
+ const [gltf, bin] = await Promise.all([gltfResp.json(), binResp.arrayBuffer()]);
172
+
173
+ const geom = unpackGeometry(gltf, bin, scale);
174
+ const vAttrBuf = device.createBuffer({ size: geom.allVAttr.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
175
+ device.queue.writeBuffer(vAttrBuf, 0, geom.allVAttr);
176
+ const idxAttrBuf = device.createBuffer({ size: geom.allIndices.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
177
+ device.queue.writeBuffer(idxAttrBuf, 0, geom.allIndices);
178
+ const triMatBuf = device.createBuffer({ size: geom.triMatIds.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
179
+ device.queue.writeBuffer(triMatBuf, 0, geom.triMatIds);
180
+
181
+ const tex = loadPbrTextureArrays(device, gltf, { baseUrl, onProgress });
182
+ const tBvh0 = performance.now();
183
+ const vb = device.createBuffer({ size: geom.allPos.byteLength, usage: GPUBufferUsage.ACCELERATION_STRUCTURE_INPUT | GPUBufferUsage.COPY_DST });
184
+ device.queue.writeBuffer(vb, 0, geom.allPos);
185
+ const ib = device.createBuffer({ size: geom.allIndices.byteLength, usage: GPUBufferUsage.ACCELERATION_STRUCTURE_INPUT | GPUBufferUsage.COPY_DST });
186
+ device.queue.writeBuffer(ib, 0, geom.allIndices);
187
+
188
+ const blas = device.createBlas({
189
+ label: "gltf_unified",
190
+ geometries: [{ vertexFormat: "float32x3", maxVertexCount: geom.totalVerts, indexFormat: "uint32", maxPrimitiveCount: geom.totalTris, flags: 1 }],
191
+ });
192
+ const tlas = device.createTlas({ label: "gltfTlas", maxInstances: 1 });
193
+ const enc = device.createCommandEncoder();
194
+ enc.buildAccelerationStructures(
195
+ [{ blas, geometries: [{ vertexBuffer: vb, vertexStride: 12, vertexCount: geom.totalVerts, vertexFormat: "float32x3", indexBuffer: ib, indexFormat: "uint32", indexCount: geom.totalIndices, flags: 1 }] }],
196
+ [{ tlas, instances: [{ blas, transform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], customIndex: 0 }] }]
197
+ );
198
+ device.queue.submit([enc.finish()]);
199
+ return { tlas, vAttrBuf, idxAttrBuf, triMatBuf, ...tex, triCount: geom.totalTris, bvhMs: Math.round(performance.now() - tBvh0) };
200
+ }
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createMagmaPathTracer, halton } from "./renderer.js";
2
+ export { loadGltfScene } from "./gltfLoader.js";
3
+ export { createPathTraceWgsl } from "./shaders/ptShader.js";
4
+ export { createFilterMomentsWgsl, createAtrousWgsl } from "./shaders/svgfShaders.js";
5
+ export { createComposeWgsl, createTaauWgsl, createRcasBlitWgsl } from "./shaders/postShaders.js";
@@ -0,0 +1,253 @@
1
+ import { createPathTraceWgsl } from "./shaders/ptShader.js";
2
+ import { createFilterMomentsWgsl, createAtrousWgsl } from "./shaders/svgfShaders.js";
3
+ import { createComposeWgsl, createTaauWgsl, createRcasBlitWgsl } from "./shaders/postShaders.js";
4
+
5
+ export function halton(index, base) {
6
+ let f = 1.0;
7
+ let r = 0.0;
8
+ let i = index;
9
+ while (i > 0) {
10
+ f /= base;
11
+ r += f * (i % base);
12
+ i = Math.floor(i / base);
13
+ }
14
+ return r;
15
+ }
16
+
17
+ function createTextures(device, W, H, outW, outH) {
18
+ const mk = (fmt, w = W, h = H) =>
19
+ device.createTexture({ size: [w, h], format: fmt, usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING });
20
+ return {
21
+ reprojectIllum: mk("rgba16float"),
22
+ momentsA: mk("rgba16float"), momentsB: mk("rgba16float"),
23
+ histIllumA: mk("rgba16float"), histIllumB: mk("rgba16float"),
24
+ directA: mk("rgba16float"), directB: mk("rgba16float"),
25
+ posA: mk("rgba32float"), posB: mk("rgba32float"),
26
+ normA: mk("rgba16float"), normB: mk("rgba16float"),
27
+ albedoTex: mk("rgba16float"), rawIndTex: mk("rgba16float"),
28
+ filtA: mk("rgba16float"), filtB: mk("rgba16float"),
29
+ curLdrTex: mk("rgba16float"),
30
+ taaA: mk("rgba16float", outW, outH), taaB: mk("rgba16float", outW, outH),
31
+ };
32
+ }
33
+
34
+ function createUniforms(device, W, H) {
35
+ const mk = (size) => device.createBuffer({ size, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
36
+ const fmUniformBuf = mk(16);
37
+ device.queue.writeBuffer(fmUniformBuf, 0, new Float32Array([W, H, 4.0, 128.0]));
38
+ const atrousUniformBufs = [1, 2, 4, 8].map((step) => {
39
+ const b = mk(16);
40
+ device.queue.writeBuffer(b, 0, new Float32Array([W, H, step, 4.0]));
41
+ return b;
42
+ });
43
+ return {
44
+ ptUniformBuf: mk(16 * 12),
45
+ fmUniformBuf,
46
+ atrousUniformBufs,
47
+ composeUniformBuf: mk(32),
48
+ taaUniformBuf: mk(16 * 11),
49
+ blitUniformBuf: mk(16),
50
+ };
51
+ }
52
+
53
+ function createPipelines(device, format) {
54
+ const cs = (code) => device.createShaderModule({ code });
55
+ const unfilt = (binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, texture: { sampleType: "unfilterable-float" } });
56
+ const store = (binding, formatName = "rgba16float") => ({ binding, visibility: GPUShaderStage.COMPUTE, storageTexture: { access: "write-only", format: formatName } });
57
+ const unif = (binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } });
58
+ const roBuf = (binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } });
59
+ const arr2d = (binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, texture: { viewDimension: "2d-array" } });
60
+
61
+ const ptBgl = device.createBindGroupLayout({
62
+ entries: [
63
+ { binding: 0, visibility: GPUShaderStage.COMPUTE, accelerationStructure: {} },
64
+ unfilt(1), unfilt(2), unfilt(3), unfilt(4), unfilt(5),
65
+ store(6), store(7), store(8), store(9, "rgba32float"), store(10), store(11), store(12),
66
+ unif(13), roBuf(14), roBuf(15), roBuf(16), roBuf(17),
67
+ arr2d(18), arr2d(19), arr2d(20),
68
+ { binding: 21, visibility: GPUShaderStage.COMPUTE, sampler: {} },
69
+ ],
70
+ });
71
+ const fmBgl = device.createBindGroupLayout({ entries: [unfilt(0), unfilt(1), unfilt(2), unfilt(3), store(4), unif(5)] });
72
+ const atrousBgl = device.createBindGroupLayout({ entries: [unfilt(0), unfilt(1), unfilt(2), store(3), unif(4)] });
73
+ const composeBgl = device.createBindGroupLayout({ entries: [unfilt(0), unfilt(1), unfilt(2), unfilt(3), unfilt(4), unfilt(5), store(6), unif(7)] });
74
+ const taaBgl = device.createBindGroupLayout({
75
+ entries: [
76
+ unfilt(0), { binding: 1, visibility: GPUShaderStage.COMPUTE, texture: { sampleType: "float" } },
77
+ unfilt(2), { binding: 3, visibility: GPUShaderStage.COMPUTE, sampler: {} }, store(4), unif(5),
78
+ ],
79
+ });
80
+
81
+ const mkPipe = (bgl, code) => device.createComputePipeline({ layout: device.createPipelineLayout({ bindGroupLayouts: [bgl] }), compute: { module: cs(code), entryPoint: "main" } });
82
+ const blitMod = cs(createRcasBlitWgsl());
83
+ return {
84
+ ptBgl, fmBgl, atrousBgl, composeBgl, taaBgl,
85
+ ptPipe: mkPipe(ptBgl, createPathTraceWgsl()),
86
+ fmPipe: mkPipe(fmBgl, createFilterMomentsWgsl()),
87
+ atrousPipe: mkPipe(atrousBgl, createAtrousWgsl()),
88
+ composePipe: mkPipe(composeBgl, createComposeWgsl()),
89
+ taaPipe: mkPipe(taaBgl, createTaauWgsl()),
90
+ blitPipe: device.createRenderPipeline({
91
+ layout: "auto",
92
+ vertex: { module: blitMod, entryPoint: "vs" },
93
+ fragment: { module: blitMod, entryPoint: "fs", targets: [{ format }] },
94
+ primitive: { topology: "triangle-list" },
95
+ }),
96
+ };
97
+ }
98
+
99
+ function createBindGroups(device, state) {
100
+ const { pipes, tex, unif, scene } = state;
101
+ const texSamp = device.createSampler({ magFilter: "linear", minFilter: "linear", addressModeU: "repeat", addressModeV: "repeat" });
102
+ const linearSamp = device.createSampler({ magFilter: "linear", minFilter: "linear" });
103
+
104
+ const makePtBg = (pH, pM, pD, pP, pN, nM, nD, cP, cN) => device.createBindGroup({
105
+ layout: pipes.ptBgl,
106
+ entries: [
107
+ { binding: 0, resource: scene.tlas }, { binding: 1, resource: pH.createView() }, { binding: 2, resource: pM.createView() },
108
+ { binding: 3, resource: pD.createView() }, { binding: 4, resource: pP.createView() }, { binding: 5, resource: pN.createView() },
109
+ { binding: 6, resource: tex.reprojectIllum.createView() }, { binding: 7, resource: nM.createView() }, { binding: 8, resource: nD.createView() },
110
+ { binding: 9, resource: cP.createView() }, { binding: 10, resource: cN.createView() }, { binding: 11, resource: tex.albedoTex.createView() },
111
+ { binding: 12, resource: tex.rawIndTex.createView() }, { binding: 13, resource: { buffer: unif.ptUniformBuf } },
112
+ { binding: 14, resource: { buffer: scene.vAttrBuf } }, { binding: 15, resource: { buffer: scene.idxAttrBuf } },
113
+ { binding: 16, resource: { buffer: scene.triMatBuf } }, { binding: 17, resource: { buffer: scene.matBuf } },
114
+ { binding: 18, resource: scene.albedoArr.createView({ dimension: "2d-array" }) },
115
+ { binding: 19, resource: scene.normalArr.createView({ dimension: "2d-array" }) },
116
+ { binding: 20, resource: scene.mrArr.createView({ dimension: "2d-array" }) },
117
+ { binding: 21, resource: texSamp },
118
+ ],
119
+ });
120
+
121
+ const makeFmBg = (cM, cP, cN) => device.createBindGroup({
122
+ layout: pipes.fmBgl,
123
+ entries: [
124
+ { binding: 0, resource: tex.reprojectIllum.createView() }, { binding: 1, resource: cM.createView() },
125
+ { binding: 2, resource: cP.createView() }, { binding: 3, resource: cN.createView() },
126
+ { binding: 4, resource: tex.filtA.createView() }, { binding: 5, resource: { buffer: unif.fmUniformBuf } },
127
+ ],
128
+ });
129
+
130
+ const makeAtrousSet = (nH, cP, cN) => [
131
+ [tex.filtA, nH, 0], [nH, tex.filtB, 1], [tex.filtB, tex.filtA, 2], [tex.filtA, tex.filtB, 3],
132
+ ].map(([src, dst, idx]) => device.createBindGroup({
133
+ layout: pipes.atrousBgl,
134
+ entries: [
135
+ { binding: 0, resource: src.createView() }, { binding: 1, resource: cP.createView() },
136
+ { binding: 2, resource: cN.createView() }, { binding: 3, resource: dst.createView() },
137
+ { binding: 4, resource: { buffer: unif.atrousUniformBufs[idx] } },
138
+ ],
139
+ }));
140
+
141
+ const makeComposeBg = (dT, cN, cM) => device.createBindGroup({
142
+ layout: pipes.composeBgl,
143
+ entries: [
144
+ { binding: 0, resource: dT.createView() }, { binding: 1, resource: tex.filtB.createView() },
145
+ { binding: 2, resource: tex.rawIndTex.createView() }, { binding: 3, resource: tex.albedoTex.createView() },
146
+ { binding: 4, resource: cN.createView() }, { binding: 5, resource: cM.createView() },
147
+ { binding: 6, resource: tex.curLdrTex.createView() }, { binding: 7, resource: { buffer: unif.composeUniformBuf } },
148
+ ],
149
+ });
150
+
151
+ const makeTaaBg = (prevT, cP, nextT) => device.createBindGroup({
152
+ layout: pipes.taaBgl,
153
+ entries: [
154
+ { binding: 0, resource: tex.curLdrTex.createView() }, { binding: 1, resource: prevT.createView() },
155
+ { binding: 2, resource: cP.createView() }, { binding: 3, resource: linearSamp },
156
+ { binding: 4, resource: nextT.createView() }, { binding: 5, resource: { buffer: unif.taaUniformBuf } },
157
+ ],
158
+ });
159
+
160
+ const makeBlitBg = (srcT) => device.createBindGroup({
161
+ layout: pipes.blitPipe.getBindGroupLayout(0),
162
+ entries: [{ binding: 0, resource: srcT.createView() }, { binding: 1, resource: { buffer: unif.blitUniformBuf } }],
163
+ });
164
+
165
+ return {
166
+ pt: [
167
+ makePtBg(tex.histIllumA, tex.momentsA, tex.directA, tex.posA, tex.normA, tex.momentsB, tex.directB, tex.posB, tex.normB),
168
+ makePtBg(tex.histIllumB, tex.momentsB, tex.directB, tex.posB, tex.normB, tex.momentsA, tex.directA, tex.posA, tex.normA),
169
+ ],
170
+ fm: [makeFmBg(tex.momentsB, tex.posB, tex.normB), makeFmBg(tex.momentsA, tex.posA, tex.normA)],
171
+ atrous: [makeAtrousSet(tex.histIllumB, tex.posB, tex.normB), makeAtrousSet(tex.histIllumA, tex.posA, tex.normA)],
172
+ compose: [makeComposeBg(tex.directB, tex.normB, tex.momentsB), makeComposeBg(tex.directA, tex.normA, tex.momentsA)],
173
+ taa: [makeTaaBg(tex.taaA, tex.posB, tex.taaB), makeTaaBg(tex.taaB, tex.posA, tex.taaA)],
174
+ blit: [makeBlitBg(tex.taaB), makeBlitBg(tex.taaA)],
175
+ };
176
+ }
177
+
178
+ export function createMagmaPathTracer(device, canvas, scene, options = {}) {
179
+ const W = options.renderWidth || 960;
180
+ const H = options.renderHeight || 540;
181
+ const outW = options.outputWidth || 1920;
182
+ const outH = options.outputHeight || 1080;
183
+ const fov = options.fov || 0.62;
184
+ const ctx = canvas.getContext("webgpu");
185
+ const format = navigator.gpu.getPreferredCanvasFormat();
186
+ canvas.width = outW;
187
+ canvas.height = outH;
188
+ ctx.configure({ device, format, alphaMode: "opaque" });
189
+
190
+ const tex = createTextures(device, W, H, outW, outH);
191
+ const unif = createUniforms(device, W, H);
192
+ const pipes = createPipelines(device, format);
193
+ const bgs = createBindGroups(device, { pipes, tex, unif, scene });
194
+
195
+ const ptU = new ArrayBuffer(16 * 12), ptF = new Float32Array(ptU), ptI = new Uint32Array(ptU);
196
+ const taaU = new ArrayBuffer(16 * 11), taaF = new Float32Array(taaU), taaI = new Uint32Array(taaU);
197
+ let prevCam = null;
198
+ let frameCounter = 0;
199
+ let ping = 0;
200
+
201
+ function renderFrame(params) {
202
+ const { camera, sunDir, sunIntensity = 10.5, bounces = 3, exposure = 1.5, toneMap = 0, aovView = 0, denoise = true, splitX = 1.0, sharpness = 0.7, moved = false, lightDirty = false, timeSec = 0 } = params;
203
+ if (!prevCam) prevCam = camera;
204
+ const curFrame = frameCounter++;
205
+ const hIdx = (curFrame & 15) + 1;
206
+
207
+ ptF.set([...camera.pos, 0, ...camera.fwd, 0, ...camera.right, 0, ...camera.up, 0, ...prevCam.pos, 0, ...prevCam.fwd, 0, ...prevCam.right, 0, ...prevCam.up, 0, ...sunDir, sunIntensity, W, H, timeSec, fov], 0);
208
+ ptI[40] = moved ? 1 : 0; ptI[41] = bounces; ptI[42] = curFrame; ptI[43] = lightDirty ? 1 : 0;
209
+ device.queue.writeBuffer(unif.ptUniformBuf, 0, ptU);
210
+
211
+ device.queue.writeBuffer(unif.composeUniformBuf, 0, new Float32Array([exposure, splitX, denoise ? 1.0 : 0.0, toneMap, aovView, W, H, 0.0]));
212
+
213
+ const taaEnabled = denoise && aovView === 0 ? 1 : 0;
214
+ taaF.set([...camera.pos, 0, ...camera.fwd, 0, ...camera.right, 0, ...camera.up, 0, ...prevCam.pos, 0, ...prevCam.fwd, 0, ...prevCam.right, 0, ...prevCam.up, 0, W, H, outW, outH, fov, moved ? 0.24 : 0.12, halton(hIdx, 2), halton(hIdx, 3)], 0);
215
+ taaI[40] = taaEnabled; taaI[41] = curFrame; taaI[42] = moved ? 1 : 0;
216
+ device.queue.writeBuffer(unif.taaUniformBuf, 0, taaU);
217
+ device.queue.writeBuffer(unif.blitUniformBuf, 0, new Float32Array([outW, outH, sharpness, taaEnabled ? 1.0 : 0.0]));
218
+
219
+ const enc = device.createCommandEncoder();
220
+ const wgX = Math.ceil(W / 8), wgY = Math.ceil(H / 8);
221
+ const outWgX = Math.ceil(outW / 8), outWgY = Math.ceil(outH / 8);
222
+
223
+ const cpass = enc.beginComputePass();
224
+ cpass.setPipeline(pipes.ptPipe); cpass.setBindGroup(0, bgs.pt[ping]); cpass.dispatchWorkgroups(wgX, wgY);
225
+ cpass.setPipeline(pipes.fmPipe); cpass.setBindGroup(0, bgs.fm[ping]); cpass.dispatchWorkgroups(wgX, wgY);
226
+ cpass.setPipeline(pipes.atrousPipe);
227
+ for (let k = 0; k < 4; k++) { cpass.setBindGroup(0, bgs.atrous[ping][k]); cpass.dispatchWorkgroups(wgX, wgY); }
228
+ cpass.setPipeline(pipes.composePipe); cpass.setBindGroup(0, bgs.compose[ping]); cpass.dispatchWorkgroups(wgX, wgY);
229
+ cpass.setPipeline(pipes.taaPipe); cpass.setBindGroup(0, bgs.taa[ping]); cpass.dispatchWorkgroups(outWgX, outWgY);
230
+ cpass.end();
231
+
232
+ const rpass = enc.beginRenderPass({
233
+ colorAttachments: [{ view: ctx.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: { r: 0, g: 0, b: 0, a: 1 } }],
234
+ });
235
+ rpass.setPipeline(pipes.blitPipe); rpass.setBindGroup(0, bgs.blit[ping]); rpass.draw(3); rpass.end();
236
+ device.queue.submit([enc.finish()]);
237
+
238
+ prevCam = camera;
239
+ ping ^= 1;
240
+ }
241
+
242
+ function destroy() {
243
+ Object.values(tex).forEach((t) => t.destroy());
244
+ unif.ptUniformBuf.destroy();
245
+ unif.fmUniformBuf.destroy();
246
+ unif.atrousUniformBufs.forEach((b) => b.destroy());
247
+ unif.composeUniformBuf.destroy();
248
+ unif.taaUniformBuf.destroy();
249
+ unif.blitUniformBuf.destroy();
250
+ }
251
+
252
+ return { renderFrame, destroy, renderWidth: W, renderHeight: H, outputWidth: outW, outputHeight: outH };
253
+ }