@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.
@@ -0,0 +1,231 @@
1
+ export function createComposeWgsl() {
2
+ return `
3
+ struct ComposeU { exposure: f32, splitX: f32, useDenoise: f32, toneMap: f32, aovView: f32, W: f32, H: f32, p0: f32 };
4
+ @group(0) @binding(0) var directT: texture_2d<f32>;
5
+ @group(0) @binding(1) var denIndT: texture_2d<f32>;
6
+ @group(0) @binding(2) var rawIndT: texture_2d<f32>;
7
+ @group(0) @binding(3) var albedoT: texture_2d<f32>;
8
+ @group(0) @binding(4) var normT: texture_2d<f32>;
9
+ @group(0) @binding(5) var momentsT: texture_2d<f32>;
10
+ @group(0) @binding(6) var outLdr: texture_storage_2d<rgba16float, write>;
11
+ @group(0) @binding(7) var<uniform> u: ComposeU;
12
+
13
+ fn agxContrast(x: vec3<f32>) -> vec3<f32> {
14
+ let x2 = x * x; let x4 = x2 * x2;
15
+ return 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232;
16
+ }
17
+ fn toneMapAgX(val: vec3<f32>) -> vec3<f32> {
18
+ let agxMat = mat3x3<f32>(
19
+ vec3<f32>(0.842479062253094, 0.0423282422610123, 0.0423756549057051),
20
+ vec3<f32>(0.0784335999999992, 0.878468636469772, 0.0784336),
21
+ vec3<f32>(0.0792237451477643, 0.0791661274605434, 0.879142973793104)
22
+ );
23
+ let agxMatInv = mat3x3<f32>(
24
+ vec3<f32>(1.19687900512017, -0.0528968517574562, -0.0529716355144438),
25
+ vec3<f32>(-0.0980208811401368, 1.15190312990417, -0.0980434501171241),
26
+ vec3<f32>(-0.0990297440797205, -0.0989611768448433, 1.15107367264116)
27
+ );
28
+ var c = agxMat * max(val, vec3<f32>(1e-6));
29
+ c = clamp((log2(c) - (-12.47393)) / (4.026069 - (-12.47393)), vec3<f32>(0.0), vec3<f32>(1.0));
30
+ return clamp(agxMatInv * agxContrast(c), vec3<f32>(0.0), vec3<f32>(1.0));
31
+ }
32
+ fn toneMapACES(hdr: vec3<f32>) -> vec3<f32> {
33
+ let m = (hdr * (2.51 * hdr + 0.03)) / (hdr * (2.43 * hdr + 0.59) + 0.14);
34
+ return pow(clamp(m, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(1.0 / 2.2));
35
+ }
36
+
37
+ @compute @workgroup_size(8, 8)
38
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
39
+ let W = i32(u.W); let H = i32(u.H);
40
+ if (i32(gid.x) >= W || i32(gid.y) >= H) { return; }
41
+ let p = vec2<i32>(i32(gid.x), i32(gid.y));
42
+ let uvX = (f32(gid.x) + 0.5) / u.W;
43
+ let aov = i32(u.aovView);
44
+ let alb = textureLoad(albedoT, p, 0);
45
+ let dir4 = textureLoad(directT, p, 0);
46
+ let denInd4 = textureLoad(denIndT, p, 0);
47
+ let rawInd = textureLoad(rawIndT, p, 0).rgb;
48
+
49
+ var col = vec3<f32>(0.0);
50
+ if (aov == 5) { col = textureLoad(normT, p, 0).xyz * 0.5 + 0.5; }
51
+ else if (aov == 6) { col = pow(clamp(alb.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(1.0 / 2.2)); }
52
+ else if (aov == 3) {
53
+ let v = clamp(sqrt(max(denInd4.a, 0.0)) * 2.5, 0.0, 1.0);
54
+ col = vec3<f32>(v, v * (1.0 - v) * 2.5, 1.0 - v);
55
+ } else if (aov == 4) {
56
+ let h = clamp(textureLoad(momentsT, p, 0).z / 64.0, 0.0, 1.0);
57
+ col = vec3<f32>(1.0 - h, h, 0.25);
58
+ } else {
59
+ let showDen = (u.useDenoise > 0.5) && (uvX <= u.splitX);
60
+ let indL = select(rawInd, denInd4.rgb * mix(0.45, 1.0, clamp(dir4.a, 0.0, 1.0)), showDen);
61
+ var hdr = select(alb.rgb * (dir4.rgb + indL), alb.rgb, alb.a > 0.5) * u.exposure;
62
+ if (aov == 1) { hdr = indL * u.exposure; }
63
+ if (aov == 2) { hdr = dir4.rgb * u.exposure; }
64
+ col = select(toneMapAgX(hdr), toneMapACES(hdr), u.toneMap > 0.5);
65
+ }
66
+ textureStore(outLdr, p, vec4<f32>(col, 1.0));
67
+ }`;
68
+ }
69
+
70
+ function taauHelpers() {
71
+ return `
72
+ struct TaaU {
73
+ curCamPos: vec4<f32>, curCamFwd: vec4<f32>, curCamRight: vec4<f32>, curCamUp: vec4<f32>,
74
+ prevCamPos: vec4<f32>, prevCamFwd: vec4<f32>, prevCamRight: vec4<f32>, prevCamUp: vec4<f32>,
75
+ sizes: vec4<f32>, params: vec4<f32>, cfg: vec4<u32>,
76
+ };
77
+ @group(0) @binding(0) var curT: texture_2d<f32>;
78
+ @group(0) @binding(1) var prevTaaT: texture_2d<f32>;
79
+ @group(0) @binding(2) var curPosT: texture_2d<f32>;
80
+ @group(0) @binding(3) var linSamp: sampler;
81
+ @group(0) @binding(4) var outTaa: texture_storage_2d<rgba16float, write>;
82
+ @group(0) @binding(5) var<uniform> u: TaaU;
83
+
84
+ fn rgbToYCoCg(c: vec3<f32>) -> vec3<f32> {
85
+ return vec3<f32>(0.25 * c.r + 0.5 * c.g + 0.25 * c.b, 0.5 * c.r - 0.5 * c.b, -0.25 * c.r + 0.5 * c.g - 0.25 * c.b);
86
+ }
87
+ fn yCoCgToRgb(c: vec3<f32>) -> vec3<f32> {
88
+ let tmp = c.x - c.z;
89
+ return clamp(vec3<f32>(tmp + c.y, c.x + c.z, tmp - c.y), vec3<f32>(0.0), vec3<f32>(1.0));
90
+ }
91
+ fn clipToAABB(hist: vec3<f32>, bMin: vec3<f32>, bMax: vec3<f32>) -> vec3<f32> {
92
+ let boxCenter = 0.5 * (bMax + bMin);
93
+ let boxExt = max(0.5 * (bMax - bMin), vec3<f32>(1e-5));
94
+ let ray = hist - boxCenter;
95
+ let vUnit = abs(ray / boxExt);
96
+ let maxUnit = max(vUnit.x, max(vUnit.y, vUnit.z));
97
+ return select(hist, boxCenter + ray / maxUnit, maxUnit > 1.0);
98
+ }
99
+ fn sampleCatmullRom(tex: texture_2d<f32>, samp: sampler, uv: vec2<f32>, texSize: vec2<f32>) -> vec3<f32> {
100
+ let samplePos = uv * texSize;
101
+ let texPos1 = floor(samplePos - 0.5) + 0.5;
102
+ let f = samplePos - texPos1;
103
+ let w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
104
+ let w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
105
+ let w2 = f * (0.5 + f * (2.0 - 1.5 * f));
106
+ let w3 = f * f * (-0.5 + 0.5 * f);
107
+ let w12 = w1 + w2;
108
+ let invSize = 1.0 / texSize;
109
+ let lo = invSize * 0.5;
110
+ let hi = vec2<f32>(1.0) - lo;
111
+ let p0 = clamp((texPos1 - 1.0) * invSize, lo, hi);
112
+ let p3 = clamp((texPos1 + 2.0) * invSize, lo, hi);
113
+ let p12 = clamp((texPos1 + w2 / max(w12, vec2<f32>(1e-5))) * invSize, lo, hi);
114
+ var res = textureSampleLevel(tex, samp, vec2<f32>(p12.x, p0.y), 0.0).rgb * (w12.x * w0.y);
115
+ res += textureSampleLevel(tex, samp, vec2<f32>(p0.x, p12.y), 0.0).rgb * (w0.x * w12.y);
116
+ res += textureSampleLevel(tex, samp, vec2<f32>(p12.x, p12.y), 0.0).rgb * (w12.x * w12.y);
117
+ res += textureSampleLevel(tex, samp, vec2<f32>(p3.x, p12.y), 0.0).rgb * (w3.x * w12.y);
118
+ res += textureSampleLevel(tex, samp, vec2<f32>(p12.x, p3.y), 0.0).rgb * (w12.x * w3.y);
119
+ let wTot = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
120
+ return clamp(res / max(wTot, 1e-5), vec3<f32>(0.0), vec3<f32>(1.0));
121
+ }`;
122
+ }
123
+
124
+ function taauMainBody() {
125
+ return `
126
+ @compute @workgroup_size(8, 8)
127
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
128
+ let outW = i32(u.sizes.z); let outH = i32(u.sizes.w);
129
+ if (i32(gid.x) >= outW || i32(gid.y) >= outH) { return; }
130
+ let W = i32(u.sizes.x); let H = i32(u.sizes.y);
131
+ let op = vec2<i32>(i32(gid.x), i32(gid.y));
132
+ let outUv = (vec2<f32>(f32(gid.x) + 0.5, f32(gid.y) + 0.5)) / u.sizes.zw;
133
+ let rPos = outUv * u.sizes.xy;
134
+ let centerRp = vec2<i32>(floor(rPos));
135
+
136
+ var m1 = vec3<f32>(0.0); var m2 = vec3<f32>(0.0);
137
+ var bhSum = vec3<f32>(0.0); var bhW = 0.0;
138
+ var minDist2 = 1e9; var nearestCol = vec3<f32>(0.0);
139
+ var bestPos = vec4<f32>(0.0, 0.0, 0.0, 100.0);
140
+
141
+ for (var dy: i32 = -1; dy <= 1; dy++) {
142
+ for (var dx: i32 = -1; dx <= 1; dx++) {
143
+ let q = clamp(centerRp + vec2<i32>(dx, dy), vec2<i32>(0, 0), vec2<i32>(W - 1, H - 1));
144
+ let c = textureLoad(curT, q, 0).rgb;
145
+ let yc = rgbToYCoCg(c);
146
+ m1 += yc; m2 += yc * yc;
147
+ let d = (vec2<f32>(f32(q.x), f32(q.y)) + u.params.zw) - rPos;
148
+ let dist2 = dot(d, d);
149
+ if (dist2 < minDist2) { minDist2 = dist2; nearestCol = c; }
150
+ let w = exp(-2.29 * dist2);
151
+ bhSum += c * w; bhW += w;
152
+ let pq = textureLoad(curPosT, q, 0);
153
+ if (pq.w < bestPos.w) { bestPos = pq; }
154
+ }
155
+ }
156
+ let curBH = bhSum / max(bhW, 1e-5);
157
+ let cur = mix(curBH, nearestCol, smoothstep(0.18, 0.02, minDist2));
158
+ if (u.cfg.x == 0u || u.cfg.y == 0u) { textureStore(outTaa, op, vec4<f32>(curBH, 1.0)); return; }
159
+
160
+ m1 /= 9.0; m2 /= 9.0;
161
+ let sigma = sqrt(max(m2 - m1 * m1, vec3<f32>(0.0)));
162
+ let isMoving = u.cfg.z != 0u;
163
+ let gamma = select(1.45, 0.85, isMoving);
164
+ let boxMin = m1 - sigma * gamma;
165
+ let boxMax = m1 + sigma * gamma;
166
+
167
+ var valid = true; var histRgb = cur; var speedPx = 0.0;
168
+ if (!isMoving) {
169
+ histRgb = textureLoad(prevTaaT, op, 0).rgb;
170
+ } else if (bestPos.w < 90.0) {
171
+ let aspect = u.sizes.x / u.sizes.y; let fov = u.params.x;
172
+ let vCur = bestPos.xyz - u.curCamPos.xyz; let zCur = dot(vCur, u.curCamFwd.xyz);
173
+ let vPrev = bestPos.xyz - u.prevCamPos.xyz; let zPrev = dot(vPrev, u.prevCamFwd.xyz);
174
+ if (zCur > 0.02 && zPrev > 0.02) {
175
+ let curBestUv = vec2<f32>(dot(vCur, u.curCamRight.xyz) / (zCur * aspect * fov), -dot(vCur, u.curCamUp.xyz) / (zCur * fov)) * 0.5 + 0.5;
176
+ let prevBestUv = vec2<f32>(dot(vPrev, u.prevCamRight.xyz) / (zPrev * aspect * fov), -dot(vPrev, u.prevCamUp.xyz) / (zPrev * fov)) * 0.5 + 0.5;
177
+ let velocity = curBestUv - prevBestUv;
178
+ speedPx = length(velocity * u.sizes.zw);
179
+ let prevUv = outUv - velocity;
180
+ if (prevUv.x >= 0.0 && prevUv.x < 1.0 && prevUv.y >= 0.0 && prevUv.y < 1.0) {
181
+ histRgb = sampleCatmullRom(prevTaaT, linSamp, prevUv, u.sizes.zw);
182
+ } else { valid = false; }
183
+ } else { valid = false; }
184
+ } else { valid = false; }
185
+
186
+ var resolved = cur;
187
+ if (valid) {
188
+ let histClipped = yCoCgToRgb(clipToAABB(rgbToYCoCg(histRgb), boxMin, boxMax));
189
+ let staticAlpha = clamp(u.params.y * mix(0.15, 1.4, exp(-3.5 * minDist2)), 0.015, 0.35);
190
+ let motionAlpha = mix(0.24, 0.55, clamp(speedPx / 16.0, 0.0, 1.0));
191
+ resolved = mix(histClipped, cur, select(staticAlpha, motionAlpha, isMoving));
192
+ }
193
+ textureStore(outTaa, op, vec4<f32>(resolved, 1.0));
194
+ }`;
195
+ }
196
+
197
+ export function createTaauWgsl() {
198
+ return `${taauHelpers()}\n${taauMainBody()}`;
199
+ }
200
+
201
+ export function createRcasBlitWgsl() {
202
+ return `
203
+ struct BlitU { outW: f32, outH: f32, sharpness: f32, enabled: f32 };
204
+ @group(0) @binding(0) var tex: texture_2d<f32>;
205
+ @group(0) @binding(1) var<uniform> u: BlitU;
206
+ struct VSOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> };
207
+ @vertex fn vs(@builtin(vertex_index) vid: u32) -> VSOut {
208
+ var p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
209
+ var o: VSOut;
210
+ o.pos = vec4<f32>(p[vid], 0.0, 1.0);
211
+ o.uv = vec2<f32>(p[vid].x * 0.5 + 0.5, 0.5 - p[vid].y * 0.5);
212
+ return o;
213
+ }
214
+ @fragment fn fs(inp: VSOut) -> @location(0) vec4<f32> {
215
+ let maxC = vec2<i32>(i32(u.outW) - 1, i32(u.outH) - 1);
216
+ let ip = clamp(vec2<i32>(inp.pos.xy), vec2<i32>(0, 0), maxC);
217
+ let e = textureLoad(tex, ip, 0).rgb;
218
+ if (u.enabled < 0.5 || u.sharpness <= 0.001) { return vec4<f32>(e, 1.0); }
219
+ let b = textureLoad(tex, clamp(ip + vec2<i32>(0, -1), vec2<i32>(0, 0), maxC), 0).rgb;
220
+ let d = textureLoad(tex, clamp(ip + vec2<i32>(-1, 0), vec2<i32>(0, 0), maxC), 0).rgb;
221
+ let f = textureLoad(tex, clamp(ip + vec2<i32>(1, 0), vec2<i32>(0, 0), maxC), 0).rgb;
222
+ let h = textureLoad(tex, clamp(ip + vec2<i32>(0, 1), vec2<i32>(0, 0), maxC), 0).rgb;
223
+ let mn4 = min(min(b, d), min(f, h));
224
+ let mx4 = max(max(b, d), max(f, h));
225
+ let hitMin = min(mn4, e) / max(4.0 * mx4, vec3<f32>(1e-5));
226
+ let hitMax = (vec3<f32>(1.0) - max(mx4, e)) / min(4.0 * mn4 - vec3<f32>(4.0), vec3<f32>(-1e-5));
227
+ let lobeRGB = max(-hitMin, hitMax);
228
+ let lobe = max(-0.1875, min(max(lobeRGB.r, max(lobeRGB.g, lobeRGB.b)), 0.0)) * u.sharpness;
229
+ return vec4<f32>(clamp((lobe * (b + d + f + h) + e) / (4.0 * lobe + 1.0), vec3<f32>(0.0), vec3<f32>(1.0)), 1.0);
230
+ }`;
231
+ }
@@ -0,0 +1,431 @@
1
+ function ptHeaderAndBindings() {
2
+ return `
3
+ enable magma_ray_query;
4
+
5
+ struct PTUniforms {
6
+ camPos: vec4<f32>,
7
+ camFwd: vec4<f32>,
8
+ camRight: vec4<f32>,
9
+ camUp: vec4<f32>,
10
+ prevCamPos: vec4<f32>,
11
+ prevCamFwd: vec4<f32>,
12
+ prevCamRight: vec4<f32>,
13
+ prevCamUp: vec4<f32>,
14
+ sunDir: vec4<f32>,
15
+ params: vec4<f32>,
16
+ cfg: vec4<u32>,
17
+ pad: vec4<u32>,
18
+ };
19
+
20
+ @group(0) @binding(0) var scene: acceleration_structure;
21
+ @group(0) @binding(1) var prevHistIllumT: texture_2d<f32>;
22
+ @group(0) @binding(2) var prevMomentsT: texture_2d<f32>;
23
+ @group(0) @binding(3) var prevDirectT: texture_2d<f32>;
24
+ @group(0) @binding(4) var prevPosT: texture_2d<f32>;
25
+ @group(0) @binding(5) var prevNormT: texture_2d<f32>;
26
+ @group(0) @binding(6) var reprojectOut: texture_storage_2d<rgba16float, write>;
27
+ @group(0) @binding(7) var momentsOut: texture_storage_2d<rgba16float, write>;
28
+ @group(0) @binding(8) var directOut: texture_storage_2d<rgba16float, write>;
29
+ @group(0) @binding(9) var curPosOut: texture_storage_2d<rgba32float, write>;
30
+ @group(0) @binding(10) var curNormOut: texture_storage_2d<rgba16float, write>;
31
+ @group(0) @binding(11) var albedoOut: texture_storage_2d<rgba16float, write>;
32
+ @group(0) @binding(12) var rawIndOut: texture_storage_2d<rgba16float, write>;
33
+ @group(0) @binding(13) var<uniform> u: PTUniforms;
34
+ @group(0) @binding(14) var<storage, read> vAttr: array<vec4<f32>>;
35
+ @group(0) @binding(15) var<storage, read> indices: array<u32>;
36
+ @group(0) @binding(16) var<storage, read> triMatIds: array<u32>;
37
+ @group(0) @binding(17) var<storage, read> matData: array<vec4<f32>>;
38
+ @group(0) @binding(18) var albedoArr: texture_2d_array<f32>;
39
+ @group(0) @binding(19) var normalArr: texture_2d_array<f32>;
40
+ @group(0) @binding(20) var mrArr: texture_2d_array<f32>;
41
+ @group(0) @binding(21) var texSamp: sampler;
42
+
43
+ const PI: f32 = 3.14159265359;
44
+ fn luma(c: vec3<f32>) -> f32 { return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722)); }`;
45
+ }
46
+
47
+ function ptSamplingAndBrdf() {
48
+ return `
49
+ fn ign(px: vec2<f32>) -> f32 {
50
+ return fract(52.9829189 * fract(dot(px, vec2<f32>(0.06711056, 0.00583715))));
51
+ }
52
+ fn r2Sample(px: vec2<f32>, frame: u32, dim: u32) -> vec2<f32> {
53
+ let n = f32((frame * 5u + dim) & 1023u) + 1.0;
54
+ let off = vec2<f32>(ign(px + f32(dim) * 17.0), ign(px.yx + f32(dim) * 31.0));
55
+ return fract(off + n * vec2<f32>(0.7548776662, 0.5698402910));
56
+ }
57
+ fn skyRadiance(dir: vec3<f32>, sunDir: vec3<f32>, includeSunDisk: bool) -> vec3<f32> {
58
+ let up = clamp(dir.y, 0.0, 1.0);
59
+ let rayleigh = mix(vec3<f32>(0.65, 0.77, 0.96), vec3<f32>(0.12, 0.34, 0.78), pow(up, 0.52));
60
+ let sunCos = max(dot(dir, sunDir), 0.0);
61
+ let mie = vec3<f32>(1.0, 0.88, 0.68) * (pow(sunCos, 8.0) * 0.25 + pow(sunCos, 48.0) * 0.35);
62
+ var sky = (rayleigh + mie) * 1.85;
63
+ if (includeSunDisk) { sky += vec3<f32>(1.0, 0.97, 0.88) * smoothstep(0.9965, 0.9995, sunCos) * 16.0; }
64
+ return sky;
65
+ }
66
+ fn buildBasis(n: vec3<f32>) -> mat3x3<f32> {
67
+ let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n.y) > 0.9);
68
+ let t = normalize(cross(up, n));
69
+ return mat3x3<f32>(t, cross(n, t), n);
70
+ }
71
+ fn sampleCosineHemisphere(n: vec3<f32>, r: vec2<f32>) -> vec3<f32> {
72
+ let phi = 2.0 * PI * r.x;
73
+ let cosT = sqrt(1.0 - r.y);
74
+ let sinT = sqrt(r.y);
75
+ let basis = buildBasis(n);
76
+ return normalize(basis[0] * (cos(phi) * sinT) + basis[1] * (sin(phi) * sinT) + basis[2] * cosT);
77
+ }
78
+ fn sampleGGXVNDF(n: vec3<f32>, vWorld: vec3<f32>, rough: f32, r: vec2<f32>) -> vec3<f32> {
79
+ let a = max(rough * rough, 0.004);
80
+ let basis = buildBasis(n);
81
+ let Ve = vec3<f32>(dot(vWorld, basis[0]), dot(vWorld, basis[1]), max(dot(vWorld, basis[2]), 0.001));
82
+ let Vh = normalize(vec3<f32>(a * Ve.x, a * Ve.y, Ve.z));
83
+ let lensq = Vh.x * Vh.x + Vh.y * Vh.y;
84
+ let T1 = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(-Vh.y, Vh.x, 0.0) * inverseSqrt(lensq), lensq > 1e-7);
85
+ let T2 = cross(Vh, T1);
86
+ let rad = sqrt(r.x);
87
+ let phi = 2.0 * PI * r.y;
88
+ let t1 = rad * cos(phi);
89
+ var t2 = rad * sin(phi);
90
+ let s = 0.5 * (1.0 + Vh.z);
91
+ t2 = (1.0 - s) * sqrt(max(0.0, 1.0 - t1 * t1)) + s * t2;
92
+ let Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
93
+ let Ne = normalize(vec3<f32>(a * Nh.x, a * Nh.y, max(0.0, Nh.z)));
94
+ return normalize(basis[0] * Ne.x + basis[1] * Ne.y + basis[2] * Ne.z);
95
+ }
96
+ fn fresnelSchlick(cosTheta: f32, f0: vec3<f32>) -> vec3<f32> {
97
+ return f0 + (1.0 - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
98
+ }
99
+ fn evalGGXDirect(n: vec3<f32>, v: vec3<f32>, l: vec3<f32>, rough: f32, f0: vec3<f32>) -> vec3<f32> {
100
+ let h = normalize(v + l);
101
+ let ndh = max(dot(n, h), 0.0);
102
+ let ndv = max(dot(n, v), 0.001);
103
+ let ndl = max(dot(n, l), 0.001);
104
+ let a = max(rough * rough, 0.004);
105
+ let a2 = a * a;
106
+ let denom = ndh * ndh * (a2 - 1.0) + 1.0;
107
+ let D = a2 / (PI * denom * denom + 1e-6);
108
+ let k = (rough + 1.0) * (rough + 1.0) * 0.125;
109
+ let gV = ndv / (ndv * (1.0 - k) + k);
110
+ let gL = ndl / (ndl * (1.0 - k) + k);
111
+ let F = fresnelSchlick(max(dot(h, v), 0.0), f0);
112
+ return (D * gV * gL * F) / (4.0 * ndv * ndl + 1e-4);
113
+ }`;
114
+ }
115
+
116
+ function ptShadowAndHalton() {
117
+ return `
118
+ fn traceSunShadow(orig: vec3<f32>, dir: vec3<f32>) -> bool {
119
+ var sqFast: ray_query;
120
+ rayQueryInitialize(&sqFast, scene, RayDesc(5u, 0xFFu, 0.005, 100.0, orig, dir));
121
+ while (rayQueryProceed(&sqFast)) {}
122
+ let sh0 = rayQueryGetCommittedIntersection(&sqFast);
123
+ if (sh0.kind == 0u) { return false; }
124
+ let m0 = triMatIds[sh0.primitive_index];
125
+ if (matData[m0 * 2u].w <= 0.0) { return true; }
126
+
127
+ var sOrig = orig;
128
+ for (var sSkip: u32 = 0u; sSkip < 4u; sSkip++) {
129
+ var sq: ray_query;
130
+ rayQueryInitialize(&sq, scene, RayDesc(1u, 0xFFu, 0.004, 100.0, sOrig, dir));
131
+ while (rayQueryProceed(&sq)) {}
132
+ let sh = rayQueryGetCommittedIntersection(&sq);
133
+ if (sh.kind == 0u) { return false; }
134
+ let sMat = triMatIds[sh.primitive_index];
135
+ let sCut = matData[sMat * 2u].w;
136
+ if (sCut > 0.0) {
137
+ let si0 = indices[sh.primitive_index * 3u + 0u];
138
+ let si1 = indices[sh.primitive_index * 3u + 1u];
139
+ let si2 = indices[sh.primitive_index * 3u + 2u];
140
+ let sb = sh.barycentrics;
141
+ let sw0 = 1.0 - sb.x - sb.y;
142
+ let sUv = vec2<f32>(
143
+ vAttr[si0 * 3u].w * sw0 + vAttr[si1 * 3u].w * sb.x + vAttr[si2 * 3u].w * sb.y,
144
+ vAttr[si0 * 3u + 2u].x * sw0 + vAttr[si1 * 3u + 2u].x * sb.x + vAttr[si2 * 3u + 2u].x * sb.y
145
+ );
146
+ if (textureSampleLevel(albedoArr, texSamp, sUv, i32(sMat), 0.0).a < sCut) {
147
+ sOrig = sOrig + dir * (sh.t + 0.003);
148
+ continue;
149
+ }
150
+ }
151
+ return true;
152
+ }
153
+ return true;
154
+ }
155
+
156
+ fn halton(idx: u32, base: u32) -> f32 {
157
+ var f = 1.0;
158
+ var r = 0.0;
159
+ var i = idx;
160
+ for (var k: u32 = 0u; k < 6u; k++) {
161
+ if (i == 0u) { break; }
162
+ f = f / f32(base);
163
+ r = r + f * f32(i % base);
164
+ i = i / base;
165
+ }
166
+ return r;
167
+ }`;
168
+ }
169
+
170
+ function ptMainPreamble() {
171
+ return `
172
+ @compute @workgroup_size(8, 8)
173
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
174
+ let W = u32(u.params.x);
175
+ let H = u32(u.params.y);
176
+ if (gid.x >= W || gid.y >= H) { return; }
177
+
178
+ let px = vec2<f32>(f32(gid.x), f32(gid.y));
179
+ let isMoving = u.cfg.x != 0u;
180
+ let lightChanged = u.cfg.w != 0u;
181
+ let frameIdx = u.cfg.z;
182
+ let hIdx = (frameIdx & 15u) + 1u;
183
+ let jSub = vec2<f32>(halton(hIdx, 2u), halton(hIdx, 3u));
184
+ let uv = ((px + jSub) / vec2<f32>(u.params.x, u.params.y)) * 2.0 - 1.0;
185
+ let aspect = u.params.x / u.params.y;
186
+ let fov = u.params.w;
187
+
188
+ var rayOrigin = u.camPos.xyz;
189
+ var rayDir = normalize(u.camFwd.xyz + u.camRight.xyz * (uv.x * aspect * fov) - u.camUp.xyz * (uv.y * fov));
190
+ let sunDir = normalize(u.sunDir.xyz);
191
+ let sunCol = vec3<f32>(1.0, 0.93, 0.80) * u.sunDir.w;
192
+ let maxBounces = u.cfg.y;
193
+
194
+ var directLight = vec3<f32>(0.0);
195
+ var indirectLight = vec3<f32>(0.0);
196
+ var throughput = vec3<f32>(1.0);
197
+ var primaryAlbedo = vec3<f32>(1.0);
198
+ var primaryPos = vec3<f32>(0.0);
199
+ var primaryN = vec3<f32>(0.0, 1.0, 0.0);
200
+ var primaryRough = 0.8;
201
+ var primaryDepth = 100.0;
202
+ var isSky = 0.0;
203
+ var hitSky = false;
204
+ var rawContactAO = 1.0;
205
+
206
+ for (var bounce: u32 = 0u; bounce < 4u; bounce++) {
207
+ if (bounce >= maxBounces) { break; }`;
208
+ }
209
+
210
+ function ptTraceAlphaLoop() {
211
+ return `
212
+ var hit: RayIntersection;
213
+ var hitPos = vec3<f32>(0.0);
214
+ var matId = 0u;
215
+ var geomN = vec3<f32>(0.0, 1.0, 0.0);
216
+ var shadeN = vec3<f32>(0.0, 1.0, 0.0);
217
+ var texSample = vec4<f32>(1.0);
218
+ var texUv = vec2<f32>(0.0);
219
+ var gotHit = false;
220
+ var curOrig = rayOrigin;
221
+ var totalT = 0.0;
222
+
223
+ let maxSkip = select(6u, 16u, bounce == 0u);
224
+ for (var aSkip: u32 = 0u; aSkip < maxSkip; aSkip++) {
225
+ var rq: ray_query;
226
+ rayQueryInitialize(&rq, scene, RayDesc(1u, 0xFFu, 0.003, 150.0 - totalT, curOrig, rayDir));
227
+ while (rayQueryProceed(&rq)) {}
228
+ hit = rayQueryGetCommittedIntersection(&rq);
229
+ if (hit.kind == 0u) { break; }
230
+
231
+ hitPos = curOrig + rayDir * hit.t;
232
+ totalT += hit.t;
233
+ let gTri = hit.primitive_index;
234
+ matId = triMatIds[gTri];
235
+ let i0 = indices[gTri * 3u + 0u];
236
+ let i1 = indices[gTri * 3u + 1u];
237
+ let i2 = indices[gTri * 3u + 2u];
238
+ let n0 = vAttr[i0 * 3u]; let t0 = vAttr[i0 * 3u + 1u]; let v0 = vAttr[i0 * 3u + 2u];
239
+ let n1 = vAttr[i1 * 3u]; let t1 = vAttr[i1 * 3u + 1u]; let v1 = vAttr[i1 * 3u + 2u];
240
+ let n2 = vAttr[i2 * 3u]; let t2 = vAttr[i2 * 3u + 1u]; let v2 = vAttr[i2 * 3u + 2u];
241
+ let bary = hit.barycentrics;
242
+ let w0 = 1.0 - bary.x - bary.y;
243
+ texUv = vec2<f32>(n0.w * w0 + n1.w * bary.x + n2.w * bary.y, v0.x * w0 + v1.x * bary.x + v2.x * bary.y);
244
+ texSample = textureSampleLevel(albedoArr, texSamp, texUv, i32(matId), 0.0);
245
+ let cutoff = matData[matId * 2u].w;
246
+ if (cutoff > 0.0 && texSample.a < cutoff && aSkip + 1u < maxSkip) {
247
+ curOrig = hitPos + rayDir * 0.002;
248
+ continue;
249
+ }
250
+ geomN = normalize(n0.xyz * w0 + n1.xyz * bary.x + n2.xyz * bary.y);
251
+ if (dot(geomN, rayDir) > 0.0) { geomN = -geomN; }
252
+ shadeN = geomN;
253
+ let pbrFlags = matData[matId * 2u + 1u];
254
+ if (bounce == 0u && pbrFlags.z > 0.5) {
255
+ let tan4 = t0 * w0 + t1 * bary.x + t2 * bary.y;
256
+ let T = normalize(tan4.xyz - geomN * dot(geomN, tan4.xyz));
257
+ let B = cross(geomN, T) * select(-1.0, 1.0, tan4.w >= 0.0);
258
+ let tsN = textureSampleLevel(normalArr, texSamp, texUv, i32(matId), 0.0).xyz * 2.0 - 1.0;
259
+ let mappedN = normalize(T * tsN.x + B * tsN.y + geomN * max(tsN.z, 0.25));
260
+ if (dot(mappedN, -rayDir) > 0.01) { shadeN = mappedN; }
261
+ }
262
+ gotHit = true;
263
+ break;
264
+ }`;
265
+ }
266
+
267
+ function ptMainLoopPart2() {
268
+ return `
269
+ if (!gotHit) {
270
+ let sky = skyRadiance(rayDir, sunDir, bounce == 0u);
271
+ if (bounce == 0u) { primaryAlbedo = sky; directLight = vec3<f32>(1.0); isSky = 1.0; }
272
+ else { indirectLight += throughput * sky; }
273
+ hitSky = true;
274
+ break;
275
+ }
276
+
277
+ let mBase = matData[matId * 2u];
278
+ let mPbr = matData[matId * 2u + 1u];
279
+ let albedo = max(texSample.rgb * mBase.rgb, vec3<f32>(0.03));
280
+ let mrSample = textureSampleLevel(mrArr, texSamp, texUv, i32(matId), 0.0);
281
+ let rough = clamp(mrSample.g * mPbr.y, 0.08, 1.0);
282
+ let metal = clamp(mrSample.b * mPbr.x, 0.0, 1.0);
283
+ let f0 = mix(vec3<f32>(0.04), albedo, metal);
284
+ let V = -rayDir;
285
+
286
+ if (bounce == 0u) {
287
+ primaryAlbedo = albedo; primaryPos = hitPos; primaryN = shadeN;
288
+ primaryRough = rough; primaryDepth = totalT;
289
+ }
290
+
291
+ let rSun = r2Sample(px, frameIdx, bounce * 2u);
292
+ let sunBasis = buildBasis(sunDir);
293
+ let sAng = 2.0 * PI * rSun.x;
294
+ let sRad = sqrt(rSun.y) * 0.022;
295
+ let jitterSun = normalize(sunDir + (sunBasis[0] * cos(sAng) + sunBasis[1] * sin(sAng)) * sRad);
296
+ let ndl = max(dot(shadeN, jitterSun), 0.0);
297
+ if (ndl > 0.0 && !traceSunShadow(hitPos + geomN * 0.008, jitterSun)) {
298
+ if (bounce == 0u) {
299
+ let spec = evalGGXDirect(shadeN, V, jitterSun, rough, f0);
300
+ let kD = (1.0 - metal) * (1.0 / PI);
301
+ let specDemod = spec / max(albedo, vec3<f32>(0.08));
302
+ directLight += (vec3<f32>(kD) + min(specDemod, vec3<f32>(4.0))) * ndl * sunCol;
303
+ } else {
304
+ indirectLight += min(throughput * albedo * (ndl / PI) * sunCol, vec3<f32>(2.5));
305
+ }
306
+ }
307
+
308
+ if (bounce == 0u) {
309
+ let rAo = r2Sample(px, frameIdx, 9u);
310
+ let aoDir = sampleCosineHemisphere(shadeN, rAo);
311
+ if (dot(aoDir, geomN) > 0.01) {
312
+ var aq: ray_query;
313
+ rayQueryInitialize(&aq, scene, RayDesc(5u, 0xFFu, 0.012, 0.85, hitPos + geomN * 0.008, aoDir));
314
+ while (rayQueryProceed(&aq)) {}
315
+ if (rayQueryGetCommittedIntersection(&aq).kind != 0u) { rawContactAO = 0.0; }
316
+ }
317
+ }
318
+
319
+ let rBounce = r2Sample(px, frameIdx, bounce * 2u + 1u);
320
+ let Fv = fresnelSchlick(max(dot(shadeN, V), 0.0), f0);
321
+ let specProb = clamp(mix(luma(Fv), 0.85, metal) * (1.0 - rough * 0.65), 0.0, 0.85);
322
+ if ((bounce == 0u) && (rough < 0.45) && (rBounce.x < specProb)) {
323
+ let rGgx = vec2<f32>(rBounce.x / max(specProb, 0.01), rBounce.y);
324
+ let Hvec = sampleGGXVNDF(shadeN, V, rough, rGgx);
325
+ let Ldir = reflect(rayDir, Hvec);
326
+ if (dot(Ldir, geomN) > 0.01) {
327
+ rayDir = normalize(Ldir);
328
+ let ndlSpec = max(dot(shadeN, rayDir), 0.001);
329
+ let a2 = max(rough * rough, 0.004);
330
+ let g1L = (2.0 * ndlSpec) / (ndlSpec + sqrt(a2 * a2 + (1.0 - a2 * a2) * ndlSpec * ndlSpec));
331
+ let Fh = fresnelSchlick(max(dot(Hvec, V), 0.0), f0);
332
+ throughput *= mix(vec3<f32>(1.0), albedo, metal) * (Fh * g1L / max(specProb, 0.05));
333
+ } else {
334
+ rayDir = sampleCosineHemisphere(shadeN, rBounce);
335
+ if (bounce > 0u) { throughput *= albedo; }
336
+ }
337
+ } else {
338
+ rayDir = sampleCosineHemisphere(shadeN, rBounce);
339
+ if (dot(rayDir, geomN) <= 0.01) { rayDir = sampleCosineHemisphere(geomN, rBounce); }
340
+ if (bounce > 0u) { throughput *= albedo * (1.0 - metal * 0.8); }
341
+ }
342
+ if (max(throughput.x, max(throughput.y, throughput.z)) < 0.02) { break; }
343
+ rayOrigin = hitPos + geomN * 0.01;
344
+ }`;
345
+ }
346
+
347
+ function ptReprojectTail() {
348
+ return `
349
+ if (isSky < 0.5 && !hitSky) { indirectLight += throughput * vec3<f32>(0.06, 0.07, 0.10); }
350
+ let rawInd = min(indirectLight, vec3<f32>(4.0));
351
+ let rawDir = min(directLight, vec3<f32>(8.0));
352
+ let curL = luma(rawInd);
353
+ var outIllum = rawInd;
354
+ var outDir = rawDir;
355
+ var outAO = rawContactAO;
356
+ var outMoments = vec2<f32>(curL, curL * curL);
357
+ var histLen = 1.0;
358
+
359
+ if (isSky < 0.5 && !lightChanged && frameIdx > 0u) {
360
+ let vPrev = primaryPos - u.prevCamPos.xyz;
361
+ let zPrev = dot(vPrev, u.prevCamFwd.xyz);
362
+ if (zPrev > 0.02) {
363
+ let xPrev = dot(vPrev, u.prevCamRight.xyz) / (zPrev * aspect * fov);
364
+ let yPrev = -dot(vPrev, u.prevCamUp.xyz) / (zPrev * fov);
365
+ let prevUv = vec2<f32>(xPrev, yPrev) * 0.5 + 0.5;
366
+ if (prevUv.x >= 0.0 && prevUv.x < 1.0 && prevUv.y >= 0.0 && prevUv.y < 1.0) {
367
+ let fPos = prevUv * vec2<f32>(u.params.x, u.params.y) - 0.5;
368
+ let base = vec2<i32>(floor(fPos));
369
+ let frac = fract(fPos);
370
+ var indSum = vec3<f32>(0.0);
371
+ var dirSum = vec3<f32>(0.0);
372
+ var aoSum = 0.0;
373
+ var momSum = vec2<f32>(0.0);
374
+ var hSum = 0.0;
375
+ var wSum = 0.0;
376
+ let posThresh = max(0.08, primaryDepth * 0.05);
377
+ let normThresh = mix(0.86, 0.72, clamp(primaryDepth / 20.0, 0.0, 1.0));
378
+ for (var dy: i32 = 0; dy <= 1; dy++) {
379
+ for (var dx: i32 = 0; dx <= 1; dx++) {
380
+ let q = clamp(base + vec2<i32>(dx, dy), vec2<i32>(0, 0), vec2<i32>(i32(W) - 1, i32(H) - 1));
381
+ let pp = textureLoad(prevPosT, q, 0);
382
+ let pn = textureLoad(prevNormT, q, 0).xyz;
383
+ if (pp.w < 90.0 && dot(primaryN, pn) > normThresh && length(primaryPos - pp.xyz) < posThresh) {
384
+ let bw = select(1.0 - frac.x, frac.x, dx == 1) * select(1.0 - frac.y, frac.y, dy == 1);
385
+ indSum += textureLoad(prevHistIllumT, q, 0).rgb * bw;
386
+ let pd4 = textureLoad(prevDirectT, q, 0);
387
+ dirSum += pd4.rgb * bw;
388
+ aoSum += pd4.a * bw;
389
+ let pm = textureLoad(prevMomentsT, q, 0);
390
+ momSum += pm.xy * bw;
391
+ hSum += pm.z * bw;
392
+ wSum += bw;
393
+ }
394
+ }
395
+ }
396
+ if (wSum > 0.05) {
397
+ histLen = min((hSum / wSum) + 1.0, select(256.0, 32.0, isMoving));
398
+ let alpha = max(select(0.004, 0.06, isMoving), 1.0 / histLen);
399
+ let alphaMom = max(0.2, 1.0 / histLen);
400
+ outIllum = mix(indSum / wSum, rawInd, alpha);
401
+ outMoments = mix(momSum / wSum, vec2<f32>(curL, curL * curL), alphaMom);
402
+ outDir = mix(dirSum / wSum, rawDir, max(select(0.008, 0.14, isMoving), 1.0 / histLen));
403
+ outAO = mix(aoSum / wSum, rawContactAO, max(select(0.008, 0.08, isMoving), 1.0 / histLen));
404
+ }
405
+ }
406
+ }
407
+ }
408
+
409
+ let variance = max(0.0, outMoments.y - outMoments.x * outMoments.x);
410
+ let ip = vec2<i32>(i32(gid.x), i32(gid.y));
411
+ textureStore(reprojectOut, ip, vec4<f32>(outIllum, variance));
412
+ textureStore(momentsOut, ip, vec4<f32>(outMoments, histLen, 0.0));
413
+ textureStore(directOut, ip, vec4<f32>(outDir, outAO));
414
+ textureStore(curPosOut, ip, vec4<f32>(primaryPos, primaryDepth));
415
+ textureStore(curNormOut, ip, vec4<f32>(primaryN, primaryRough));
416
+ textureStore(albedoOut, ip, vec4<f32>(primaryAlbedo, isSky));
417
+ textureStore(rawIndOut, ip, vec4<f32>(rawInd, 1.0));
418
+ }`;
419
+ }
420
+
421
+ export function createPathTraceWgsl() {
422
+ return [
423
+ ptHeaderAndBindings(),
424
+ ptSamplingAndBrdf(),
425
+ ptShadowAndHalton(),
426
+ ptMainPreamble(),
427
+ ptTraceAlphaLoop(),
428
+ ptMainLoopPart2(),
429
+ ptReprojectTail(),
430
+ ].join("\n");
431
+ }