@threenative/three-native 0.3.6 → 0.3.9

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,849 @@
1
+ import type { GpuStage } from "../gpu-stages.js";
2
+
3
+ /**
4
+ * Screen-space reflections for the owned engine, with the call shape of three's `ssr(color, depth,
5
+ * normal, options)` (SSRNode): the engine had no live SSR node, so `three/addons/tsl/display/SSRNode.js`
6
+ * refused by name. This one is authored in TSL over the engine's own functions, so the V8 player and the
7
+ * Wasm web module share it (both hand `defineScreenSpaceReflections` their TSL table).
8
+ *
9
+ * What it computes: per pixel, a view-space ray along the mirror direction, marched in `steps` slices
10
+ * that grow with distance (a quadratic spacing, so near hits are dense), tested against the depth
11
+ * buffer, refined by bisection. A hit samples the lit colour at the hit pixel. The returned colour is
12
+ * a **delta to add to the lit frame**: for a metal it replaces the frame's own environment reflection
13
+ * with the traced one (`hit - base`), for a dielectric it adds the Fresnel-weighted reflection. A ray
14
+ * that finds nothing on screen adds nothing, so the environment reflection stays: the same tiering
15
+ * Unreal's Lumen reflections use, screen traces first and the captured sky for what they miss
16
+ * (Engine/Source/Runtime/Renderer/Private/Lumen/LumenReflections.cpp). Roughness never gates here;
17
+ * the game scales the result by its own roughness cut-off, since where a reflection fades is a look.
18
+ */
19
+
20
+ /** A TSL node: every method three's node classes carry, built by the engine's table. */
21
+ // quality-allow: three's TSL node surface is open-ended chained calls; the engine table returns them untyped.
22
+ // biome-ignore lint/suspicious/noExplicitAny: three's TSL node surface is open-ended chained calls.
23
+ export type TslNode = any;
24
+
25
+ /** The engine TSL functions and inputs the effect composes. */
26
+ export interface IScreenSpaceTsl {
27
+ // quality-allow: the engine TSL table must match three's own function name
28
+ // biome-ignore lint/style/useNamingConvention: three's TSL function name.
29
+ readonly Break: () => void;
30
+ // quality-allow: the engine TSL table must match three's own function name
31
+ // biome-ignore lint/style/useNamingConvention: three's TSL function name.
32
+ readonly Fn: (body: () => TslNode) => () => TslNode;
33
+ // quality-allow: the engine TSL table must match three's own function name
34
+ // biome-ignore lint/style/useNamingConvention: three's TSL function name.
35
+ readonly If: (condition: TslNode, body: () => void) => { Else(body: () => void): void };
36
+ // quality-allow: the engine TSL table must match three's own function name
37
+ // biome-ignore lint/style/useNamingConvention: three's TSL function name.
38
+ readonly Loop: (
39
+ options: { start: TslNode; end: TslNode; type: string; condition: string },
40
+ body: (indices: { i: TslNode }) => void,
41
+ ) => void;
42
+ readonly clamp: (value: TslNode, low: TslNode, high: TslNode) => TslNode;
43
+ readonly dot: (a: TslNode, b: TslNode) => TslNode;
44
+ readonly float: (value: TslNode) => TslNode;
45
+ readonly int: (value: number) => TslNode;
46
+ readonly max: (a: TslNode, b: TslNode) => TslNode;
47
+ readonly min: (a: TslNode, b: TslNode) => TslNode;
48
+ readonly mix: (a: TslNode, b: TslNode, t: TslNode) => TslNode;
49
+ readonly normalize: (value: TslNode) => TslNode;
50
+ readonly reflect: (incident: TslNode, normal: TslNode) => TslNode;
51
+ readonly rtt: (
52
+ source: TslNode,
53
+ width: number | null,
54
+ height: number | null,
55
+ options: { type: number; minFilter?: number; magFilter?: number; gpuStage?: GpuStage },
56
+ ) => TslNode;
57
+ readonly smoothstep: (low: TslNode, high: TslNode, value: TslNode) => TslNode;
58
+ readonly uniform: (value: number) => TslNode;
59
+ readonly uv: () => TslNode;
60
+ readonly vec2: (...values: TslNode[]) => TslNode;
61
+ readonly vec3: (...values: TslNode[]) => TslNode;
62
+ readonly vec4: (...values: TslNode[]) => TslNode;
63
+ }
64
+
65
+ /** The perspective camera the frame draws with: the effect reads its projection each render. */
66
+ export interface IScreenSpaceCamera {
67
+ readonly near: number;
68
+ readonly projectionMatrix: { readonly elements: readonly number[] };
69
+ }
70
+
71
+ export interface IScreenSpaceReflectionOptions {
72
+ /**
73
+ * The camera the scene pass draws with. A post effect is drawn through its own full-screen quad, so
74
+ * the engine's `cameraProjectionMatrix` there is the quad's orthographic camera, not the scene's:
75
+ * every view/screen mapping built on it is wrong and no ray ever hits (three's SSRNode reads the
76
+ * scene camera through a reference uniform for the same reason).
77
+ */
78
+ readonly camera: IScreenSpaceCamera;
79
+ /** Per-pixel metalness. Missing means every surface is a dielectric. */
80
+ readonly metalnessNode?: TslNode;
81
+ /** Per-pixel roughness. Missing means every surface is a mirror. It blurs the sampled hit. */
82
+ readonly roughnessNode?: TslNode;
83
+ /** `false` skips dielectrics, as three's SSR does by default. */
84
+ readonly reflectNonMetals?: boolean;
85
+ }
86
+
87
+ const HALF_FLOAT_TYPE = 1016;
88
+ /** The passes of the screen-space gather report their GPU time under this stage (gpu-stages.ts). */
89
+ const GI_STAGE: GpuStage = "SSGI";
90
+ /**
91
+ * The most ray slices per pixel. `maxSteps` lowers it per quality tier, as Unreal caps its march
92
+ * (UE 5.8.3: Engine/Shaders/Private/SSRT/SSRTReflections.usf:198-216); `maxDistance` scales how far they reach.
93
+ */
94
+ const STEPS = 48;
95
+ /** Bisection steps that sharpen a detected crossing. */
96
+ const REFINEMENTS = 5;
97
+ /** Largest radiance a hit may carry, so one sun-lit highlight cannot paint a whole reflection. */
98
+ const MAX_LUMINANCE = 10;
99
+
100
+ /**
101
+ * The view <-> screen mapping of the scene camera, as TSL over uniforms refreshed every render. A post
102
+ * effect is drawn through its own quad, so the engine's own camera nodes there are the quad's.
103
+ */
104
+ function defineCameraMapping(
105
+ tsl: IScreenSpaceTsl,
106
+ camera: IScreenSpaceCamera | undefined,
107
+ owner: string,
108
+ ) {
109
+ const { float, uniform, vec2, vec3 } = tsl;
110
+ // The projection terms a view <-> screen mapping of a perspective camera needs, read from the scene
111
+ // camera before every render: column k of P (P * e_k) is e[4k..4k+3] of its column-major elements.
112
+ // Depth is (A z + B) / -z, so z = -B / (depth + A).
113
+ if (camera?.projectionMatrix === undefined)
114
+ throw new TypeError(
115
+ `TN_NATIVE_${owner.toUpperCase()}_CAMERA: ${owner} needs options.camera, the camera the scene pass draws with`,
116
+ );
117
+ const live = (read: () => number): TslNode => uniform(read()).onRenderUpdate(read);
118
+ const term = (index: number): TslNode => live(() => camera.projectionMatrix.elements[index] ?? 0);
119
+ const cameraNear = live(() => camera.near);
120
+ const column0 = { x: term(0) };
121
+ const column1 = { y: term(5) };
122
+ const column2 = { x: term(8), y: term(9), z: term(10) };
123
+ const column3 = { z: term(14) };
124
+ const viewZ = (depth: TslNode): TslNode => column3.z.negate().div(depth.add(column2.z));
125
+ const viewPosition = (coordinate: TslNode, depth: TslNode): TslNode => {
126
+ const z = viewZ(depth);
127
+ const ndcX = coordinate.x.mul(2).sub(1);
128
+ const ndcY = float(1).sub(coordinate.y).mul(2).sub(1);
129
+ return vec3(
130
+ z.negate().mul(ndcX.add(column2.x)).div(column0.x),
131
+ z.negate().mul(ndcY.add(column2.y)).div(column1.y),
132
+ z,
133
+ );
134
+ };
135
+ const project = (position: TslNode): TslNode => {
136
+ const w = position.z.negate();
137
+ const ndcX = position.x.mul(column0.x).add(position.z.mul(column2.x)).div(w);
138
+ const ndcY = position.y.mul(column1.y).add(position.z.mul(column2.y)).div(w);
139
+ return vec2(ndcX.mul(0.5).add(0.5), float(0.5).sub(ndcY.mul(0.5)));
140
+ };
141
+ return { cameraNear, viewZ, viewPosition, project };
142
+ }
143
+
144
+ export function defineScreenSpaceReflections(tsl: IScreenSpaceTsl) {
145
+ return function ssr(
146
+ colorNode: TslNode,
147
+ depthNode: TslNode,
148
+ normalNode: TslNode,
149
+ options: IScreenSpaceReflectionOptions,
150
+ ): TslNode {
151
+ // Read here, not at definition: the camera inputs are lazy engine nodes.
152
+ const { Break, Fn, If, Loop, clamp, dot, float, int } = tsl;
153
+ const { max, min, mix, normalize, reflect, rtt, smoothstep, uniform, uv, vec2, vec3, vec4 } =
154
+ tsl;
155
+ const maxDistance = uniform(1);
156
+ const thickness = uniform(0.1);
157
+ const intensity = uniform(1);
158
+ const screenEdgeFade = uniform(0.2);
159
+ const maxSteps = uniform(STEPS);
160
+ // Unreal traces no ray above its roughness cut-off (UE 5.8.3: Engine/Source/Runtime/Engine/Private/Scene.cpp:658,
161
+ // MaxRoughness 0.4). A caller whose composite weights SSR to 0 there sets this to that cut-off and skips the march.
162
+ const maxRoughness = uniform(1);
163
+ const roughness = options.roughnessNode ?? float(0);
164
+ const metalness = options.metalnessNode ?? float(0);
165
+
166
+ const { cameraNear, viewZ, viewPosition, project } = defineCameraMapping(
167
+ tsl,
168
+ options.camera,
169
+ "ssr",
170
+ );
171
+
172
+ const graph = Fn(() => {
173
+ const coordinate = uv();
174
+ const result = vec4(0, 0, 0, 0).toVar();
175
+ const centreDepth = depthNode.sample(coordinate).r;
176
+ If(centreDepth.lessThan(1).and(roughness.lessThan(maxRoughness)), () => {
177
+ const position = viewPosition(coordinate, centreDepth);
178
+ const normal = normalize(normalNode.sample(coordinate).xyz);
179
+ const incident = normalize(position);
180
+ const direction = normalize(reflect(incident, normal));
181
+ // Start off the surface, by more the farther it is: depth precision falls with distance.
182
+ const origin = position.add(normal.mul(max(0.01, position.z.negate().mul(0.004))));
183
+
184
+ const hitCoordinate = vec2(0, 0).toVar();
185
+ const hitDistance = float(-1).toVar();
186
+ const previous = float(0).toVar();
187
+ // The sample before: a hit is a crossing from in front of the depth buffer to behind it, and the
188
+ // buffer's own depth change between the two samples is slack (a floor seen at a grazing angle drops
189
+ // away faster along the ray than any fixed thickness covers; a depth jump is an edge, not slack).
190
+ const previousBehind = float(-1).toVar();
191
+ const previousSceneZ = position.z.toVar();
192
+ Loop({ start: int(0), end: int(STEPS), type: "int", condition: "<" }, ({ i }) => {
193
+ If(float(i).greaterThanEqual(maxSteps), () => {
194
+ Break();
195
+ });
196
+ const fraction = float(i).add(1).div(min(maxSteps, STEPS));
197
+ const travelled = maxDistance.mul(fraction.mul(fraction));
198
+ const point = origin.add(direction.mul(travelled));
199
+ If(point.z.greaterThan(cameraNear.negate()), () => {
200
+ Break();
201
+ });
202
+ const screen = project(point);
203
+ If(
204
+ screen.x
205
+ .lessThan(0)
206
+ .or(screen.x.greaterThan(1))
207
+ .or(screen.y.lessThan(0))
208
+ .or(screen.y.greaterThan(1)),
209
+ () => {
210
+ Break();
211
+ },
212
+ );
213
+ const sceneDepth = depthNode.sample(screen).r;
214
+ // Positive: the ray is behind the surface the depth buffer holds at that pixel.
215
+ const sceneZ = viewZ(sceneDepth);
216
+ const behind = sceneZ.sub(point.z);
217
+ const slice = travelled.sub(previous);
218
+ const drop = sceneZ.sub(previousSceneZ).abs();
219
+ const slack = drop.lessThan(sceneZ.abs().mul(0.15)).select(drop, float(0));
220
+ If(
221
+ sceneDepth
222
+ .lessThan(1)
223
+ .and(behind.greaterThan(0))
224
+ .and(previousBehind.lessThanEqual(0))
225
+ .and(behind.lessThan(thickness.add(slice.mul(direction.z.abs())).add(slack))),
226
+ () => {
227
+ // Bisect the slice [previous, travelled] to put the hit on the surface.
228
+ const low = previous.toVar();
229
+ const high = travelled.toVar();
230
+ Loop({ start: int(0), end: int(REFINEMENTS), type: "int", condition: "<" }, () => {
231
+ const middle = low.add(high).mul(0.5);
232
+ const middleScreen = project(origin.add(direction.mul(middle)));
233
+ const middleDepth = viewZ(depthNode.sample(middleScreen).r).sub(
234
+ origin.add(direction.mul(middle)).z,
235
+ );
236
+ If(middleDepth.greaterThan(0), () => {
237
+ high.assign(middle);
238
+ }).Else(() => {
239
+ low.assign(middle);
240
+ });
241
+ });
242
+ hitDistance.assign(high);
243
+ hitCoordinate.assign(project(origin.add(direction.mul(high))));
244
+ Break();
245
+ },
246
+ );
247
+ previous.assign(travelled);
248
+ previousBehind.assign(behind);
249
+ previousSceneZ.assign(sceneZ);
250
+ });
251
+
252
+ If(hitDistance.greaterThanEqual(0), () => {
253
+ // A rougher surface smears the hit: a cross of taps whose reach grows with roughness.
254
+ const reach = roughness.mul(0.03);
255
+ const tap = (offset: TslNode): TslNode => colorNode.sample(hitCoordinate.add(offset)).rgb;
256
+ const hit = tap(vec2(0, 0))
257
+ .add(tap(vec2(reach, 0)))
258
+ .add(tap(vec2(reach.negate(), 0)))
259
+ .add(tap(vec2(0, reach)))
260
+ .add(tap(vec2(0, reach.negate())))
261
+ .mul(0.2)
262
+ .min(vec3(MAX_LUMINANCE, MAX_LUMINANCE, MAX_LUMINANCE));
263
+ // A surface that faces away from the ray was reached through its back: no reflection.
264
+ const hitNormal = normalize(normalNode.sample(hitCoordinate).xyz);
265
+ const facing = smoothstep(0.25, -0.05, dot(hitNormal, direction));
266
+ const edge = min(
267
+ min(
268
+ smoothstep(0, screenEdgeFade, hitCoordinate.x),
269
+ smoothstep(0, screenEdgeFade, float(1).sub(hitCoordinate.x)),
270
+ ),
271
+ min(
272
+ smoothstep(0, screenEdgeFade, hitCoordinate.y),
273
+ smoothstep(0, screenEdgeFade, float(1).sub(hitCoordinate.y)),
274
+ ),
275
+ );
276
+ const reach01 = hitDistance.div(maxDistance);
277
+ const distance = float(1).sub(smoothstep(0.5, 1, reach01));
278
+ const weight = facing.mul(edge).mul(distance).mul(intensity);
279
+ const facingView = clamp(dot(normal, incident.negate()), 0, 1);
280
+ const fresnel = float(0.04).add(float(0.96).mul(float(1).sub(facingView).pow(5)));
281
+ const base = colorNode.sample(coordinate).rgb;
282
+ const dielectric = hit.mul(fresnel).mul(options.reflectNonMetals === true ? 1 : 0);
283
+ const delta = mix(dielectric, hit.sub(base), clamp(metalness, 0, 1));
284
+ result.assign(vec4(delta.mul(weight), 0));
285
+ });
286
+ });
287
+ return result;
288
+ })();
289
+
290
+ const node = rtt(graph, null, null, { type: HALF_FLOAT_TYPE });
291
+ return Object.defineProperties(node, {
292
+ maxDistance: { value: maxDistance },
293
+ thickness: { value: thickness },
294
+ intensity: { value: intensity },
295
+ screenEdgeFade: { value: screenEdgeFade },
296
+ maxSteps: { value: maxSteps },
297
+ maxRoughness: { value: maxRoughness },
298
+ resolutionScale: {
299
+ get: () => node.getResolutionScale(),
300
+ set: (value: number) => node.setResolutionScale(value),
301
+ },
302
+ });
303
+ };
304
+ }
305
+
306
+ /** The scene the traces read, and the uniforms that shape them. */
307
+ export interface IGiTraceScene {
308
+ readonly colorNode: TslNode;
309
+ readonly depthNode: TslNode;
310
+ readonly normalNode: TslNode;
311
+ readonly mapping: ReturnType<typeof defineCameraMapping>;
312
+ readonly uniforms: {
313
+ readonly radius: TslNode;
314
+ readonly screenEdgeFade: TslNode;
315
+ readonly stepCount: TslNode;
316
+ readonly thickness: TslNode;
317
+ };
318
+ }
319
+
320
+ /**
321
+ * The depth-buffer march and the hit shading both gathers share (`ssgi` per pixel, the screen probes per probe).
322
+ * `march` walks one ray in `stepCount` slices (quadratic spacing out to `radius`) and answers where it crossed the
323
+ * depth buffer; `shade` turns a crossing into the lit colour there and a weight.
324
+ */
325
+ export function defineGiTrace(tsl: IScreenSpaceTsl, scene: IGiTraceScene) {
326
+ const { Break, If, Loop, float, int, max, min, smoothstep, vec2, vec3 } = tsl;
327
+ const { colorNode, depthNode, normalNode } = scene;
328
+ const { cameraNear, viewZ, project } = scene.mapping;
329
+ const { radius, screenEdgeFade, stepCount, thickness } = scene.uniforms;
330
+ const march = (origin: TslNode, direction: TslNode, startZ: TslNode) => {
331
+ const hitCoordinate = vec2(0, 0).toVar();
332
+ const hitDistance = float(-1).toVar();
333
+ const previous = float(0).toVar();
334
+ const previousBehind = float(-1).toVar();
335
+ const previousSceneZ = startZ.toVar();
336
+ Loop({ start: int(0), end: int(GI_MAX_STEPS), type: "int", condition: "<" }, ({ i: step }) => {
337
+ If(float(step).greaterThanEqual(stepCount), () => {
338
+ Break();
339
+ });
340
+ const fraction = float(step).add(1).div(stepCount);
341
+ const travelled = radius.mul(fraction.mul(fraction));
342
+ const point = origin.add(direction.mul(travelled));
343
+ If(point.z.greaterThan(cameraNear.negate()), () => {
344
+ Break();
345
+ });
346
+ const screen = project(point);
347
+ If(
348
+ screen.x
349
+ .lessThan(0)
350
+ .or(screen.x.greaterThan(1))
351
+ .or(screen.y.lessThan(0))
352
+ .or(screen.y.greaterThan(1)),
353
+ () => {
354
+ Break();
355
+ },
356
+ );
357
+ const sceneDepth = depthNode.sample(screen).r;
358
+ const sceneZ = viewZ(sceneDepth);
359
+ const behind = sceneZ.sub(point.z);
360
+ const slice = travelled.sub(previous);
361
+ const drop = sceneZ.sub(previousSceneZ).abs();
362
+ const slack = drop.lessThan(sceneZ.abs().mul(0.15)).select(drop, float(0));
363
+ // Lumen's relative thickness, plus what the slice itself can have crossed.
364
+ const reach = sceneZ.abs().mul(thickness).add(slice.mul(direction.z.abs())).add(slack);
365
+ If(
366
+ sceneDepth
367
+ .lessThan(1)
368
+ .and(behind.greaterThan(0))
369
+ .and(previousBehind.lessThanEqual(0))
370
+ .and(behind.lessThan(reach)),
371
+ () => {
372
+ hitCoordinate.assign(screen);
373
+ hitDistance.assign(travelled);
374
+ Break();
375
+ },
376
+ );
377
+ previous.assign(travelled);
378
+ previousBehind.assign(behind);
379
+ previousSceneZ.assign(sceneZ);
380
+ });
381
+
382
+ return { hitCoordinate, hitDistance };
383
+ };
384
+ const shade = (hitCoordinate: TslNode, hitDistance: TslNode, direction: TslNode) => {
385
+ // A surface that faces away from the ray was reached through its back: a miss.
386
+ // (An unlit surface has no normal, so it counts as facing: a light source is usually one.)
387
+ const hitNormal = normalNode.sample(hitCoordinate).xyz;
388
+ const hitLength = hitNormal.dot(hitNormal).sqrt();
389
+ const facing = hitLength
390
+ .greaterThan(0.5)
391
+ .select(
392
+ smoothstep(0.25, -0.05, hitNormal.dot(direction).div(max(hitLength, float(1e-4)))),
393
+ float(1),
394
+ );
395
+ const edge = min(
396
+ min(
397
+ smoothstep(0, screenEdgeFade, hitCoordinate.x),
398
+ smoothstep(0, screenEdgeFade, float(1).sub(hitCoordinate.x)),
399
+ ),
400
+ min(
401
+ smoothstep(0, screenEdgeFade, hitCoordinate.y),
402
+ smoothstep(0, screenEdgeFade, float(1).sub(hitCoordinate.y)),
403
+ ),
404
+ );
405
+ // The trace fades into the fallback over its last half, as SSR's does.
406
+ const reachFade = float(1).sub(smoothstep(0.5, 1, hitDistance.div(radius)));
407
+ const weight = facing.mul(edge).mul(reachFade);
408
+ const radiance = colorNode
409
+ .sample(hitCoordinate)
410
+ .rgb.min(vec3(GI_MAX_LUMINANCE, GI_MAX_LUMINANCE, GI_MAX_LUMINANCE));
411
+ return { radiance, weight };
412
+ };
413
+ return { march, shade };
414
+ }
415
+
416
+ export interface IScreenSpaceGiOptions {
417
+ /** The camera the scene pass draws with (see IScreenSpaceReflectionOptions.camera). */
418
+ readonly camera: IScreenSpaceCamera;
419
+ /**
420
+ * The light a ray that finds nothing on screen would have returned: the tier below the screen traces. It is
421
+ * called once per pixel with the pixel's view-space position and unit normal and answers the average incident
422
+ * radiance (E / pi) that tier already supplies there. The gather then returns `hit - fallback` for the rays that
423
+ * hit, so the two tiers never add the same light twice. Missing means 0, as three's SSGINode (hits add light).
424
+ */
425
+ readonly fallback?: (position: TslNode, normal: TslNode) => TslNode;
426
+ /**
427
+ * Gather with screen probes instead of per-pixel rays (Unreal's ScreenProbeGather): one probe per
428
+ * `downsampleFactor` pixel tile traces an octahedron of rays, the probe radiance is turned into an irradiance
429
+ * octahedron, and each pixel blends the four nearest probes it can see. The call shape and the result are the
430
+ * per-pixel gather's, at a fraction of its rays.
431
+ */
432
+ readonly probes?: IScreenProbeOptions;
433
+ }
434
+
435
+ export interface IScreenProbeOptions {
436
+ /** Pixels between probes (Unreal's r.Lumen.ScreenProbeGather.DownsampleFactor; 16 at Epic). */
437
+ readonly downsampleFactor: number;
438
+ /** The drawing buffer, in pixels. It fixes the probe grid; a resize needs a new gather. */
439
+ readonly viewport: { readonly width: number; readonly height: number };
440
+ /** Rays on a side of each probe's octahedron (r.Lumen.ScreenProbeGather.TracingOctahedronResolution; 8 at Epic). */
441
+ readonly tracingOctahedronResolution?: number;
442
+ /**
443
+ * Diagnosis: label only this pass group as the `SSGI` GPU stage, so `info.engine.gpuStages.SSGI` times it alone and the
444
+ * other groups count in the frame. Omit to label every pass; `null` labels none (another stage is being timed).
445
+ */
446
+ readonly timedPass?: ScreenProbePass | null;
447
+ }
448
+
449
+ /** The screen-probe gather's pass groups, in the order they draw. */
450
+ export const SCREEN_PROBE_PASSES = ["trace", "filter", "gather"] as const;
451
+ export type ScreenProbePass = (typeof SCREEN_PROBE_PASSES)[number];
452
+
453
+ /** Texels on a side of the irradiance octahedron each probe keeps (Unreal's gather resolution 6, bilinear lookup). */
454
+ const IRRADIANCE_SIDE = 6;
455
+
456
+ /** Rays per slice: sliceCount x this many cosine-weighted rays leave each pixel. */
457
+ const RAYS_PER_SLICE = 4;
458
+ /** The most slices a trace may take (`stepCount` picks how many, spaced quadratically over `radius`). */
459
+ const GI_MAX_STEPS = 24;
460
+ /** Largest radiance a hit may carry (the radiosity cache of Lumen caps a ray at 40: LumenRadiosity.cpp). */
461
+ const GI_MAX_LUMINANCE = 40;
462
+
463
+ /**
464
+ * Screen-space diffuse GI for the owned engine, with the call shape of three's `ssgi(beauty, depth, normal,
465
+ * camera)` (SSGINode): per pixel, `sliceCount x 4` cosine-weighted rays over the normal's hemisphere, each
466
+ * marched through the depth buffer in `stepCount` slices (a quadratic spacing out to `radius`, hits by depth crossing with Lumen's
467
+ * relative thickness, 0.02 of the depth: LumenScreenProbeTracing.cpp). A hit returns the lit colour at the hit
468
+ * pixel, as Lumen's screen traces return the previous frame's lit scene; a miss returns the `fallback` tier.
469
+ * The result is the incident radiance the traces add to what the fallback supplies, E / pi units: the caller
470
+ * multiplies it by the receiver's albedo (`mrt({ diffuseColor })`) and adds it to the lit frame.
471
+ * rgb mean over the rays of hit x (hit radiance - fallback)
472
+ * a the share of rays that hit
473
+ * `getAONode()` answers 1: occlusion is the GTAO stage's, and hits already darken through `hit - fallback`.
474
+ */
475
+ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
476
+ return function ssgi(
477
+ colorNode: TslNode,
478
+ depthNode: TslNode,
479
+ normalNode: TslNode,
480
+ cameraOrOptions: IScreenSpaceCamera | IScreenSpaceGiOptions,
481
+ ): TslNode {
482
+ const { Break, Fn, If, Loop, float, int, max, min, normalize, rtt, smoothstep, uniform, uv } =
483
+ tsl;
484
+ const { vec2, vec3, vec4 } = tsl;
485
+ const options: IScreenSpaceGiOptions =
486
+ "camera" in cameraOrOptions ? cameraOrOptions : { camera: cameraOrOptions };
487
+ const mapping = defineCameraMapping(tsl, options.camera, "ssgi");
488
+ const { viewPosition } = mapping;
489
+ const radius = uniform(12);
490
+ const thickness = uniform(0.02);
491
+ const sliceCount = uniform(2);
492
+ const stepCount = uniform(12);
493
+ const intensity = uniform(1);
494
+ const screenEdgeFade = uniform(0.1);
495
+ const probeJitter = uniform(1);
496
+ const probeDebug = uniform(0);
497
+ const { march, shade } = defineGiTrace(tsl, {
498
+ colorNode,
499
+ depthNode,
500
+ mapping,
501
+ normalNode,
502
+ uniforms: { radius, screenEdgeFade, stepCount, thickness },
503
+ });
504
+
505
+ if (options.probes !== undefined) {
506
+ const node = defineScreenProbes(tsl, {
507
+ depthNode,
508
+ mapping,
509
+ march,
510
+ normalNode,
511
+ options,
512
+ probes: options.probes,
513
+ shade,
514
+ uniform: { intensity, jitter: probeJitter, debug: probeDebug },
515
+ });
516
+ return Object.defineProperties(node, {
517
+ ...Object.fromEntries(
518
+ Object.entries({
519
+ radius,
520
+ thickness,
521
+ sliceCount,
522
+ stepCount,
523
+ intensity,
524
+ screenEdgeFade,
525
+ probeJitter,
526
+ probeDebug,
527
+ }).map(([name, value]) => [name, { value }]),
528
+ ),
529
+ getGINode: { value: () => node },
530
+ getAONode: { value: () => tsl.vec4(1, 1, 1, 1) },
531
+ resolutionScale: {
532
+ get: () => node.getResolutionScale(),
533
+ set: (value: number) => node.setResolutionScale(value),
534
+ },
535
+ });
536
+ }
537
+
538
+ const graph = Fn(() => {
539
+ const coordinate = uv();
540
+ const result = vec4(0, 0, 0, 0).toVar();
541
+ const centreDepth = depthNode.sample(coordinate).r;
542
+ const centreNormal = normalNode.sample(coordinate).xyz;
543
+ // A draw the normal pass skips (an unlit material) leaves a zero normal: it takes no gathered light.
544
+ If(centreDepth.lessThan(1).and(centreNormal.dot(centreNormal).greaterThan(0.25)), () => {
545
+ const position = viewPosition(coordinate, centreDepth);
546
+ const normal = normalize(centreNormal);
547
+ const fallback = options.fallback?.(position, normal) ?? vec3(0, 0, 0);
548
+ // A frame around the normal, and a per-pixel rotation of the ray set (interleaved gradient noise on a
549
+ // fixed lattice of the uv: the noise is the denoiser's to remove, not a pattern to see).
550
+ const helper = normal.y
551
+ .abs()
552
+ .lessThan(0.99)
553
+ .select(vec3(0, 1, 0), vec3(1, 0, 0));
554
+ const tangent = normalize(helper.cross(normal));
555
+ const bitangent = normal.cross(tangent);
556
+ const cell = coordinate.mul(2048).floor();
557
+ const noiseA = cell.x
558
+ .mul(0.06711056)
559
+ .add(cell.y.mul(0.00583715))
560
+ .fract()
561
+ .mul(52.9829189)
562
+ .fract();
563
+ const noiseB = noiseA.mul(7.31).add(cell.x.mul(0.0123)).fract();
564
+ const origin = position.add(normal.mul(max(0.01, position.z.negate().mul(0.004))));
565
+ const rays = sliceCount.mul(RAYS_PER_SLICE);
566
+
567
+ const gathered = vec3(0, 0, 0).toVar();
568
+ const hits = float(0).toVar();
569
+ Loop(
570
+ { start: int(0), end: int(RAYS_PER_SLICE * 8), type: "int", condition: "<" },
571
+ ({ i }) => {
572
+ If(float(i).greaterThanEqual(rays), () => {
573
+ Break();
574
+ });
575
+ // Stratified cosine-weighted direction: u1 stratified over the set, u2 a golden-ratio sequence.
576
+ const u1 = float(i).add(noiseA).div(rays);
577
+ const u2 = noiseB.add(float(i).mul(0.61803398875)).fract();
578
+ const spread = u1.sqrt();
579
+ const angle = u2.mul(6.28318530718);
580
+ const direction = normalize(
581
+ tangent
582
+ .mul(spread.mul(angle.cos()))
583
+ .add(bitangent.mul(spread.mul(angle.sin())))
584
+ .add(normal.mul(float(1).sub(u1).sqrt())),
585
+ );
586
+
587
+ const trace = march(origin, direction, position.z);
588
+ If(trace.hitDistance.greaterThanEqual(0), () => {
589
+ const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
590
+ gathered.assign(gathered.add(hit.radiance.sub(fallback).mul(hit.weight)));
591
+ hits.assign(hits.add(hit.weight));
592
+ });
593
+ },
594
+ );
595
+ result.assign(vec4(gathered.div(rays).mul(intensity), hits.div(rays)));
596
+ });
597
+ return result;
598
+ })();
599
+
600
+ const node = rtt(graph, null, null, { type: HALF_FLOAT_TYPE, gpuStage: GI_STAGE });
601
+ const uniformObjects = { radius, thickness, sliceCount, stepCount, intensity, screenEdgeFade };
602
+ return Object.defineProperties(node, {
603
+ ...Object.fromEntries(
604
+ Object.entries(uniformObjects).map(([name, value]) => [name, { value }]),
605
+ ),
606
+ getGINode: { value: () => node },
607
+ getAONode: { value: () => vec4(1, 1, 1, 1) },
608
+ resolutionScale: {
609
+ get: () => node.getResolutionScale(),
610
+ set: (value: number) => node.setResolutionScale(value),
611
+ },
612
+ });
613
+ };
614
+ }
615
+
616
+ /** Octahedral direction of a point in the unit square (a unit vector, uniform enough over the sphere for a probe). */
617
+ function octahedronDecode(tsl: IScreenSpaceTsl, square: TslNode): TslNode {
618
+ const { float, normalize, vec2, vec3 } = tsl;
619
+ const f = square.mul(2).sub(1);
620
+ const z = float(1).sub(f.x.abs()).sub(f.y.abs());
621
+ const fold = vec2(float(1).sub(f.y.abs()), float(1).sub(f.x.abs())).mul(
622
+ vec2(
623
+ f.x.greaterThanEqual(0).select(float(1), float(-1)),
624
+ f.y.greaterThanEqual(0).select(float(1), float(-1)),
625
+ ),
626
+ );
627
+ const xy = z.lessThan(0).select(fold, f);
628
+ return normalize(vec3(xy.x, xy.y, z));
629
+ }
630
+
631
+ /** The point of the unit square an octahedral direction lands on (the inverse of `octahedronDecode`). */
632
+ function octahedronEncode(tsl: IScreenSpaceTsl, direction: TslNode): TslNode {
633
+ const { float, vec2 } = tsl;
634
+ const p = vec2(direction.x, direction.y).div(
635
+ direction.x.abs().add(direction.y.abs()).add(direction.z.abs()),
636
+ );
637
+ const fold = vec2(float(1).sub(p.y.abs()), float(1).sub(p.x.abs())).mul(
638
+ vec2(
639
+ p.x.greaterThanEqual(0).select(float(1), float(-1)),
640
+ p.y.greaterThanEqual(0).select(float(1), float(-1)),
641
+ ),
642
+ );
643
+ return direction.z.lessThan(0).select(fold, p).mul(0.5).add(0.5);
644
+ }
645
+
646
+ /**
647
+ * The screen-probe gather (PRD-640). Three passes, none per pixel until the last:
648
+ * 1. trace one texel per ray: a probe per tile traces an `n x n` octahedron of rays (view space) and keeps the lit
649
+ * colour each hit found and its weight.
650
+ * 2. filter each probe turns its rays into an irradiance octahedron: per direction, the cosine-weighted mean of
651
+ * `hit - fallback` over every ray, as the per-pixel gather returns it, so a ray that leaves the screen keeps
652
+ * the cache. A pixel then reads one bilinear tap instead of 64 rays.
653
+ * 3. gather each pixel blends the four nearest probes by position, depth-plane distance and normal agreement, and
654
+ * reads each probe's irradiance along the pixel normal. A pixel no probe can see gets the cache alone.
655
+ */
656
+ function defineScreenProbes(
657
+ tsl: IScreenSpaceTsl,
658
+ input: {
659
+ readonly depthNode: TslNode;
660
+ readonly normalNode: TslNode;
661
+ readonly mapping: ReturnType<typeof defineCameraMapping>;
662
+ readonly march: ReturnType<typeof defineGiTrace>["march"];
663
+ readonly shade: ReturnType<typeof defineGiTrace>["shade"];
664
+ readonly options: IScreenSpaceGiOptions;
665
+ readonly probes: IScreenProbeOptions;
666
+ readonly uniform: {
667
+ readonly intensity: TslNode;
668
+ readonly jitter: TslNode;
669
+ readonly debug: TslNode;
670
+ };
671
+ },
672
+ ): TslNode {
673
+ const { Fn, If, Loop, float, int, max, min, normalize, rtt, smoothstep, uv, vec2, vec3, vec4 } =
674
+ tsl;
675
+ const { depthNode, normalNode, march, shade, options, probes } = input;
676
+ const { viewPosition } = input.mapping;
677
+ const factor = probes.downsampleFactor;
678
+ const side = probes.tracingOctahedronResolution ?? 8;
679
+ if (
680
+ !(factor >= 1) ||
681
+ !(side >= 2) ||
682
+ !(probes.viewport.width > 0) ||
683
+ !(probes.viewport.height > 0) ||
684
+ (probes.timedPass != null && !SCREEN_PROBE_PASSES.includes(probes.timedPass))
685
+ )
686
+ throw new TypeError(
687
+ `TN_NATIVE_SCREEN_PROBES: downsampleFactor ${factor}, tracingOctahedronResolution ${side}, viewport ${probes.viewport.width}x${probes.viewport.height}, timedPass ${String(probes.timedPass)}`,
688
+ );
689
+ const stage = (pass: ScreenProbePass): GpuStage | undefined =>
690
+ probes.timedPass === undefined || probes.timedPass === pass ? GI_STAGE : undefined;
691
+ const tilesX = Math.ceil(probes.viewport.width / factor);
692
+ const tilesY = Math.ceil(probes.viewport.height / factor);
693
+ const tiles = vec2(tilesX, tilesY);
694
+ const traceSize = vec2(tilesX * side, tilesY * side);
695
+ const irradianceSize = vec2(tilesX * IRRADIANCE_SIDE, tilesY * IRRADIANCE_SIDE);
696
+ const valid = (depth: TslNode, normal: TslNode): TslNode =>
697
+ // A draw the normal pass skips (an unlit material) leaves a zero normal: it takes no gathered light.
698
+ depth
699
+ .lessThan(1)
700
+ .and(normal.dot(normal).greaterThan(0.25));
701
+
702
+ // Each probe rotates its octahedron by its own offset inside one cell (a golden-ratio sequence over the tile index), so
703
+ // the rays of neighbouring probes never repeat: banding that follows the probe grid turns into noise the denoiser removes.
704
+ const rayDirection = (tile: TslNode, cell: TslNode): TslNode => {
705
+ const index = tile.x.add(tile.y.mul(tilesX));
706
+ const offset = index
707
+ .mul(vec2(0.7548776662, 0.569840291))
708
+ .fract()
709
+ .sub(0.5)
710
+ .mul(input.uniform.jitter)
711
+ .add(0.5);
712
+ return octahedronDecode(tsl, cell.add(offset).div(side));
713
+ };
714
+
715
+ // 1. trace: this texel is ray `cell` of probe `tile`.
716
+ const traceGraph = Fn(() => {
717
+ const texel = uv().mul(traceSize).floor();
718
+ const tile = texel.div(side).floor();
719
+ const cell = texel.sub(tile.mul(side));
720
+ const probeUv = tile.add(0.5).div(tiles).min(vec2(1, 1));
721
+ const result = vec4(0, 0, 0, 0).toVar();
722
+ const depth = depthNode.sample(probeUv).r;
723
+ const rawNormal = normalNode.sample(probeUv).xyz;
724
+ If(valid(depth, rawNormal), () => {
725
+ const position = viewPosition(probeUv, depth);
726
+ const normal = normalize(rawNormal);
727
+ const direction = rayDirection(tile, cell);
728
+ const origin = position.add(normal.mul(max(0.01, position.z.negate().mul(0.004))));
729
+ const trace = march(origin, direction, position.z);
730
+ If(trace.hitDistance.greaterThanEqual(0), () => {
731
+ // The lit colour the ray found and its weight; the filter subtracts what the cache believes about the receiver.
732
+ const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
733
+ result.assign(vec4(hit.radiance.mul(hit.weight), hit.weight));
734
+ });
735
+ });
736
+ return result;
737
+ })();
738
+ const traced = rtt(traceGraph, tilesX * side, tilesY * side, {
739
+ type: HALF_FLOAT_TYPE,
740
+ minFilter: 1003,
741
+ magFilter: 1003,
742
+ gpuStage: stage("trace"),
743
+ });
744
+
745
+ // 2. filter: this texel is direction `cell` of probe `tile`'s irradiance octahedron.
746
+ const filterGraph = Fn(() => {
747
+ const texel = uv().mul(irradianceSize).floor();
748
+ const tile = texel.div(IRRADIANCE_SIDE).floor();
749
+ const cell = texel.sub(tile.mul(IRRADIANCE_SIDE));
750
+ const normal = octahedronDecode(tsl, cell.add(0.5).div(IRRADIANCE_SIDE));
751
+ const sum = vec4(0, 0, 0, 0).toVar();
752
+ const weights = float(0).toVar();
753
+ Loop({ start: int(0), end: int(side * side), type: "int", condition: "<" }, ({ i }) => {
754
+ const row = float(i).div(side).floor();
755
+ const ray = vec2(float(i).sub(row.mul(side)), row);
756
+ const direction = rayDirection(tile, ray);
757
+ const weight = max(direction.dot(normal), float(0));
758
+ const found = traced.sample(tile.mul(side).add(ray).add(0.5).div(traceSize));
759
+ sum.assign(sum.add(found.mul(weight)));
760
+ weights.assign(weights.add(weight));
761
+ });
762
+ // The per-pixel gather's convention, once per probe direction instead of once per pixel: the rays that hit return
763
+ // `hit - cache` over every ray, so the two tiers never add the same light twice.
764
+ const probeUv = tile.add(0.5).div(tiles).min(vec2(1, 1));
765
+ const depth = depthNode.sample(probeUv).r;
766
+ const rawNormal = normalNode.sample(probeUv).xyz;
767
+ const believed = valid(depth, rawNormal).select(
768
+ options.fallback?.(viewPosition(probeUv, depth), normal) ?? vec3(0, 0, 0),
769
+ vec3(0, 0, 0),
770
+ );
771
+ const total = max(weights, float(1e-4));
772
+ return vec4(sum.rgb.sub(believed.mul(sum.a)).div(total), sum.a.div(total));
773
+ })();
774
+ const filtered = rtt(filterGraph, tilesX * IRRADIANCE_SIDE, tilesY * IRRADIANCE_SIDE, {
775
+ type: HALF_FLOAT_TYPE,
776
+ gpuStage: stage("filter"),
777
+ });
778
+
779
+ // 3. gather: each pixel blends the four nearest probes it can see.
780
+ const gatherGraph = Fn(() => {
781
+ const coordinate = uv();
782
+ const result = vec4(0, 0, 0, 0).toVar();
783
+ const centreDepth = depthNode.sample(coordinate).r;
784
+ const centreNormal = normalNode.sample(coordinate).xyz;
785
+ If(valid(centreDepth, centreNormal), () => {
786
+ const position = viewPosition(coordinate, centreDepth);
787
+ const normal = normalize(centreNormal);
788
+ const grid = coordinate.mul(tiles).sub(0.5);
789
+ const base = grid.floor();
790
+ const fraction = grid.sub(base);
791
+ const lookup = octahedronEncode(tsl, normal)
792
+ .mul(IRRADIANCE_SIDE - 1)
793
+ .add(0.5);
794
+ const sum = vec4(0, 0, 0, 0).toVar();
795
+ const weights = float(0).toVar();
796
+ for (const [dx, dy] of [
797
+ [0, 0],
798
+ [1, 0],
799
+ [0, 1],
800
+ [1, 1],
801
+ ] as const) {
802
+ const tile = base.add(vec2(dx, dy)).max(vec2(0, 0)).min(tiles.sub(1));
803
+ const probeUv = tile.add(0.5).div(tiles);
804
+ const probeDepth = depthNode.sample(probeUv).r;
805
+ const probeNormal = normalNode.sample(probeUv).xyz;
806
+ const probePosition = viewPosition(probeUv, probeDepth);
807
+ const bilinear = (dx === 1 ? fraction.x : float(1).sub(fraction.x)).mul(
808
+ dy === 1 ? fraction.y : float(1).sub(fraction.y),
809
+ );
810
+ // A probe on another surface reads another surface's light: weigh it by how far it lies off this pixel's plane
811
+ // (relative to depth) and how closely its normal agrees.
812
+ const offPlane = normal
813
+ .dot(probePosition.sub(position))
814
+ .abs()
815
+ .div(max(position.z.abs(), float(1e-3)));
816
+ const planeWeight = float(1).sub(smoothstep(0, 0.05, offPlane));
817
+ const agree = max(normal.dot(normalize(probeNormal)), float(0));
818
+ const normalWeight = agree.mul(agree).mul(agree.mul(agree));
819
+ const weight = valid(probeDepth, probeNormal).select(
820
+ bilinear.mul(planeWeight).mul(normalWeight),
821
+ float(0),
822
+ );
823
+ const irradiance = filtered.sample(
824
+ tile.mul(IRRADIANCE_SIDE).add(lookup).div(irradianceSize),
825
+ );
826
+ sum.assign(sum.add(irradiance.mul(weight)));
827
+ weights.assign(weights.add(weight));
828
+ }
829
+ // A pixel the probes cannot vouch for keeps the cache alone, fading in as their weight grows.
830
+ const trust = smoothstep(0.02, 0.25, weights);
831
+ const mean = sum.div(max(weights, float(1e-4))).mul(trust);
832
+ const shown = vec4(mean.rgb.mul(input.uniform.intensity), mean.a);
833
+ // Diagnosis: 1 shows the probes' weight and trust, 2 the delta's sign (red lighter than the cache, blue darker).
834
+ const luminance = mean.r.add(mean.g).add(mean.b).mul(0.3333);
835
+ result.assign(
836
+ input.uniform.debug
837
+ .equal(1)
838
+ .select(
839
+ vec4(trust, weights.min(1), 0, 0),
840
+ input.uniform.debug
841
+ .equal(2)
842
+ .select(vec4(luminance.max(0).mul(8), 0, luminance.negate().max(0).mul(8), 0), shown),
843
+ ),
844
+ );
845
+ });
846
+ return result;
847
+ })();
848
+ return rtt(gatherGraph, null, null, { type: HALF_FLOAT_TYPE, gpuStage: stage("gather") });
849
+ }