@threenative/core 0.3.12 → 0.3.13

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 (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
@@ -22,6 +22,7 @@ import {
22
22
  vec4,
23
23
  } from "three/tsl";
24
24
  import { StorageBufferAttribute } from "three/webgpu";
25
+ import { readLaunchValue } from "../debug.js";
25
26
 
26
27
  /**
27
28
  * The hierarchical-depth (pyramid) occlusion test, and the max-distance pyramid it reads.
@@ -64,21 +65,12 @@ export type OcclusionMode = "off" | "measure";
64
65
  * browser asks with `?tnOcclusion=measure`, and a test sets the global.
65
66
  */
66
67
  export function occlusionMode(): OcclusionMode {
67
- const host = globalThis as {
68
- process?: { env?: Record<string, unknown> };
69
- __tnOcclusion?: unknown;
70
- location?: { search?: string };
71
- };
72
- const fromEnv = host.process?.env?.[OCCLUSION_FLAG];
73
- const query = host.location?.search;
74
68
  const asked =
75
- typeof fromEnv === "string" && fromEnv !== ""
76
- ? fromEnv
77
- : typeof query === "string"
78
- ? (/[?&]tnOcclusion=([^&]*)/u.exec(query)?.[1] ?? "")
79
- : typeof host.__tnOcclusion === "string"
80
- ? host.__tnOcclusion
81
- : "";
69
+ readLaunchValue({
70
+ environment: OCCLUSION_FLAG,
71
+ global: "__tnOcclusion",
72
+ query: "tnOcclusion",
73
+ }) ?? "";
82
74
  const value = asked.trim().toLowerCase();
83
75
  if (value === "" || value === "0" || value === "off" || value === "false") return "off";
84
76
  if (value === "measure" || value === "1" || value === "true") return "measure";
@@ -0,0 +1,202 @@
1
+ // Generated for you. Measure actual source radiance; unreadable environments stay unknown.
2
+ import {
3
+ type Color,
4
+ EquirectangularReflectionMapping,
5
+ FloatType,
6
+ LinearSRGBColorSpace,
7
+ NoColorSpace,
8
+ RGBAFormat,
9
+ SRGBColorSpace,
10
+ type Scene,
11
+ type Texture,
12
+ UnsignedByteType,
13
+ } from "three";
14
+
15
+ export interface IEnvironmentMeasurement {
16
+ readonly status: "measured" | "unknown";
17
+ readonly meanRadiance: number | null;
18
+ readonly meanRGB: readonly [number, number, number] | null;
19
+ readonly reason: string;
20
+ }
21
+ const unknown = (reason: string): IEnvironmentMeasurement => ({
22
+ status: "unknown",
23
+ meanRadiance: null,
24
+ meanRGB: null,
25
+ reason,
26
+ });
27
+ const linear = (value: number) =>
28
+ value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
29
+
30
+ function validSize(value: unknown): value is number {
31
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
32
+ }
33
+ interface IReadableSource {
34
+ readonly status: "source";
35
+ readonly data: Uint8Array | Float32Array;
36
+ readonly width: number;
37
+ readonly height: number;
38
+ readonly bytes: boolean;
39
+ }
40
+ function readSource(
41
+ texture: Texture,
42
+ maxSourceTexels: number,
43
+ ): IReadableSource | IEnvironmentMeasurement {
44
+ if (texture.mapping !== EquirectangularReflectionMapping)
45
+ return unknown("Only CPU-readable equirectangular source radiance is qualified.");
46
+ const image: unknown = texture.image;
47
+ if (
48
+ image === null ||
49
+ typeof image !== "object" ||
50
+ !("data" in image) ||
51
+ !("width" in image) ||
52
+ !("height" in image)
53
+ )
54
+ return unknown("Environment source pixels are not CPU-readable; no radiance was inferred.");
55
+ const { data, width, height } = image;
56
+ if (!validSize(width) || !validSize(height))
57
+ return unknown("Environment source dimensions are invalid.");
58
+ if (width * height > maxSourceTexels)
59
+ return unknown("Environment CPU sample budget exceeded; no radiance was inferred.");
60
+ if (texture.format !== RGBAFormat)
61
+ return unknown("Only explicit RGBA source samples are qualified.");
62
+ const bytes = texture.type === UnsignedByteType && data instanceof Uint8Array;
63
+ const floats = texture.type === FloatType && data instanceof Float32Array;
64
+ if (!bytes && !floats) return unknown("Environment source sample type is not qualified.");
65
+ if (data.length !== width * height * 4)
66
+ return unknown("Environment source samples do not match their dimensions.");
67
+ if (
68
+ !new Set<string>([NoColorSpace, LinearSRGBColorSpace, SRGBColorSpace]).has(texture.colorSpace)
69
+ )
70
+ return unknown("Environment source color-space conversion is not qualified.");
71
+ return { status: "source", data, width, height, bytes };
72
+ }
73
+
74
+ function accumulate(source: IReadableSource, srgb: boolean) {
75
+ const { data, width, height, bytes } = source;
76
+ const sums = [0, 0, 0];
77
+ const weights = Array.from(
78
+ { length: height },
79
+ (_, y) => Math.cos((Math.PI * y) / height) - Math.cos((Math.PI * (y + 1)) / height),
80
+ );
81
+ for (let offset = 0; offset < data.length; offset += 4) {
82
+ const weight = weights[Math.floor(offset / (width * 4))] ?? 0;
83
+ for (let channel = 0; channel < 3; channel += 1) {
84
+ const sample = data[offset + channel];
85
+ if (sample === undefined || !Number.isFinite(sample) || sample < 0)
86
+ return unknown("Environment radiance samples must be finite and nonnegative.");
87
+ const value = bytes ? sample / 255 : sample;
88
+ sums[channel] = (sums[channel] ?? 0) + (srgb ? linear(value) : value) * weight;
89
+ }
90
+ }
91
+ return { sums, weightSum: weights.reduce((a, b) => a + b, 0) * width };
92
+ }
93
+
94
+ /**
95
+ * CPU-readable equirectangular source radiance only; no DOM/canvas or invented JPEG mean.
96
+ * Rows are weighted by their exact spherical solid angle, rather than overweighting the poles.
97
+ * Arbitrary GPU/compressed/HTML/cube sources remain explicitly unknown until separately proven.
98
+ * @example const m = measureEnvironment(scene, 2048);
99
+ */
100
+ export function measureEnvironment(scene: Scene, maxSourceTexels: number): IEnvironmentMeasurement {
101
+ if (!Number.isSafeInteger(maxSourceTexels) || maxSourceTexels < 1)
102
+ throw new Error("Environment CPU sample budget must be a positive safe integer.");
103
+ const texture = scene.environment;
104
+ if (texture === null)
105
+ return {
106
+ status: "measured",
107
+ meanRadiance: 0,
108
+ meanRGB: [0, 0, 0],
109
+ reason: "No environment is bound.",
110
+ };
111
+ if (!Number.isFinite(scene.environmentIntensity) || scene.environmentIntensity < 0)
112
+ return unknown("Environment intensity must be finite and nonnegative.");
113
+ const source = readSource(texture, maxSourceTexels);
114
+ if (source.status !== "source") return source;
115
+ const accumulated = accumulate(source, texture.colorSpace === SRGBColorSpace);
116
+ if ("status" in accumulated) return accumulated;
117
+ const { sums, weightSum } = accumulated;
118
+ const meanRGB = sums.map((sum) => (sum / weightSum) * scene.environmentIntensity) as [
119
+ number,
120
+ number,
121
+ number,
122
+ ];
123
+ const meanRadiance = meanRGB[0] * 0.2126 + meanRGB[1] * 0.7152 + meanRGB[2] * 0.0722;
124
+ if (!meanRGB.every(Number.isFinite) || !Number.isFinite(meanRadiance))
125
+ return unknown("Environment radiance accumulation overflowed.");
126
+ return {
127
+ status: "measured",
128
+ meanRadiance,
129
+ meanRGB,
130
+ reason: "Solid-angle-weighted linear source radiance, with active environment intensity.",
131
+ };
132
+ }
133
+
134
+ /**
135
+ * What a contribution report reads: the backlight's gains and the source-texel limit.
136
+ *
137
+ * Exported because `reportEnvironmentContribution` takes it — a public function with a private
138
+ * parameter type cannot be called from a game, which is how its example failed to compile.
139
+ */
140
+ export interface IContributionControls {
141
+ readonly darkThreshold: number;
142
+ readonly rimGain: number;
143
+ readonly fillGain: number;
144
+ readonly fillAdmitted: boolean;
145
+ readonly fillColor: Color;
146
+ readonly maxSourceTexels: number;
147
+ }
148
+ function fillReport(options: IContributionControls) {
149
+ const blackColorOverride = options.fillColor.toArray().every((value) => value === 0);
150
+ let reason = "analytic fill enabled by caller; contribution still needs pixel qualification";
151
+ if (!options.fillAdmitted) reason = "not admitted by this qualification";
152
+ else if (options.fillGain === 0) reason = "disabled by fillGain override";
153
+ else if (blackColorOverride) reason = "disabled by black fillColor override";
154
+ return {
155
+ requestedGain: options.fillGain,
156
+ admitted: options.fillAdmitted,
157
+ effectiveGain: options.fillAdmitted ? options.fillGain : 0,
158
+ color: options.fillColor.toArray(),
159
+ blackColorOverride,
160
+ reason,
161
+ };
162
+ }
163
+ /**
164
+ * Overrides change the look, never whether its source contribution is measured/reported.
165
+ * @example
166
+ * reportEnvironmentContribution(scene, {
167
+ * darkThreshold: 0.02, fillAdmitted: true, fillColor: new Color(1, 1, 1), fillGain: 0.4,
168
+ * maxSourceTexels: 2048, rimGain: 0.6,
169
+ * });
170
+ */
171
+ export function reportEnvironmentContribution(
172
+ scene: Scene,
173
+ options: IContributionControls,
174
+ measurement?: IEnvironmentMeasurement,
175
+ ) {
176
+ if (
177
+ ![
178
+ options.darkThreshold,
179
+ options.rimGain,
180
+ options.fillGain,
181
+ ...options.fillColor.toArray(),
182
+ ].every((value) => Number.isFinite(value) && value >= 0)
183
+ )
184
+ throw new Error("Backlight measurement controls must be finite and nonnegative.");
185
+ const measured = measurement ?? measureEnvironment(scene, options.maxSourceTexels);
186
+ const dark =
187
+ measured.meanRadiance === null ? null : measured.meanRadiance <= options.darkThreshold;
188
+ const environmentState =
189
+ scene.environment === null ? "missing" : dark === null ? "unknown" : dark ? "dark" : "bright";
190
+ const report = {
191
+ ...measured,
192
+ scope: "scene environment source availability; not material-specific reflected contribution",
193
+ environmentState,
194
+ ibl: dark === null ? "unknown" : dark ? "non-contributing" : "contributing",
195
+ analyticFill: fillReport(options),
196
+ rimGain: options.rimGain,
197
+ fillGain: options.fillGain,
198
+ darkThreshold: options.darkThreshold,
199
+ };
200
+ console.info(`TN_ENVIRONMENT_CONTRIBUTION:${JSON.stringify(report)}`);
201
+ return report;
202
+ }
@@ -0,0 +1,44 @@
1
+ // Generated for you. Spherical accumulation of bounded linear source samples.
2
+ import type { IEnvironmentMeasurement } from "./environmentContribution.js";
3
+ const WIDTH = 64;
4
+ const HEIGHT = 32;
5
+ function unmeasured(reason: string): IEnvironmentMeasurement {
6
+ return { status: "unknown", meanRadiance: null, meanRGB: null, reason };
7
+ }
8
+ /**
9
+ * The mean radiance and colour of a bounded linear sample, or `unknown` with the reason.
10
+ *
11
+ * @situation turn an environment readback into the radiance a material's fill light needs
12
+ * @situation know why an environment sample could not be measured
13
+ * @constraint the sample must be the qualified 64x32 float RGBA readback; anything else is refused by name
14
+ * @example const m = sampledRadiance(readback, 1);
15
+ */
16
+ export function sampledRadiance(samples: unknown, intensity: number): IEnvironmentMeasurement {
17
+ if (!(samples instanceof Float32Array) || samples.length !== WIDTH * HEIGHT * 4)
18
+ return unmeasured("GPU readback did not provide the qualified float RGBA sample layout.");
19
+ const sums = [0, 0, 0];
20
+ const weights = Array.from(
21
+ { length: HEIGHT },
22
+ (_, y) => Math.cos((Math.PI * y) / HEIGHT) - Math.cos((Math.PI * (y + 1)) / HEIGHT),
23
+ );
24
+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0) * WIDTH;
25
+ for (const [offset, value] of samples.entries()) {
26
+ const channel = offset % 4;
27
+ if (channel === 3) continue;
28
+ if (!Number.isFinite(value) || value < 0)
29
+ return unmeasured("GPU radiance samples must be finite and nonnegative.");
30
+ const weight = weights[Math.floor(offset / (WIDTH * 4))] ?? 0;
31
+ sums[channel] = (sums[channel] ?? 0) + value * weight;
32
+ }
33
+ const meanRGB = sums.map((sum) => (sum / totalWeight) * intensity) as [number, number, number];
34
+ const meanRadiance = meanRGB[0] * 0.2126 + meanRGB[1] * 0.7152 + meanRGB[2] * 0.0722;
35
+ if (!meanRGB.every(Number.isFinite) || !Number.isFinite(meanRadiance))
36
+ return unmeasured("GPU radiance accumulation overflowed.");
37
+ return {
38
+ status: "measured",
39
+ meanRGB,
40
+ meanRadiance,
41
+ reason:
42
+ "Estimated linear scene-environment source radiance from 64x32 GPU samples, spherical row weighting and active intensity; not material-specific BRDF contribution.",
43
+ };
44
+ }
@@ -0,0 +1,56 @@
1
+ // Generated for you. Weak ownership and full provenance guard successful source estimates.
2
+ import type { Scene, Texture } from "three";
3
+ import type { IEnvironmentSample } from "./environmentSampling.js";
4
+ import { environmentSnapshotCurrent } from "./environmentSnapshot.js";
5
+ const samples = new WeakMap<object, WeakMap<Texture, IEnvironmentSample>>();
6
+ /**
7
+ * The sample this renderer took of `scene`'s environment, if it is still current.
8
+ *
9
+ * @situation skip a second environment readback in the same frame
10
+ * @constraint a sample whose source texture or intensity moved is dropped, so a stale one never reaches a material
11
+ * @example const hit = cachedEnvironmentSample(renderer, scene);
12
+ */
13
+ export function cachedEnvironmentSample(
14
+ renderer: object,
15
+ scene: Scene,
16
+ ): IEnvironmentSample | undefined {
17
+ if (scene.environment === null) return undefined;
18
+ const sample = samples.get(renderer)?.get(scene.environment);
19
+ return sample !== undefined && environmentSnapshotCurrent(scene, sample)
20
+ ? copySample(sample)
21
+ : undefined;
22
+ }
23
+ /**
24
+ * Remembers `sample` as this renderer's reading of `scene`'s environment.
25
+ *
26
+ * @situation reuse one environment readback across the materials of a scene
27
+ * @example cacheEnvironmentSample(renderer, scene, sample);
28
+ */
29
+ export function cacheEnvironmentSample(
30
+ renderer: object,
31
+ scene: Scene,
32
+ sample: IEnvironmentSample,
33
+ ): void {
34
+ if (
35
+ sample.source === null ||
36
+ sample.measurement.status !== "measured" ||
37
+ !environmentSnapshotCurrent(scene, sample)
38
+ )
39
+ return;
40
+ let byTexture = samples.get(renderer);
41
+ if (byTexture === undefined) {
42
+ byTexture = new WeakMap();
43
+ samples.set(renderer, byTexture);
44
+ }
45
+ byTexture.set(sample.source, copySample(sample));
46
+ }
47
+
48
+ function copySample(sample: IEnvironmentSample): IEnvironmentSample {
49
+ return {
50
+ ...sample,
51
+ measurement: {
52
+ ...sample.measurement,
53
+ meanRGB: sample.measurement.meanRGB === null ? null : [...sample.measurement.meanRGB],
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,201 @@
1
+ // Generated for you. A bounded source-radiance estimate, never a material/BRDF measurement.
2
+ import {
3
+ FloatType,
4
+ LinearSRGBColorSpace,
5
+ NoToneMapping,
6
+ RGBAFormat,
7
+ RenderTarget,
8
+ type Scene,
9
+ type ToneMapping,
10
+ } from "three";
11
+ import { texture, uv } from "three/tsl";
12
+ import { MeshBasicNodeMaterial, QuadMesh, type WebGPURenderer } from "three/webgpu";
13
+ import { type IEnvironmentMeasurement, measureEnvironment } from "./environmentContribution.js";
14
+ import { sampledRadiance } from "./environmentRadiance.js";
15
+ import { cacheEnvironmentSample, cachedEnvironmentSample } from "./environmentSampleCache.js";
16
+ import {
17
+ type IEnvironmentSourceSnapshot,
18
+ captureEnvironmentSnapshot,
19
+ environmentSnapshotCurrent,
20
+ samplingSourceSupported,
21
+ } from "./environmentSnapshot.js";
22
+ import {
23
+ type IMaterialLightingEnvironment,
24
+ isWebGLFallbackRenderer,
25
+ materialLightingEnabled,
26
+ } from "./gate.js";
27
+ export interface IEnvironmentSample extends IEnvironmentSourceSnapshot {
28
+ readonly measurement: IEnvironmentMeasurement;
29
+ }
30
+ /** Editable bound on asynchronous readback, independent of the engine startup deadline. */
31
+ const ENVIRONMENT_READBACK_TIMEOUT_MS = 1000;
32
+ const WIDTH = 64;
33
+ const HEIGHT = 32;
34
+ /**
35
+ * Measures and samples the scene's real environment on the GPU, bounded by a readback deadline.
36
+ *
37
+ * @situation measure what a scene's environment actually contributes without stalling the frame
38
+ * @situation give a material's fill light the environment's own radiance
39
+ * @constraint off unless the renderer is the admitted high-tier WebGPU lane; every refusal is reported by name
40
+ * @constraint the readback is abandoned after the deadline and the frame keeps the previous answer
41
+ * @example const sample = await sampleEnvironment(renderer, scene, env);
42
+ */
43
+ export async function sampleEnvironment(
44
+ renderer: unknown,
45
+ scene: Scene,
46
+ environment: IMaterialLightingEnvironment,
47
+ ): Promise<IEnvironmentSample> {
48
+ const snapshot = captureEnvironmentSnapshot(scene);
49
+ const { source, intensity } = snapshot;
50
+ const result = (measurement: IEnvironmentMeasurement): IEnvironmentSample => ({
51
+ ...snapshot,
52
+ measurement,
53
+ });
54
+ const unknown = (reason: string): IEnvironmentSample =>
55
+ result({ status: "unknown", meanRadiance: null, meanRGB: null, reason });
56
+ if (!materialLightingEnabled("high", environment) || isWebGLFallbackRenderer(renderer))
57
+ return unknown("Environment GPU sampling is unqualified on this platform/renderer.");
58
+ if (source === null) return result(measureEnvironment(scene, WIDTH * HEIGHT));
59
+ if (!samplingSourceSupported(source))
60
+ return unknown("Environment mapping/color-space is not qualified for the bounded GPU sample.");
61
+ if (!Number.isFinite(intensity) || intensity < 0)
62
+ return unknown("Environment intensity must be finite and nonnegative.");
63
+ if (!samplingRendererSupported(renderer))
64
+ return unknown("Raw Three.js renderer lacks the qualified sampling/readback methods.");
65
+ const raw = renderer as WebGPURenderer;
66
+ const cached = cachedEnvironmentSample(raw, scene);
67
+ if (cached !== undefined) return cached;
68
+ let state: {
69
+ target: ReturnType<WebGPURenderer["getRenderTarget"]>;
70
+ face: number;
71
+ mip: number;
72
+ toneMapping: ToneMapping;
73
+ colorSpace: string;
74
+ autoClear: boolean;
75
+ };
76
+ try {
77
+ state = {
78
+ target: raw.getRenderTarget(),
79
+ face: raw.getActiveCubeFace(),
80
+ mip: raw.getActiveMipmapLevel(),
81
+ toneMapping: raw.toneMapping,
82
+ colorSpace: raw.outputColorSpace,
83
+ autoClear: raw.autoClear,
84
+ };
85
+ } catch {
86
+ return unknown("Raw renderer state could not be saved; GPU sample skipped.");
87
+ }
88
+ const target = new RenderTarget(WIDTH, HEIGHT, {
89
+ type: FloatType,
90
+ format: RGBAFormat,
91
+ depthBuffer: false,
92
+ stencilBuffer: false,
93
+ });
94
+ target.texture.colorSpace = LinearSRGBColorSpace;
95
+ const material = new MeshBasicNodeMaterial();
96
+ material.toneMapped = false;
97
+ material.colorNode = texture(source, uv()).rgb;
98
+ const quad = new QuadMesh(material);
99
+ let pendingReadback: Promise<unknown> | undefined;
100
+ let readbackSettled = false;
101
+ let cleaned = false;
102
+ function cleanup(): void {
103
+ if (cleaned) return;
104
+ cleaned = true;
105
+ try {
106
+ material.dispose();
107
+ } finally {
108
+ target.dispose();
109
+ }
110
+ // QuadMesh geometry is shared and borrowed.
111
+ }
112
+ try {
113
+ try {
114
+ raw.toneMapping = NoToneMapping;
115
+ raw.outputColorSpace = LinearSRGBColorSpace;
116
+ raw.autoClear = true;
117
+ raw.setRenderTarget(target, 0, 0);
118
+ quad.render(raw);
119
+ pendingReadback = Promise.resolve(
120
+ raw.readRenderTargetPixelsAsync(target, 0, 0, WIDTH, HEIGHT),
121
+ ).then(
122
+ (value) => {
123
+ readbackSettled = true;
124
+ return value;
125
+ },
126
+ (error) => {
127
+ readbackSettled = true;
128
+ throw error;
129
+ },
130
+ );
131
+ } finally {
132
+ // No async gap while the shared renderer points at our scratch target.
133
+ try {
134
+ raw.setRenderTarget(state.target, state.face, state.mip);
135
+ } finally {
136
+ raw.toneMapping = state.toneMapping;
137
+ raw.outputColorSpace = state.colorSpace;
138
+ raw.autoClear = state.autoClear;
139
+ }
140
+ }
141
+ const outcome = await waitForReadback(pendingReadback);
142
+ if (outcome.timedOut)
143
+ return unknown(
144
+ `Environment GPU readback exceeded ${ENVIRONMENT_READBACK_TIMEOUT_MS} ms budget; scratch resources retained until readback settles.`,
145
+ );
146
+ const samples = outcome.samples;
147
+ if (!environmentSnapshotCurrent(scene, snapshot))
148
+ return unknown(
149
+ "Environment source/content/interpretation changed while GPU readback was pending; sample refused.",
150
+ );
151
+ const sampled = result(sampledRadiance(samples, intensity));
152
+ cacheEnvironmentSample(raw, scene, sampled);
153
+ return sampled;
154
+ } catch (error) {
155
+ return unknown(`Environment GPU sample/readback unavailable: ${String(error)}`);
156
+ } finally {
157
+ finishSampleCleanup(pendingReadback, readbackSettled, cleanup);
158
+ }
159
+ }
160
+
161
+ async function waitForReadback(
162
+ readback: Promise<unknown>,
163
+ ): Promise<{ timedOut: true } | { timedOut: false; samples: unknown }> {
164
+ let timer: ReturnType<typeof setTimeout> | undefined;
165
+ try {
166
+ return await Promise.race([
167
+ readback.then((samples) => ({ timedOut: false as const, samples })),
168
+ new Promise<{ timedOut: true }>((resolve) => {
169
+ timer = setTimeout(() => resolve({ timedOut: true }), ENVIRONMENT_READBACK_TIMEOUT_MS);
170
+ }),
171
+ ]);
172
+ } finally {
173
+ if (timer !== undefined) clearTimeout(timer);
174
+ }
175
+ }
176
+
177
+ function samplingRendererSupported(renderer: unknown): renderer is WebGPURenderer {
178
+ return (
179
+ renderer !== null &&
180
+ typeof renderer === "object" &&
181
+ Reflect.get(renderer, "isWebGPURenderer") === true &&
182
+ [
183
+ "render",
184
+ "getRenderTarget",
185
+ "getActiveCubeFace",
186
+ "getActiveMipmapLevel",
187
+ "setRenderTarget",
188
+ "readRenderTargetPixelsAsync",
189
+ ].every((name) => typeof Reflect.get(renderer, name) === "function")
190
+ );
191
+ }
192
+
193
+ function finishSampleCleanup(
194
+ readback: Promise<unknown> | undefined,
195
+ settled: boolean,
196
+ cleanup: () => void,
197
+ ): void {
198
+ // Timeout permits startup, but GPU work may still reference the target/material.
199
+ if (readback !== undefined && !settled) void readback.then(cleanup, cleanup);
200
+ else cleanup();
201
+ }
@@ -0,0 +1,71 @@
1
+ // Generated for you. Borrowed environment provenance for stale-readback rejection.
2
+ import {
3
+ EquirectangularReflectionMapping,
4
+ LinearSRGBColorSpace,
5
+ NoColorSpace,
6
+ SRGBColorSpace,
7
+ type Scene,
8
+ type Texture,
9
+ } from "three";
10
+ /** Provenance stays outside the printable measurement; source/image references are borrowed. */
11
+ export interface IEnvironmentSourceSnapshot {
12
+ readonly source: Texture | null;
13
+ readonly intensity: number;
14
+ readonly textureVersion: number | null;
15
+ readonly sourceVersion: number | null;
16
+ readonly colorSpace: string | null;
17
+ readonly mapping: number | null;
18
+ readonly image: unknown;
19
+ }
20
+ /**
21
+ * The provenance of a scene's environment: which texture, at which intensity, in which colour space.
22
+ *
23
+ * @situation reject an environment readback that belongs to a different sky
24
+ * @example const snapshot = captureEnvironmentSnapshot(scene);
25
+ */
26
+ export function captureEnvironmentSnapshot(scene: Scene): IEnvironmentSourceSnapshot {
27
+ const source = scene.environment;
28
+ return {
29
+ source,
30
+ intensity: scene.environmentIntensity,
31
+ textureVersion: source?.version ?? null,
32
+ sourceVersion: source?.source.version ?? null,
33
+ colorSpace: source?.colorSpace ?? null,
34
+ mapping: source?.mapping ?? null,
35
+ image: source?.image ?? null,
36
+ };
37
+ }
38
+ /**
39
+ * Whether the scene's environment still matches the snapshot a sample was taken from.
40
+ *
41
+ * @situation hold a material's fill light to the sky that is on screen now
42
+ * @example if (environmentSnapshotCurrent(scene, snapshot)) draw(snapshot);
43
+ */
44
+ export function environmentSnapshotCurrent(
45
+ scene: Scene,
46
+ snapshot: IEnvironmentSourceSnapshot,
47
+ ): boolean {
48
+ const source = scene.environment;
49
+ return (
50
+ source === snapshot.source &&
51
+ scene.environmentIntensity === snapshot.intensity &&
52
+ (source?.version ?? null) === snapshot.textureVersion &&
53
+ (source?.source.version ?? null) === snapshot.sourceVersion &&
54
+ (source?.colorSpace ?? null) === snapshot.colorSpace &&
55
+ (source?.mapping ?? null) === snapshot.mapping &&
56
+ (source?.image ?? null) === snapshot.image
57
+ );
58
+ }
59
+
60
+ /**
61
+ * Whether an environment texture's mapping and colour space are qualified for the bounded GPU sample.
62
+ *
63
+ * @situation know why an environment was not sampled on the GPU
64
+ * @example if (samplingSourceSupported(source)) sample(source);
65
+ */
66
+ export function samplingSourceSupported(source: NonNullable<Scene["environment"]>): boolean {
67
+ return (
68
+ source.mapping === EquirectangularReflectionMapping &&
69
+ new Set<string>([NoColorSpace, LinearSRGBColorSpace, SRGBColorSpace]).has(source.colorSpace)
70
+ );
71
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Which renderers may run the material-lighting lane, and whether a renderer is running three's
3
+ * WebGL backend behind a WebGPU wrapper.
4
+ *
5
+ * Both questions are asked by the environment sampling mechanism beside this file, and both were
6
+ * answered in each template's `quality.ts` — twelve copies of the same predicate, so a fix to one
7
+ * left eleven kits admitting a renderer the fix refused. The tier they compare is the caller's, so
8
+ * a game that wants a different admission rule passes its own tier; nothing here decides how
9
+ * anything looks.
10
+ */
11
+ import type { QualityTier } from "../../look/quality.js";
12
+
13
+ /** First admitted material lane: high desktop hardware WebGPU in the browser only. */
14
+ export interface IMaterialLightingEnvironment {
15
+ readonly web: boolean;
16
+ readonly rendererKind: string;
17
+ readonly mobile?: boolean;
18
+ readonly software?: boolean;
19
+ readonly webglFallback?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Whether `tier` may run the material-lighting lane in `environment`.
24
+ *
25
+ * @situation decide whether this renderer is the admitted material lane
26
+ * @constraint high tier, browser, hardware WebGPU, not mobile, not software, not a WebGL fallback
27
+ * @example if (materialLightingEnabled("high", env)) lightMaterials();
28
+ */
29
+ export function materialLightingEnabled(
30
+ tier: QualityTier,
31
+ environment: IMaterialLightingEnvironment,
32
+ ): boolean {
33
+ return (
34
+ tier === "high" &&
35
+ environment.web &&
36
+ environment.rendererKind === "webgpu" &&
37
+ environment.mobile !== true &&
38
+ environment.software !== true &&
39
+ environment.webglFallback !== true
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Whether a `WebGPURenderer` wrapper is running three's WebGL backend behind it.
45
+ *
46
+ * @situation refuse a GPU-only lane on a WebGL fallback instead of drawing something wrong
47
+ * @example if (isWebGLFallbackRenderer(renderer)) skipMaterialLane();
48
+ */
49
+ export function isWebGLFallbackRenderer(renderer: unknown): boolean {
50
+ if (renderer === null || typeof renderer !== "object") return false;
51
+ const backend = Reflect.get(renderer, "backend");
52
+ return (
53
+ backend !== null &&
54
+ typeof backend === "object" &&
55
+ Reflect.get(backend, "isWebGLBackend") === true
56
+ );
57
+ }