@threenative/core 0.3.5 → 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-Bj8G1wmD.d.ts → game-cb99J-YE.d.ts} +112 -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 +22445 -12411
  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 +59 -10
  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 +544 -106
  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 +40 -6
  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 +69 -12
  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,237 @@
1
+ import { type IStageGpuReading, SHADOW_STAGE, stageGpuReading } from "../render-pass-budget.js";
2
+ import { BudgetLadder, type BudgetVerdict, type IBudgetWindow } from "./budget-ladder.js";
3
+
4
+ /** `TN_SHADOW_TIER` lines carry one report as JSON. */
5
+ export const SHADOW_TIER_MARKER = "TN_SHADOW_TIER";
6
+
7
+ /** The shadow filter tiers, cheapest first. The game maps each one to its own sample counts. */
8
+ export const SHADOW_FILTER_TIERS = ["low", "medium", "high"] as const;
9
+
10
+ export type ShadowFilterTier = (typeof SHADOW_FILTER_TIERS)[number];
11
+
12
+ /** `sg.ShadowQuality` of the Unreal level each tier follows (Low, Medium, Epic). */
13
+ const UNREAL_QUALITY: Readonly<Record<ShadowFilterTier, 0 | 1 | 3>> = {
14
+ high: 3,
15
+ low: 0,
16
+ medium: 1,
17
+ };
18
+
19
+ /** The stage the engines name the shadow passes' GPU time by: the owned engine's shadow segment, three's `Shadow Map` passes. */
20
+ export const SHADOW_STAGES: readonly string[] = [SHADOW_STAGE];
21
+
22
+ export interface IShadowFilterReport {
23
+ /** The tier after this window. */
24
+ readonly tier: ShadowFilterTier;
25
+ /** Read-only: the `sg.ShadowQuality` the tier follows. */
26
+ readonly shadowQuality: 0 | 1 | 3;
27
+ /** Mean GPU milliseconds of the shadow stages over the window, or `undefined` when no frame resolved. */
28
+ readonly windowMs: number | undefined;
29
+ /** Mean whole-frame GPU milliseconds over the window. */
30
+ readonly frameMs: number | undefined;
31
+ /** The frame period the frame is compared with. */
32
+ readonly periodMs: number;
33
+ /** The frame period less its headroom. */
34
+ readonly targetMs: number;
35
+ /** Resolved whole-frame readings in the window. */
36
+ readonly samples: number;
37
+ /** Which of the named `stages` resolved in the window. Empty when a stage name is wrong: that reads as 0 ms. */
38
+ readonly stagesSeen: readonly string[];
39
+ readonly stepped: ShadowFilterTier | undefined;
40
+ /** Two consecutive frames over the period moved the tier without the change-period gate. */
41
+ readonly panic: boolean;
42
+ /** The frame was over the target but the shadow passes could not absorb the overage even at zero cost. */
43
+ readonly notBlamed: boolean;
44
+ readonly verdict: BudgetVerdict;
45
+ readonly explicit: boolean;
46
+ readonly reason: string;
47
+ }
48
+
49
+ export interface IShadowFilterBudgetOptions {
50
+ /** The tier the game starts at: its quality tier's shadow row. */
51
+ readonly tier: ShadowFilterTier;
52
+ /** The game set the sample counts itself: the watcher reports and never changes them. */
53
+ readonly explicit?: boolean;
54
+ /** Names of the render passes that are shadow work. Default {@link SHADOW_STAGES}. */
55
+ readonly stages?: readonly string[];
56
+ /** The frame period in milliseconds, such as 1000 / 60. The whole GPU frame is compared with it. */
57
+ readonly framePeriodMs: number;
58
+ /** Frames per report when nothing moves. Default 120. */
59
+ readonly windowFrames?: number;
60
+ /** Called after the watcher moved the tier; the game rebuilds its filter with that tier's samples. */
61
+ readonly onStep?: (tier: ShadowFilterTier, report: IShadowFilterReport) => void;
62
+ /** Where `TN_SHADOW_TIER` lines go. Default `console.info`. */
63
+ readonly report?: (line: string) => void;
64
+ /** Reads a renderer's newest GPU reading. Default `stageGpuReading`; a test supplies its own. */
65
+ readonly read?: (renderer: unknown) => IStageGpuReading | undefined;
66
+ }
67
+
68
+ /**
69
+ * Steps a game's soft-shadow tier down when the whole GPU frame stays over the frame period, and
70
+ * back up when the frame has room. The rule is Unreal's DynamicRenderScaling heuristic with the
71
+ * settings of its virtual shadow map budget (`VirtualShadowMapArray.cpp:831-845`: a linear model,
72
+ * 5% headroom, a 1% change threshold). Unreal's own budget compares the stage with a time the
73
+ * author sets, which is off by default and depends on the GPU clock, so this one compares the
74
+ * frame with its period. A frame that is slow for another reason keeps its shadows: the tier steps
75
+ * only when the shadow passes could absorb the overage even at zero cost. The game owns what each
76
+ * tier draws and rebuilds its filter on each step.
77
+ *
78
+ * Two frames over the period step the tier down at once. Otherwise a move waits 8 frames after the
79
+ * last one, and a tier that failed is retried after a longer wait each time. A game that sets the
80
+ * sample counts itself keeps them: the report says the frame is over and nothing changes. An
81
+ * adapter without timestamp queries resolves no frame, so every window is unobserved and the tier
82
+ * holds. Redraw cost keeps its own levers in `VirtualShadowNode`.
83
+ *
84
+ * @situation soft shadow filter costs too much on a weak GPU
85
+ * @situation step the shadow quality tier when the GPU frame goes over the frame period
86
+ * @situation shadow quality tier that follows the hardware
87
+ * @constraint the game rebuilds its filter with the tier's sample counts on each step; this class draws nothing
88
+ * @constraint timestamp queries are needed: without them every window is unobserved and the tier holds
89
+ * @constraint the rule reads the whole GPU frame and the `Shadow` stage, which the receiver filter inside the colour pass is not part of
90
+ * @override explicit: true keeps the game's own sample counts and reports an over-budget frame
91
+ * @alias virtual shadow map scalability
92
+ * @alias sg.ShadowQuality
93
+ * @example
94
+ * const filter = new ShadowFilterBudget({ tier: "high", framePeriodMs: 1000 / 60, onStep: (tier) => { light.shadow.filterNode = filterFor(tier); } });
95
+ * ctx.beforeRender(() => filter.observeRenderer(ctx.renderer.raw));
96
+ */
97
+ export class ShadowFilterBudget {
98
+ readonly #ladder: BudgetLadder<ShadowFilterTier>;
99
+ readonly #options: IShadowFilterBudgetOptions;
100
+ readonly #read: (renderer: unknown) => IStageGpuReading | undefined;
101
+ readonly #stages: readonly string[];
102
+ readonly #seen = new Set<string>();
103
+ #lastFrame = -1;
104
+ #last: IShadowFilterReport | undefined;
105
+ #reportedOver = false;
106
+
107
+ constructor(options: IShadowFilterBudgetOptions) {
108
+ this.#options = options;
109
+ this.#read = options.read ?? stageGpuReading;
110
+ const stages = options.stages ?? SHADOW_STAGES;
111
+ if (stages.length === 0)
112
+ throw new RangeError("ShadowFilterBudget stages must name at least one render pass.");
113
+ this.#stages = stages;
114
+ this.#ladder = new BudgetLadder<ShadowFilterTier>({
115
+ framePeriodMs: options.framePeriodMs,
116
+ levels: SHADOW_FILTER_TIERS,
117
+ // The virtual shadow map budget's own settings (VirtualShadowMapArray.cpp:834-841).
118
+ rule: { changeThreshold: 0.01, headroom: 0.05, model: "linear" },
119
+ start: options.tier,
120
+ ...(options.explicit === undefined ? {} : { explicit: options.explicit }),
121
+ ...(options.windowFrames === undefined ? {} : { windowFrames: options.windowFrames }),
122
+ });
123
+ }
124
+
125
+ get tier(): ShadowFilterTier {
126
+ return this.#ladder.level;
127
+ }
128
+
129
+ get shadowQuality(): 0 | 1 | 3 {
130
+ return UNREAL_QUALITY[this.#ladder.level];
131
+ }
132
+
133
+ /** The newest closed window's report, or `undefined` before the first closes. */
134
+ lastReport(): IShadowFilterReport | undefined {
135
+ return this.#last;
136
+ }
137
+
138
+ /**
139
+ * Feeds one loop frame: the shadow stages' GPU milliseconds and the whole frame's, or `undefined`
140
+ * for a frame whose GPU time has not resolved. Returns the report when this frame closes a window.
141
+ */
142
+ observe(ms: number | undefined, frameMs?: number): IShadowFilterReport | undefined {
143
+ const window = this.#ladder.observe(ms, frameMs);
144
+ if (window === undefined) return undefined;
145
+ const report = this.#toReport(window);
146
+ this.#last = report;
147
+ this.#seen.clear();
148
+ this.#emit(report);
149
+ if (window.stepped !== undefined) this.#options.onStep?.(window.stepped, report);
150
+ return report;
151
+ }
152
+
153
+ /**
154
+ * Feeds one loop frame from an instrumented renderer: the named shadow stages of the newest whole
155
+ * resolved frame, counted once however many loop frames wait for the next one.
156
+ */
157
+ observeRenderer(renderer: unknown): IShadowFilterReport | undefined {
158
+ const reading = this.#read(renderer);
159
+ if (reading === undefined || reading.frame === this.#lastFrame) return this.observe(undefined);
160
+ this.#lastFrame = reading.frame;
161
+ let ms = 0;
162
+ for (const name of this.#stages) {
163
+ const stageMs = reading.stages[name];
164
+ if (stageMs === undefined) continue;
165
+ this.#seen.add(name);
166
+ ms += stageMs;
167
+ }
168
+ return this.observe(ms, reading.total);
169
+ }
170
+
171
+ #toReport(window: IBudgetWindow<ShadowFilterTier>): IShadowFilterReport {
172
+ const after = window.stepped ?? window.level;
173
+ const ms = window.windowMs;
174
+ const frame = window.frameMs;
175
+ const shown = frame === undefined ? "" : `frame ${Number(frame.toFixed(2))} ms`;
176
+ const target = `${Number(window.targetMs.toFixed(2))} ms target (period ${Number(window.periodMs.toFixed(2))} ms)`;
177
+ let reason: string;
178
+ if (frame === undefined) {
179
+ reason = `no GPU time resolved in the window (${window.frames} frames): ${window.level} holds`;
180
+ } else if (window.stepped !== undefined && window.verdict === "over") {
181
+ reason = `${shown} is over the ${target}${window.panic ? " for 2 frames in a row" : ""}: stepped down to ${window.stepped}`;
182
+ } else if (window.stepped !== undefined) {
183
+ reason = `${shown} leaves room under the ${target}: stepped up to ${window.stepped}`;
184
+ } else if (window.verdict === "over") {
185
+ const base = `${shown} is over the ${target}`;
186
+ reason = window.explicit
187
+ ? `${base}: sample counts are set by the game and stay at ${window.level}`
188
+ : window.notBlamed
189
+ ? `${base}, and the shadow passes (${Number((ms ?? 0).toFixed(2))} ms) are too small to absorb it: ${window.level} holds`
190
+ : `${base} and ${window.level} is the cheapest tier or the move waits for the change period`;
191
+ } else {
192
+ reason = `${shown} is inside the ${target}`;
193
+ }
194
+ return {
195
+ explicit: window.explicit,
196
+ frameMs: frame === undefined ? undefined : Number(frame.toFixed(3)),
197
+ notBlamed: window.notBlamed,
198
+ panic: window.panic,
199
+ periodMs: Number(window.periodMs.toFixed(3)),
200
+ reason,
201
+ samples: window.samples,
202
+ shadowQuality: UNREAL_QUALITY[after],
203
+ stagesSeen: [...this.#seen],
204
+ stepped: window.stepped,
205
+ targetMs: Number(window.targetMs.toFixed(3)),
206
+ tier: after,
207
+ verdict: window.verdict,
208
+ windowMs: ms === undefined ? undefined : Number(ms.toFixed(3)),
209
+ };
210
+ }
211
+
212
+ /** A step, or the first window an explicit tier spends over budget, is worth a line. */
213
+ #emit(report: IShadowFilterReport): void {
214
+ const over = report.verdict === "over";
215
+ const worth = report.stepped !== undefined || (report.explicit && over && !this.#reportedOver);
216
+ this.#reportedOver = over;
217
+ if (!worth) return;
218
+ const line = `${SHADOW_TIER_MARKER} ${JSON.stringify(report)}`;
219
+ if (this.#options.report !== undefined) this.#options.report(line);
220
+ else console.info(line);
221
+ }
222
+ }
223
+
224
+ /** Parses a `TN_SHADOW_TIER` line back into its report, or `undefined` for any other line. */
225
+ export function readShadowTierMarker(line: string): IShadowFilterReport | undefined {
226
+ if (!line.startsWith(`${SHADOW_TIER_MARKER} `)) return undefined;
227
+ try {
228
+ const parsed: unknown = JSON.parse(line.slice(SHADOW_TIER_MARKER.length + 1));
229
+ if (typeof parsed !== "object" || parsed === null) return undefined;
230
+ const report = parsed as IShadowFilterReport;
231
+ return SHADOW_FILTER_TIERS.includes(report.tier) && typeof report.periodMs === "number"
232
+ ? report
233
+ : undefined;
234
+ } catch {
235
+ return undefined;
236
+ }
237
+ }
@@ -0,0 +1,194 @@
1
+ import {
2
+ BackSide,
3
+ type Camera,
4
+ CubeCamera,
5
+ HalfFloatType,
6
+ Mesh,
7
+ NoToneMapping,
8
+ type RenderTarget,
9
+ Scene,
10
+ SphereGeometry,
11
+ type Texture,
12
+ type Vector3,
13
+ } from "three";
14
+ import {
15
+ CubeRenderTarget,
16
+ MeshBasicNodeMaterial,
17
+ type Node,
18
+ PMREMGenerator,
19
+ type WebGPURenderer,
20
+ } from "three/webgpu";
21
+
22
+ export interface ISkyCaptureOptions {
23
+ /** Power of two, at least 16. Defaults to 128 texels per face. */
24
+ readonly resolution?: number;
25
+ /** Radians, in [0, PI]. Defaults to one degree; equality does not refresh. */
26
+ readonly thresholdAngle?: number;
27
+ /** Integer in [1, 6]. Defaults to one (six frames per capture). */
28
+ readonly facesPerFrame?: number;
29
+ readonly lowerHemisphereBlack?: boolean;
30
+ }
31
+
32
+ /** GPU-free sun movement and cube-face budget. An in-flight capture always finishes. */
33
+ export class SkyCaptureSchedule {
34
+ readonly #threshold: number;
35
+ readonly #budget: number;
36
+ #sun: Vector3 | undefined;
37
+ #face = 6;
38
+
39
+ constructor(options: Pick<ISkyCaptureOptions, "thresholdAngle" | "facesPerFrame"> = {}) {
40
+ this.#threshold = options.thresholdAngle ?? Math.PI / 180;
41
+ this.#budget = options.facesPerFrame ?? 1;
42
+ if (!Number.isFinite(this.#threshold) || this.#threshold < 0 || this.#threshold > Math.PI) {
43
+ throw new Error("SkyCapture.thresholdAngle must be radians in [0, PI].");
44
+ }
45
+ if (!Number.isInteger(this.#budget) || this.#budget < 1 || this.#budget > 6) {
46
+ throw new Error("SkyCapture.facesPerFrame must be an integer in [1, 6].");
47
+ }
48
+ }
49
+
50
+ next(sunDirection: Vector3): number[] {
51
+ const length = Math.hypot(sunDirection.x, sunDirection.y, sunDirection.z);
52
+ if (!Number.isFinite(length) || length === 0) {
53
+ throw new Error("SkyCapture sun direction must be finite and nonzero.");
54
+ }
55
+ const sun = sunDirection.clone().divideScalar(length);
56
+ if (this.#face === 6) {
57
+ if (this.#sun !== undefined && this.#sun.angleTo(sun) <= this.#threshold) return [];
58
+ this.#sun = sun;
59
+ this.#face = 0;
60
+ }
61
+ const start = this.#face;
62
+ this.#face = Math.min(6, start + this.#budget);
63
+ return Array.from({ length: this.#face - start }, (_, i) => start + i);
64
+ }
65
+
66
+ /** Retry the entire capture after a render or filter failure. */
67
+ reset(): void {
68
+ this.#sun = undefined;
69
+ this.#face = 6;
70
+ }
71
+ }
72
+
73
+ /** Capture game-owned radiance and prefilter it with Three.js WebGPU PMREM.
74
+ * @situation light a scene from a procedural sky when its sun moves
75
+ * @constraint call update once per frame on an initialized WebGPURenderer; assign texture after it returns true
76
+ * @constraint sky nodes use a world-space view direction; keep supplied sky resources alive until dispose
77
+ * @example const capture = new SkyCapture(renderer, skyNode); if (capture.update(sun)) scene.environment = capture.texture;
78
+ */
79
+ export class SkyCapture {
80
+ readonly cubeTarget: CubeRenderTarget;
81
+ readonly #renderer: WebGPURenderer;
82
+ readonly #scene: Scene;
83
+ readonly #camera: CubeCamera;
84
+ readonly #schedule: SkyCaptureSchedule;
85
+ readonly #mask: Scene | undefined;
86
+ readonly #maskMesh: Mesh<SphereGeometry, MeshBasicNodeMaterial> | undefined;
87
+ #pmrem: PMREMGenerator | undefined;
88
+ #filtered: RenderTarget | undefined;
89
+ #disposed = false;
90
+
91
+ constructor(
92
+ renderer: WebGPURenderer,
93
+ sky: Scene | Node<"vec3">,
94
+ options: ISkyCaptureOptions = {},
95
+ ) {
96
+ this.#schedule = new SkyCaptureSchedule(options);
97
+ const size = options.resolution ?? 128;
98
+ if (!Number.isSafeInteger(size) || size < 16 || !Number.isInteger(Math.log2(size))) {
99
+ throw new Error("SkyCapture.resolution must be a power of two >= 16.");
100
+ }
101
+ if (
102
+ options.lowerHemisphereBlack !== undefined &&
103
+ typeof options.lowerHemisphereBlack !== "boolean"
104
+ ) {
105
+ throw new Error("SkyCapture.lowerHemisphereBlack must be boolean.");
106
+ }
107
+ if (!(sky instanceof Scene) && sky?.isNode !== true)
108
+ throw new Error("SkyCapture requires a Scene or sky node.");
109
+ this.#renderer = renderer;
110
+ this.#scene = sky instanceof Scene ? sky : new Scene();
111
+ if (!(sky instanceof Scene)) this.#scene.backgroundNode = sky;
112
+ this.cubeTarget = new CubeRenderTarget(size, { type: HalfFloatType, generateMipmaps: false });
113
+ this.#camera = new CubeCamera(0.1, 1000, this.cubeTarget);
114
+ // Behaviour reference only: Engine/Source/Runtime/Engine/Private/Components/SkyLightComponent.cpp
115
+ // and Engine/Source/Runtime/Renderer/Private/ReflectionEnvironmentCapture.cpp (Unreal 5.8.3).
116
+ if (options.lowerHemisphereBlack !== false) {
117
+ this.#mask = new Scene();
118
+ this.#maskMesh = new Mesh(
119
+ new SphereGeometry(1, 32, 16, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2),
120
+ new MeshBasicNodeMaterial({
121
+ color: 0,
122
+ side: BackSide,
123
+ depthTest: false,
124
+ depthWrite: false,
125
+ toneMapped: false,
126
+ }),
127
+ );
128
+ this.#mask.add(this.#maskMesh);
129
+ }
130
+ }
131
+
132
+ get texture(): Texture | undefined {
133
+ return this.#filtered?.texture;
134
+ }
135
+
136
+ /** True only when all six faces have been captured and PMREM-filtered. No timer. */
137
+ update(sunDirection: Vector3): boolean {
138
+ if (this.#disposed) throw new Error("SkyCapture is disposed.");
139
+ const faces = this.#schedule.next(sunDirection);
140
+ if (faces.length === 0) return false;
141
+ const raw = this.#renderer;
142
+ const target = raw.getRenderTarget();
143
+ const face = raw.getActiveCubeFace();
144
+ const mip = raw.getActiveMipmapLevel();
145
+ const xr = raw.xr.enabled;
146
+ const autoClear = raw.autoClear;
147
+ const toneMapping = raw.toneMapping;
148
+ const mrt = raw.getMRT();
149
+ try {
150
+ raw.xr.enabled = false;
151
+ raw.toneMapping = NoToneMapping;
152
+ // A nested scene pass's named MRT outputs do not belong to the cube target.
153
+ raw.setMRT(null);
154
+ if (this.#camera.coordinateSystem !== raw.coordinateSystem) {
155
+ this.#camera.coordinateSystem = raw.coordinateSystem;
156
+ this.#camera.updateCoordinateSystem();
157
+ }
158
+ this.#camera.updateMatrixWorld(true);
159
+ for (const index of faces) {
160
+ const camera = this.#camera.children[index] as Camera;
161
+ raw.setRenderTarget(this.cubeTarget, index, 0);
162
+ raw.autoClear = true;
163
+ raw.render(this.#scene, camera);
164
+ if (this.#mask !== undefined) {
165
+ raw.autoClear = false;
166
+ raw.render(this.#mask, camera);
167
+ }
168
+ }
169
+ if (faces[faces.length - 1] !== 5) return false;
170
+ this.#pmrem ??= new PMREMGenerator(raw);
171
+ this.#filtered = this.#pmrem.fromCubemap(this.cubeTarget.texture, this.#filtered);
172
+ return true;
173
+ } catch (error) {
174
+ this.#schedule.reset();
175
+ throw error;
176
+ } finally {
177
+ raw.setRenderTarget(target, face, mip);
178
+ raw.setMRT(mrt);
179
+ raw.xr.enabled = xr;
180
+ raw.autoClear = autoClear;
181
+ raw.toneMapping = toneMapping;
182
+ }
183
+ }
184
+
185
+ dispose(): void {
186
+ if (this.#disposed) return;
187
+ this.#disposed = true;
188
+ this.cubeTarget.dispose();
189
+ this.#filtered?.dispose();
190
+ this.#pmrem?.dispose();
191
+ this.#maskMesh?.geometry.dispose();
192
+ this.#maskMesh?.material.dispose();
193
+ }
194
+ }