@threenative/core 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,309 @@
1
+ // The quality tiers of the Unreal 5.8.3 look (owner exception to "never own the look", 2026-10-22): what each tier
2
+ // turns on, and the GI and shadow settings per tier named after Unreal's scalability levels. A `WorldEnvironment`
3
+ // built with no options starts from the `high` tier; an explicit option always wins.
4
+ import type { IWorldEnvironmentOptions } from "./world-environment.js";
5
+
6
+ /**
7
+ * This game's authored looks. GPU family picks the start; measured frame budgets refine it.
8
+ * Edit these presets to change the look without changing the framework.
9
+ */
10
+ export type QualityTier = "low" | "medium" | "high";
11
+
12
+ const QUALITY_TIERS: readonly QualityTier[] = ["low", "medium", "high"];
13
+
14
+ /**
15
+ * Narrows an arbitrary string — a URL parameter, a saved setting — to a tier name. Not exported:
16
+ * `resolveQualityTier` is the one door in, so an unknown name cannot be waved past the throw.
17
+ */
18
+ function isQualityTier(value: string): value is QualityTier {
19
+ return (QUALITY_TIERS as readonly string[]).includes(value);
20
+ }
21
+
22
+ /**
23
+ * Where each GPU family starts, from `ctx.renderer.gpuClass`.
24
+ *
25
+ * A start, not a ceiling: the measured frame-budget windows move the look from here, and an
26
+ * explicit `tier` above still wins. A class absent from this table — `unknown`, an adapter no
27
+ * family rule matched — falls back to the `mobile` flag, exactly as before families existed.
28
+ * Edit the right-hand side to change what a family looks like; nothing outside this file reads it.
29
+ */
30
+ const START_TIER_BY_GPU_CLASS: Readonly<Record<string, QualityTier | undefined>> = {
31
+ software: "low",
32
+ "mobile-low": "low",
33
+ "mobile-mid": "low",
34
+ "mobile-high": "medium",
35
+ integrated: "medium",
36
+ discrete: "high",
37
+ };
38
+
39
+ /**
40
+ * Picks the tier: an explicit `tier` always wins, otherwise the platform decides.
41
+ *
42
+ * Fails closed. An unrecognised tier name throws with the value it was handed rather than
43
+ * quietly rendering the default, because a silent fallback here looks exactly like a tier that
44
+ * turned out to have no effect.
45
+ */
46
+ export function resolveQualityTier(
47
+ request: {
48
+ readonly gpuClass?: string;
49
+ readonly mobile?: boolean;
50
+ readonly software?: boolean;
51
+ readonly tier?: string;
52
+ } = {},
53
+ ): QualityTier {
54
+ const requested = request.tier;
55
+ if (requested !== undefined) {
56
+ if (!isQualityTier(requested)) {
57
+ throw new Error(
58
+ `Unknown quality tier ${JSON.stringify(requested)} — expected one of ${QUALITY_TIERS.join(", ")}.`,
59
+ );
60
+ }
61
+ return requested;
62
+ }
63
+ // A named software adapter — SwiftShader, llvmpipe, a basic-render driver — is the machine this
64
+ // game's desktop look cannot run on: a single `high` frame on one can outlast the device it is
65
+ // drawing on, and no adaptation that reacts to frame times gets to run first. `software` is the
66
+ // fact the renderer read from `adapter.info`, not a guess from a driver string, and an explicit
67
+ // `tier` above still wins over it.
68
+ if (request.software === true) return "low";
69
+ const family =
70
+ request.gpuClass === undefined ? undefined : START_TIER_BY_GPU_CLASS[request.gpuClass];
71
+ if (family !== undefined) return family;
72
+ return request.mobile === true ? "low" : "high";
73
+ }
74
+
75
+ /**
76
+ * The look every tier shares: a wide, faint glow on what is genuinely brighter than white — the
77
+ * sun disk, the visor — rather than a haze over the frame (a threshold under 1 blooms lit grey
78
+ * platforms and flattens contrast), a corner falloff, and the shared chain's SMAA. Antialiasing is
79
+ * on in every tier that installs a chain; see `screenSpaceAA` in `worldEnvironment.ts`.
80
+ *
81
+ * No screen-space reflections and no sharpen here, on purpose. Every surface already reflects the
82
+ * captured sky (`sky.ts`), and SSR on rough floors traced speckle into the grid; RCAS then rang the
83
+ * smooth sky gradient into visible bands. Both are one line to turn back on for a glossy scene.
84
+ */
85
+ const shared: IWorldEnvironmentOptions = {
86
+ // Unreal's metered auto exposure. Cost: unmeasured on its own; read `TN_FRAME_BUDGET`.
87
+ autoExposureEnabled: true,
88
+ // Unreal's local exposure (a bilateral grid). Cost: unmeasured on its own; read `TN_FRAME_BUDGET`.
89
+ localExposureEnabled: true,
90
+ // Unreal's six-stage bloom. Cost: unmeasured on its own; read `TN_FRAME_BUDGET`.
91
+ unrealBloomEnabled: true,
92
+ // Bloom cost: ~4.6 ms in the reference ablation — the second most expensive stage there.
93
+ bloomEnabled: true,
94
+ bloomRadius: 0.6,
95
+ bloomStrength: 0.22,
96
+ bloomThreshold: 1,
97
+ // Unreal's fixed exposure scale is 1.0: its scene-linear EXR passed through the filmic curve alone
98
+ // reproduces its PNG (mean error 0.4/255 over 72000 pixels, L1 and L2). Light units, not this
99
+ // number, set the level: the sun is 6 lux (`atmosphere.ts`). With auto exposure on this is only
100
+ // the value used while the meter is off.
101
+ exposure: 1,
102
+ tonemapMode: "filmic",
103
+ // Unreal's VignetteIntensity, cosine-fourth law (Scene.cpp, FPostProcessSettings constructor).
104
+ vignetteAmount: 0.4,
105
+ };
106
+
107
+ /**
108
+ * What a desktop gets: contact occlusion on top — the dark line where a foot meets the platform
109
+ * and a wall meets the ground, most of what separates "objects in a world" from "objects pasted on
110
+ * a background". Gathered at full resolution and denoised: at half, the upsample left a grain
111
+ * around every foot.
112
+ */
113
+ const high: IWorldEnvironmentOptions = {
114
+ ...shared,
115
+ // GTAO, full resolution plus denoise: unmeasured on its own here; read `TN_FRAME_BUDGET`.
116
+ gtaoEnabled: true,
117
+ // Contact scale. Unreal's Lumen (L7 up) has no wide screen-space AO: its short-range AO searches 32 px of the screen
118
+ // (aoReach.ts), so the radius is left to that rule. At a fixed 0.35 m the same GTAO darkened a band about 30 px wide
119
+ // along every interior corner and under the sunlit patch. The L6 arm keeps Unreal's SSAO radius in Reference.ts.in.
120
+ // Its steps sit at the squared fraction of the reach (`gtaoDistanceExponent` 2), 3 steps per direction
121
+ // (`gtaoSamples` 7: three directions, the node's count below 30 samples; Unreal takes 2 slices of 3 steps).
122
+ gtaoDistanceExponent: 2,
123
+ gtaoSamples: 7,
124
+ // Unreal weighs every step alike: the horizon is the largest over the steps (LumenScreenSpaceBentNormal.usf:271),
125
+ // with no 2 / (step + 2) falloff. The node's falloff narrowed the contact band to about 8 px against Unreal's 13.
126
+ gtaoDistanceFalloff: 0,
127
+ // Epic: Unreal's screen probe gather (`sg.GlobalIlluminationQuality` 3). See `giPreset`.
128
+ finalGatherMethod: "screenProbeGather",
129
+ renderChainTier: "high",
130
+ // Sharp in motion over Unreal's desktop defaults (owner, 2026-10-28: "as if things briefly lost definition"). Unreal
131
+ // turns camera motion blur on for a high end PC (HardwareTargetingModule.cpp) and resolves edges temporally
132
+ // (`r.AntiAliasingMethod` 4, SceneView.cpp:236-246); both soften anything that moves. This tier draws 4x MSAA,
133
+ // Unreal's own forward and mobile default (`r.MSAACount` 4), with no blur. `temporalAA: true` (the `traa` stage;
134
+ // `setupPost(...).debug().temporal` reads it) and `motionBlurEnabled: true` are the named opt-ins, for a scene whose
135
+ // foliage, specular or stochastic effects shimmer without temporal averaging.
136
+ motionBlurEnabled: false,
137
+ samples: 4,
138
+ temporalAA: false,
139
+ };
140
+
141
+ /**
142
+ * The rung in between: the same occlusion, and the chain's own antialiasing one notch cheaper.
143
+ */
144
+ // Medium keeps the chain's SMAA: a four-sample world resolve adds mobile bandwidth.
145
+ const medium: IWorldEnvironmentOptions = {
146
+ ...high,
147
+ // Medium: world-space probes only (`sg.GlobalIlluminationQuality` 1).
148
+ finalGatherMethod: "irradianceField",
149
+ // Unreal's Medium spends less on AO than Epic: AmbientOcclusionMaxQuality 60 against 100 (BaseScalability.ini:590,
150
+ // :625), so its SSAO runs 2 levels, the second at half resolution (PostProcessAmbientOcclusion.cpp:243-270). This
151
+ // tier gathers its occlusion at half resolution: Iris Xe, Hop Garden 1080p, GPU 28.8 -> 25.0 ms.
152
+ gtaoResolutionScale: 0.5,
153
+ renderChainTier: "medium",
154
+ samples: 0,
155
+ };
156
+
157
+ /**
158
+ * What a phone gets: bloom, vignette and the tone curve, nothing screen-space. Unreal's default device profile turns
159
+ * local exposure off on mobile (BaseDeviceProfiles.ini), so this does too. Its edges stay on SMAA: the temporal pass
160
+ * costs a velocity target and a history target, and no phone has been measured with it.
161
+ */
162
+ const low: IWorldEnvironmentOptions = {
163
+ ...shared,
164
+ // Low: no diffuse GI (`sg.GlobalIlluminationQuality` 0).
165
+ finalGatherMethod: "none",
166
+ localExposureEnabled: false,
167
+ renderChainTier: "low",
168
+ };
169
+
170
+ const QUALITY_PRESETS: Record<QualityTier, IWorldEnvironmentOptions> = { high, low, medium };
171
+
172
+ /**
173
+ * Harness: the screen-space gather Unreal's L7 (Epic) is judged against: 32 rays a pixel at half resolution, denoised
174
+ * over 16 gather pixels. A calibration tool, not a shipping tier (PRD-640 Phase 1: about 31 ms at 1080p). Every harness
175
+ * scene that renders global illumination spreads it, so no scene falls back to the `high` preset's 2-slice gather.
176
+ */
177
+ export const EPIC_SSGI: IWorldEnvironmentOptions = {
178
+ ssgiDenoiseRadius: 16,
179
+ ssgiQuality: "epic",
180
+ ssgiResolutionScale: 0.5,
181
+ };
182
+
183
+ /** The stages and strengths a tier turns on. Throws on a name that is not a tier. */
184
+ export function qualityPreset(tier: string): IWorldEnvironmentOptions {
185
+ const preset = QUALITY_PRESETS[tier as QualityTier];
186
+ if (preset === undefined) {
187
+ throw new Error(
188
+ `Unknown quality tier ${JSON.stringify(tier)} — expected one of ${QUALITY_TIERS.join(", ")}.`,
189
+ );
190
+ }
191
+ return preset;
192
+ }
193
+
194
+ /**
195
+ * Global illumination and shadow filtering per tier, named after Unreal's scalability levels
196
+ * (Engine/Config/BaseScalability.ini, `[GlobalIlluminationQuality@0..3]` and `[ShadowQuality@0..3]`).
197
+ * A fresh Unreal project runs Epic (3), so `high` is Epic; `medium` is level 1 and `low` is level 0.
198
+ * Unreal's own level 2 (High) is not a ThreeNative tier: the three tiers are the three levels a
199
+ * calibration scene is judged against (PRD-644, PRD-652).
200
+ */
201
+ export type FinalGatherMethod = "none" | "irradianceField" | "screenProbeGather";
202
+
203
+ export interface IGiTier {
204
+ /**
205
+ * How bounce light reaches a pixel. `none` is Unreal's Low: no diffuse GI, the sky light at 0.8.
206
+ * `irradianceField` is Medium: world-space probes only (the baked cache here). `screenProbeGather`
207
+ * is Epic: the screen-space gather over the same cache. The preset of the tier names it.
208
+ */
209
+ readonly finalGatherMethod: FinalGatherMethod;
210
+ /** Read-only report: the `sg.GlobalIlluminationQuality` this tier follows. */
211
+ readonly globalIlluminationQuality: 0 | 1 | 3;
212
+ /**
213
+ * `r.DistanceFieldAO`: whether the scene's distance fields shadow the sky light. Unreal's Low turns it off, so
214
+ * the sky light reaches the inside of a room unoccluded (measured on `sunlit-room`, PRD-644 `## Decisions`).
215
+ */
216
+ readonly distanceFieldAO: boolean;
217
+ /** `r.SkylightIntensityMultiplier`: Unreal suppresses the sky light to 0.8 at Low, where DFAO is off. */
218
+ readonly skylightIntensityMultiplier: number;
219
+ }
220
+
221
+ /** What each method's Unreal level sets (BaseScalability.ini `[GlobalIlluminationQuality@n]`, lines 318-460). */
222
+ const GI_LEVELS: Record<FinalGatherMethod, Omit<IGiTier, "finalGatherMethod">> = {
223
+ irradianceField: {
224
+ distanceFieldAO: true,
225
+ globalIlluminationQuality: 1,
226
+ skylightIntensityMultiplier: 1,
227
+ },
228
+ none: { distanceFieldAO: false, globalIlluminationQuality: 0, skylightIntensityMultiplier: 0.8 },
229
+ screenProbeGather: {
230
+ distanceFieldAO: true,
231
+ globalIlluminationQuality: 3,
232
+ skylightIntensityMultiplier: 1,
233
+ },
234
+ };
235
+
236
+ /** The GI method and Unreal level of a tier. Throws on a name that is not a tier. */
237
+ export function giPreset(tier: string): IGiTier {
238
+ const finalGatherMethod = qualityPreset(tier).finalGatherMethod as FinalGatherMethod;
239
+ return { finalGatherMethod, ...GI_LEVELS[finalGatherMethod] };
240
+ }
241
+
242
+ export interface IShadowFilter {
243
+ readonly blockerSamples: number;
244
+ readonly filterSamples: number;
245
+ }
246
+
247
+ export interface IShadowTier {
248
+ /** Read-only report: the `sg.ShadowQuality` this tier follows. */
249
+ readonly shadowQuality: 0 | 1 | 3;
250
+ /**
251
+ * Whether the sun and the lamps cast dynamic shadows. Unreal draws none at `sg.ShadowQuality` 0
252
+ * (`r.ShadowQuality=0`), measured on `penumbra-lab` (PRD-652 `## Decisions`), so `low` casts none.
253
+ */
254
+ readonly castShadows: boolean;
255
+ /**
256
+ * The receiver filter taps of the sun and of every lamp: Unreal's directional and local ray counts
257
+ * are equal at Medium and Epic, so one pair serves both.
258
+ */
259
+ readonly filter: IShadowFilter;
260
+ /** `r.Shadow.Virtual.ResolutionLodBiasDirectional`: -1 halves the finest sun level's texel. */
261
+ readonly resolutionLodBiasDirectional: number;
262
+ }
263
+
264
+ // Sample counts start from Unreal's rays x samples product against Epic's 32, on the filter's own
265
+ // 16 + 16 default: Medium (4 x 2 = 8) is a quarter of Epic, so 4 + 4. The penumbra-lab round
266
+ // (PRD-647 method) sets the final numbers; they are not fitted by eye. `low` draws no shadow, so its
267
+ // taps are never read.
268
+ const SHADOW_TIERS: Record<QualityTier, IShadowTier> = {
269
+ high: {
270
+ castShadows: true,
271
+ filter: { blockerSamples: 16, filterSamples: 16 },
272
+ // Unreal Epic sets -1.5 (`[ShadowQuality@3]`). Held at 0: -1.5 changes `sun4-ramp` and no judge has called it
273
+ // an improvement, so `high` stays the pre-change look (PRD-652 `## Decisions`). `?shadowBias=` brackets it.
274
+ resolutionLodBiasDirectional: 0,
275
+ shadowQuality: 3,
276
+ },
277
+ low: {
278
+ castShadows: false,
279
+ filter: { blockerSamples: 4, filterSamples: 4 },
280
+ resolutionLodBiasDirectional: 0,
281
+ shadowQuality: 0,
282
+ },
283
+ medium: {
284
+ castShadows: true,
285
+ filter: { blockerSamples: 4, filterSamples: 4 },
286
+ resolutionLodBiasDirectional: 0,
287
+ shadowQuality: 1,
288
+ },
289
+ };
290
+
291
+ /** The shadow filter and resolution bias of a tier. Throws on a name that is not a tier. */
292
+ export function shadowPreset(tier: string): IShadowTier {
293
+ const preset = SHADOW_TIERS[tier as QualityTier];
294
+ if (preset === undefined) {
295
+ throw new Error(
296
+ `Unknown quality tier ${JSON.stringify(tier)} — expected one of ${QUALITY_TIERS.join(", ")}.`,
297
+ );
298
+ }
299
+ return preset;
300
+ }
301
+
302
+ /** The tier tables as one object: `resolve` a start tier from a GPU class, `gi` and `shadow` settings of a tier. */
303
+ export const qualityTiers = {
304
+ // UE 5.8.3 BaseScalability.ini:37, snapped to the resolution scaler's rungs; low has no temporal resolve.
305
+ resolutionScale: { low: 1, medium: 0.72, high: 0.85 },
306
+ gi: giPreset,
307
+ resolve: resolveQualityTier,
308
+ shadow: shadowPreset,
309
+ } as const;
@@ -0,0 +1,344 @@
1
+ // Generated for you: ordinary Three.js; ThreeNative does not read this file.
2
+ //
3
+ // Traced reflections: what a smooth surface shows of the scene, from the scene's triangles and not from
4
+ // the screen. The `ssr` stage finds a hit among the pixels the camera drew, so a ray that leaves the frame,
5
+ // or reaches the far side of an object, meets the camera-facing pixel near the silhouette (lit, wrong side).
6
+ // This stage walks `TracedReflections` (the engine mechanism) for the exact surface, then lights
7
+ // that surface here. How a hit is lit is a look, so it lives in this file and not in the package.
8
+ //
9
+ // Unreal traces dedicated reflection rays for roughness up to 0.4 and lights each hit from its surface cache
10
+ // (Engine/Source/Runtime/Renderer/Private/Lumen/LumenReflectionTracing.cpp). Without a surface cache the hit
11
+ // takes the sun with one shadow ray, the world-space radiance cache for the bounce, and its own emission.
12
+
13
+ import type { DirectionalLight, PerspectiveCamera, PointLight, SpotLight, Texture } from "three";
14
+ import { HalfFloatType, SRGBColorSpace } from "three";
15
+ import {
16
+ Fn,
17
+ If,
18
+ clamp,
19
+ dot,
20
+ float,
21
+ length,
22
+ max,
23
+ mix,
24
+ normalize,
25
+ pow,
26
+ reflect,
27
+ rtt,
28
+ saturate,
29
+ select,
30
+ smoothstep,
31
+ uniform,
32
+ uv,
33
+ vec3,
34
+ vec4,
35
+ } from "three/tsl";
36
+ import type { Node, TextureNode } from "three/webgpu";
37
+ import type { TracedReflections } from "../render/traced-reflections.js";
38
+ import { giCache } from "./gi-registry.js";
39
+
40
+ /** The traced scene the reference scene registers, read by the `ssr` stage when it builds. */
41
+ export const reflectionTrace: {
42
+ current?: TracedReflections;
43
+ /** The scene's point and spot lamps: each lights a hit like the sun (the scene registers them with the trace). */
44
+ lamps?: readonly (PointLight | SpotLight)[];
45
+ } = {};
46
+
47
+ export interface ITracedReflectionStage {
48
+ readonly trace: TracedReflections;
49
+ /** The scene camera the pass draws with: a post quad has its own, so the stage reads this one every render. */
50
+ readonly camera: PerspectiveCamera;
51
+ /** The sun, for the hit's direct light. Unset: a hit takes only the cache and its own emission. */
52
+ readonly sun?: DirectionalLight;
53
+ /**
54
+ * The point and spot lamps, for the hit's direct light: each lights a hit through one shadow ray, as the sun does. Unreal's
55
+ * surface cache takes the direct light of every light in the scene, not only the sun
56
+ * (Engine/Source/Runtime/Renderer/Private/Lumen/LumenSceneDirectLighting.cpp).
57
+ */
58
+ readonly lamps?: readonly (PointLight | SpotLight)[];
59
+ /** The lit frame, the scene pass's depth, view-space normal, metalness (r) and roughness (g). */
60
+ readonly base: TextureNode;
61
+ readonly depth: TextureNode;
62
+ readonly normal: TextureNode;
63
+ readonly metalness: TextureNode;
64
+ readonly roughness: TextureNode;
65
+ /** The surface's own colour (the scene pass's `diffuseColor`), which tints a metal's reflection. */
66
+ readonly albedo?: TextureNode;
67
+ /** The frame's exposure multiplier: scene light times this is what the chain holds. */
68
+ readonly gain: Node<"float">;
69
+ /** Metres a ray travels before it counts as a miss. Unset: the whole scene, and no fade. */
70
+ readonly maxDistance?: number;
71
+ readonly resolutionScale?: number;
72
+ /**
73
+ * The sky light a hit takes when no world-space radiance cache is registered: E / pi on the six axes
74
+ * (+X, -X, +Y, -Y, +Z, -Z), from `skyAmbientCube`. Unset: a hit in shadow is black.
75
+ */
76
+ readonly skyIrradiance?: readonly (readonly [number, number, number])[];
77
+ }
78
+
79
+ /** The environment's pixels as linear radiance per channel, or undefined when they are not on the CPU. */
80
+ function linearPixels(
81
+ environment: Texture | null | undefined,
82
+ ): { width: number; height: number; at: (index: number) => number } | undefined {
83
+ const image = environment?.image as
84
+ | { data?: ArrayLike<number>; width?: number; height?: number }
85
+ | undefined;
86
+ const data = image?.data;
87
+ const width = image?.width ?? 0;
88
+ const height = image?.height ?? 0;
89
+ if (data === undefined || width < 1 || height < 1 || data.length < width * height * 4)
90
+ return undefined;
91
+ if (data instanceof Float32Array) return { width, height, at: (index) => data[index] ?? 0 };
92
+ if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) return undefined;
93
+ const srgb = environment?.colorSpace === SRGBColorSpace;
94
+ return {
95
+ width,
96
+ height,
97
+ at: (index) => {
98
+ const v = (data[index] ?? 0) / 255;
99
+ if (!srgb) return v;
100
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
101
+ },
102
+ };
103
+ }
104
+
105
+ /**
106
+ * The sky light a surface facing each axis receives, E / pi on +X, -X, +Y, -Y, +Z, -Z, from an equirectangular
107
+ * environment whose pixels are on the CPU (a `DataTexture`): Unreal lights a reflection hit with the sky light
108
+ * among the rest (Lumen's surface cache carries it). Undefined when the pixels are not readable (an image, a GPU
109
+ * target): the hit then takes no sky light.
110
+ */
111
+ export function skyAmbientCube(
112
+ environment: Texture | null | undefined,
113
+ intensity = 1,
114
+ ): [number, number, number][] | undefined {
115
+ const pixels = linearPixels(environment);
116
+ if (pixels === undefined) return undefined;
117
+ const { width, height } = pixels;
118
+ // +X, -X, +Y, -Y, +Z, -Z: a direction lights the axis on its own side of each component by that component.
119
+ const sums = Array.from({ length: 6 }, () => [0, 0, 0] as [number, number, number]);
120
+ // three's equirectUV: u = atan2(z, x) / 2pi + 0.5, v = asin(y) / pi + 0.5, with row 0 at v = 0 (no flip).
121
+ for (let row = 0; row < height; row++) {
122
+ const elevation = ((row + 0.5) / height - 0.5) * Math.PI;
123
+ // The texel's solid angle, (2 pi / width) (pi / height) cos(elevation), over pi.
124
+ const weight = (2 * Math.PI * Math.cos(elevation) * intensity) / (width * height);
125
+ for (let column = 0; column < width; column++) {
126
+ const azimuth = ((column + 0.5) / width - 0.5) * 2 * Math.PI;
127
+ const direction = [
128
+ Math.cos(elevation) * Math.cos(azimuth),
129
+ Math.sin(elevation),
130
+ Math.cos(elevation) * Math.sin(azimuth),
131
+ ] as const;
132
+ const at = (row * width + column) * 4;
133
+ const radiance = [pixels.at(at), pixels.at(at + 1), pixels.at(at + 2)] as const;
134
+ direction.forEach((cosine, axis) => {
135
+ const sum = sums[2 * axis + (cosine >= 0 ? 0 : 1)] as [number, number, number];
136
+ const share = Math.abs(cosine) * weight;
137
+ sum[0] += radiance[0] * share;
138
+ sum[1] += radiance[1] * share;
139
+ sum[2] += radiance[2] * share;
140
+ });
141
+ }
142
+ }
143
+ return sums;
144
+ }
145
+
146
+ /** With a `maxDistance`, a hit's reflection fades out over the last half of the reach, so a far surface does not pop. */
147
+ const FADE_FROM = 0.5;
148
+ /** Depth buffers lose precision with distance, so the ray starts off the surface by more the farther it is. */
149
+ const START_OFFSET = 0.01;
150
+ const START_OFFSET_PER_METRE = 0.004;
151
+ /** The shadow ray starts this far off the hit, along its normal. */
152
+ const SHADOW_OFFSET = 0.02;
153
+ const SHADOW_FAR = 2000;
154
+ const NO_CACHE_RADIANCE = 0;
155
+
156
+ /** The six-axis sky light at a normal, weighted by the normal's squared components (the ambient cube). */
157
+ function ambientCube(
158
+ cube: ITracedReflectionStage["skyIrradiance"],
159
+ normal: Node<"vec3">,
160
+ ): Node<"vec3"> {
161
+ if (cube === undefined || cube.length !== 6) return vec3(NO_CACHE_RADIANCE);
162
+ const face = (index: number) => vec3(...(cube[index] as [number, number, number]));
163
+ const squared = normal.mul(normal);
164
+ return select(normal.x.greaterThanEqual(0), face(0), face(1))
165
+ .mul(squared.x)
166
+ .add(select(normal.y.greaterThanEqual(0), face(2), face(3)).mul(squared.y))
167
+ .add(select(normal.z.greaterThanEqual(0), face(4), face(5)).mul(squared.z));
168
+ }
169
+ /** Share of a metal's colour, per unit of roughness, that a hit takes as diffuse: calibrated on the rough metal sphere. */
170
+ const METAL_DIFFUSE = 0.12;
171
+
172
+ /**
173
+ * The delta to add to the lit frame (zero where nothing is traced or the ray finds nothing): for a metal the
174
+ * traced hit replaces the frame's own environment reflection, for a dielectric it adds the Fresnel-weighted
175
+ * reflection. Multiply by `trace.weight(roughness)` before adding. The same shape `ssr` returns.
176
+ */
177
+ export function tracedReflections(stage: ITracedReflectionStage): Node<"vec4"> {
178
+ const { camera, trace } = stage;
179
+ const live = (read: () => number): Node<"float"> =>
180
+ uniform(read()).onRenderUpdate(read) as Node<"float">;
181
+ const projection = (index: number) => live(() => camera.projectionMatrix.elements[index] ?? 0);
182
+ const [p00, p11, p02, p12, p22, p32] = [0, 5, 8, 9, 10, 14].map(projection) as [
183
+ Node<"float">,
184
+ Node<"float">,
185
+ Node<"float">,
186
+ Node<"float">,
187
+ Node<"float">,
188
+ Node<"float">,
189
+ ];
190
+ const world = (index: number) => live(() => camera.matrixWorld.elements[index] ?? 0);
191
+ const column = (first: number) => vec3(world(first), world(first + 1), world(first + 2));
192
+ const [right, up, back, at] = [column(0), column(4), column(8), column(12)];
193
+ const direction = (v: Node<"vec3">): Node<"vec3"> =>
194
+ right.mul(v.x).add(up.mul(v.y)).add(back.mul(v.z));
195
+
196
+ const sun = stage.sun;
197
+ const sunDirection = vec3(
198
+ live(() => sunVector(sun)[0]),
199
+ live(() => sunVector(sun)[1]),
200
+ live(() => sunVector(sun)[2]),
201
+ );
202
+ const sunRadiance = vec3(
203
+ live(() => (sun === undefined ? 0 : (sun.color.r * sun.intensity) / Math.PI)),
204
+ live(() => (sun === undefined ? 0 : (sun.color.g * sun.intensity) / Math.PI)),
205
+ live(() => (sun === undefined ? 0 : (sun.color.b * sun.intensity) / Math.PI)),
206
+ );
207
+
208
+ const lamps = stage.lamps ?? [];
209
+ const lampDirect = (
210
+ lamp: PointLight | SpotLight,
211
+ hit: ReturnType<typeof trace.trace>,
212
+ ): Node<"vec3"> => {
213
+ const lampAt = vec3(
214
+ live(() => lamp.position.x),
215
+ live(() => lamp.position.y),
216
+ live(() => lamp.position.z),
217
+ );
218
+ // three's lamp: colour times candela over the squared distance, windowed to its cut-off distance, then the BRDF's 1/PI.
219
+ const radiance = vec3(
220
+ live(() => (lamp.color.r * lamp.intensity) / Math.PI),
221
+ live(() => (lamp.color.g * lamp.intensity) / Math.PI),
222
+ live(() => (lamp.color.b * lamp.intensity) / Math.PI),
223
+ );
224
+ const cutoff = live(() => lamp.distance);
225
+ const toLamp = lampAt.sub(hit.position);
226
+ const distance = max(length(toLamp), 0.01);
227
+ const direction = toLamp.div(distance);
228
+ const facing = max(dot(hit.normal, direction), 0);
229
+ const window = select(
230
+ cutoff.greaterThan(0),
231
+ pow(saturate(float(1).sub(pow(distance.div(cutoff), 4))), 2),
232
+ float(1),
233
+ );
234
+ let cone: Node<"float"> = float(1);
235
+ if ("angle" in lamp) {
236
+ const axis = vec3(
237
+ live(() => lamp.target.position.x - lamp.position.x),
238
+ live(() => lamp.target.position.y - lamp.position.y),
239
+ live(() => lamp.target.position.z - lamp.position.z),
240
+ );
241
+ const outerCos = live(() => Math.cos(lamp.angle));
242
+ const innerCos = live(() => Math.cos(lamp.angle * (1 - lamp.penumbra)));
243
+ cone = smoothstep(outerCos, innerCos, dot(direction.negate(), normalize(axis)));
244
+ }
245
+ const blocked = float(0).toVar();
246
+ If(facing.greaterThan(0), () => {
247
+ const shadow = trace.trace({
248
+ origin: hit.position.add(hit.normal.mul(SHADOW_OFFSET)),
249
+ direction,
250
+ far: distance.sub(SHADOW_OFFSET),
251
+ anyHit: true,
252
+ });
253
+ blocked.assign(shadow.hit);
254
+ });
255
+ return radiance
256
+ .mul(facing.mul(window).mul(cone).div(distance.mul(distance)))
257
+ .mul(float(1).sub(blocked));
258
+ };
259
+
260
+ const graph = Fn(() => {
261
+ const coordinate = uv();
262
+ const result = vec4(0, 0, 0, 0).toVar();
263
+ const depth = stage.depth.r;
264
+ const roughness = stage.roughness.g;
265
+ const gate = depth.lessThan(1).and(roughness.lessThan(trace.maxRoughnessToTrace));
266
+ If(gate, () => {
267
+ // View-space position from depth: depth is (A z + B) / -z, so z = -B / (depth + A).
268
+ const z = p32.negate().div(depth.add(p22));
269
+ const position = vec3(
270
+ z.negate().mul(coordinate.x.mul(2).sub(1).add(p02)).div(p00),
271
+ z.negate().mul(float(1).sub(coordinate.y).mul(2).sub(1).add(p12)).div(p11),
272
+ z,
273
+ );
274
+ const normalView = normalize(stage.normal.xyz);
275
+ const incidentView = normalize(position);
276
+ const normalWorld = direction(normalView);
277
+ const reflected = normalize(reflect(direction(incidentView), normalWorld));
278
+ const start = max(float(START_OFFSET), z.negate().mul(START_OFFSET_PER_METRE));
279
+ const origin = direction(position).add(at).add(normalWorld.mul(start));
280
+ const hit = trace.trace({
281
+ origin,
282
+ direction: reflected,
283
+ ...(stage.maxDistance === undefined ? {} : { far: stage.maxDistance }),
284
+ });
285
+ If(hit.hit.greaterThan(0), () => {
286
+ // The hit's light, in scene units: the sun through one shadow ray, the cache for everything else.
287
+ const facing = max(dot(hit.normal, sunDirection), 0);
288
+ const blocked = float(0).toVar();
289
+ If(facing.greaterThan(0), () => {
290
+ const shadow = trace.trace({
291
+ origin: hit.position.add(hit.normal.mul(SHADOW_OFFSET)),
292
+ direction: sunDirection,
293
+ far: SHADOW_FAR,
294
+ anyHit: true,
295
+ });
296
+ blocked.assign(shadow.hit);
297
+ });
298
+ const sunDirect = sunRadiance.mul(facing).mul(float(1).sub(blocked));
299
+ const direct = lamps.reduce((sum, lamp) => sum.add(lampDirect(lamp, hit)), sunDirect);
300
+ const indirect =
301
+ giCache.irradiance?.(hit.position, hit.normal) ??
302
+ ambientCube(stage.skyIrradiance, hit.normal);
303
+ // A metal has almost no diffuse colour: the sun and the bounce light it only a little, more the rougher it is
304
+ // (Unreal's reflection hit shows a rough metal as a dark shape, not black and not a lit diffuse one).
305
+ const metalShare = hit.roughness.mul(METAL_DIFFUSE);
306
+ const diffuse = hit.albedo.mul(float(1).sub(hit.metalness.mul(float(1).sub(metalShare))));
307
+ const radiance = diffuse.mul(direct.add(indirect)).add(hit.emissive).mul(stage.gain);
308
+
309
+ const facingView = clamp(dot(normalView, incidentView.negate()), 0, 1);
310
+ const schlick = float(1).sub(facingView).pow(5);
311
+ const metalness = clamp(stage.metalness.r, 0, 1);
312
+ const tint = stage.albedo === undefined ? vec3(1) : stage.albedo.rgb;
313
+ const f0 = mix(vec3(0.04), tint, metalness);
314
+ const fresnel = f0.add(vec3(1).sub(f0).mul(schlick));
315
+ const frame = stage.base.rgb;
316
+ const delta = mix(radiance.mul(fresnel), radiance.mul(fresnel).sub(frame), metalness);
317
+ const reach =
318
+ stage.maxDistance === undefined
319
+ ? float(1)
320
+ : float(1).sub(smoothstep(FADE_FROM, 1, hit.distance.div(stage.maxDistance)));
321
+ result.assign(vec4(delta.mul(reach), 0));
322
+ });
323
+ });
324
+ return result;
325
+ })();
326
+
327
+ const node = rtt(graph, null, null, { type: HalfFloatType }) as Node<"vec4"> & {
328
+ setResolutionScale?: (scale: number) => unknown;
329
+ };
330
+ if (stage.resolutionScale !== undefined && stage.resolutionScale !== 1)
331
+ node.setResolutionScale?.(stage.resolutionScale);
332
+ return node;
333
+ }
334
+
335
+ const toSun = [0, 1, 0] as [number, number, number];
336
+ /** The unit vector from the scene toward the sun: where the light sits, seen from where it aims. */
337
+ function sunVector(sun: DirectionalLight | undefined): readonly [number, number, number] {
338
+ if (sun === undefined) return toSun;
339
+ const x = sun.position.x - sun.target.position.x;
340
+ const y = sun.position.y - sun.target.position.y;
341
+ const z = sun.position.z - sun.target.position.z;
342
+ const length = Math.hypot(x, y, z) || 1;
343
+ return [x / length, y / length, z / length];
344
+ }