@threenative/core 0.3.11 → 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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,352 @@
1
+ import { SRGBColorSpace, EquirectangularReflectionMapping, NoColorSpace, LinearSRGBColorSpace, RenderTarget, RGBAFormat, FloatType, NoToneMapping, UnsignedByteType } from 'three';
2
+ import { texture, uv } from 'three/tsl';
3
+ import { MeshBasicNodeMaterial, QuadMesh } from 'three/webgpu';
4
+
5
+ // src/render/environment/environmentContribution.ts
6
+ var unknown = (reason) => ({
7
+ status: "unknown",
8
+ meanRadiance: null,
9
+ meanRGB: null,
10
+ reason
11
+ });
12
+ var linear = (value) => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
13
+ function validSize(value) {
14
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
15
+ }
16
+ function readSource(texture2, maxSourceTexels) {
17
+ if (texture2.mapping !== EquirectangularReflectionMapping)
18
+ return unknown("Only CPU-readable equirectangular source radiance is qualified.");
19
+ const image = texture2.image;
20
+ if (image === null || typeof image !== "object" || !("data" in image) || !("width" in image) || !("height" in image))
21
+ return unknown("Environment source pixels are not CPU-readable; no radiance was inferred.");
22
+ const { data, width, height } = image;
23
+ if (!validSize(width) || !validSize(height))
24
+ return unknown("Environment source dimensions are invalid.");
25
+ if (width * height > maxSourceTexels)
26
+ return unknown("Environment CPU sample budget exceeded; no radiance was inferred.");
27
+ if (texture2.format !== RGBAFormat)
28
+ return unknown("Only explicit RGBA source samples are qualified.");
29
+ const bytes = texture2.type === UnsignedByteType && data instanceof Uint8Array;
30
+ const floats = texture2.type === FloatType && data instanceof Float32Array;
31
+ if (!bytes && !floats) return unknown("Environment source sample type is not qualified.");
32
+ if (data.length !== width * height * 4)
33
+ return unknown("Environment source samples do not match their dimensions.");
34
+ if (!(/* @__PURE__ */ new Set([NoColorSpace, LinearSRGBColorSpace, SRGBColorSpace])).has(texture2.colorSpace))
35
+ return unknown("Environment source color-space conversion is not qualified.");
36
+ return { status: "source", data, width, height, bytes };
37
+ }
38
+ function accumulate(source, srgb) {
39
+ const { data, width, height, bytes } = source;
40
+ const sums = [0, 0, 0];
41
+ const weights = Array.from(
42
+ { length: height },
43
+ (_, y) => Math.cos(Math.PI * y / height) - Math.cos(Math.PI * (y + 1) / height)
44
+ );
45
+ for (let offset = 0; offset < data.length; offset += 4) {
46
+ const weight = weights[Math.floor(offset / (width * 4))] ?? 0;
47
+ for (let channel = 0; channel < 3; channel += 1) {
48
+ const sample = data[offset + channel];
49
+ if (sample === void 0 || !Number.isFinite(sample) || sample < 0)
50
+ return unknown("Environment radiance samples must be finite and nonnegative.");
51
+ const value = bytes ? sample / 255 : sample;
52
+ sums[channel] = (sums[channel] ?? 0) + (srgb ? linear(value) : value) * weight;
53
+ }
54
+ }
55
+ return { sums, weightSum: weights.reduce((a, b) => a + b, 0) * width };
56
+ }
57
+ function measureEnvironment(scene, maxSourceTexels) {
58
+ if (!Number.isSafeInteger(maxSourceTexels) || maxSourceTexels < 1)
59
+ throw new Error("Environment CPU sample budget must be a positive safe integer.");
60
+ const texture2 = scene.environment;
61
+ if (texture2 === null)
62
+ return {
63
+ status: "measured",
64
+ meanRadiance: 0,
65
+ meanRGB: [0, 0, 0],
66
+ reason: "No environment is bound."
67
+ };
68
+ if (!Number.isFinite(scene.environmentIntensity) || scene.environmentIntensity < 0)
69
+ return unknown("Environment intensity must be finite and nonnegative.");
70
+ const source = readSource(texture2, maxSourceTexels);
71
+ if (source.status !== "source") return source;
72
+ const accumulated = accumulate(source, texture2.colorSpace === SRGBColorSpace);
73
+ if ("status" in accumulated) return accumulated;
74
+ const { sums, weightSum } = accumulated;
75
+ const meanRGB = sums.map((sum) => sum / weightSum * scene.environmentIntensity);
76
+ const meanRadiance = meanRGB[0] * 0.2126 + meanRGB[1] * 0.7152 + meanRGB[2] * 0.0722;
77
+ if (!meanRGB.every(Number.isFinite) || !Number.isFinite(meanRadiance))
78
+ return unknown("Environment radiance accumulation overflowed.");
79
+ return {
80
+ status: "measured",
81
+ meanRadiance,
82
+ meanRGB,
83
+ reason: "Solid-angle-weighted linear source radiance, with active environment intensity."
84
+ };
85
+ }
86
+ function fillReport(options) {
87
+ const blackColorOverride = options.fillColor.toArray().every((value) => value === 0);
88
+ let reason = "analytic fill enabled by caller; contribution still needs pixel qualification";
89
+ if (!options.fillAdmitted) reason = "not admitted by this qualification";
90
+ else if (options.fillGain === 0) reason = "disabled by fillGain override";
91
+ else if (blackColorOverride) reason = "disabled by black fillColor override";
92
+ return {
93
+ requestedGain: options.fillGain,
94
+ admitted: options.fillAdmitted,
95
+ effectiveGain: options.fillAdmitted ? options.fillGain : 0,
96
+ color: options.fillColor.toArray(),
97
+ blackColorOverride,
98
+ reason
99
+ };
100
+ }
101
+ function reportEnvironmentContribution(scene, options, measurement) {
102
+ if (![
103
+ options.darkThreshold,
104
+ options.rimGain,
105
+ options.fillGain,
106
+ ...options.fillColor.toArray()
107
+ ].every((value) => Number.isFinite(value) && value >= 0))
108
+ throw new Error("Backlight measurement controls must be finite and nonnegative.");
109
+ const measured = measurement ?? measureEnvironment(scene, options.maxSourceTexels);
110
+ const dark = measured.meanRadiance === null ? null : measured.meanRadiance <= options.darkThreshold;
111
+ const environmentState = scene.environment === null ? "missing" : dark === null ? "unknown" : dark ? "dark" : "bright";
112
+ const report = {
113
+ ...measured,
114
+ scope: "scene environment source availability; not material-specific reflected contribution",
115
+ environmentState,
116
+ ibl: dark === null ? "unknown" : dark ? "non-contributing" : "contributing",
117
+ analyticFill: fillReport(options),
118
+ rimGain: options.rimGain,
119
+ fillGain: options.fillGain,
120
+ darkThreshold: options.darkThreshold
121
+ };
122
+ console.info(`TN_ENVIRONMENT_CONTRIBUTION:${JSON.stringify(report)}`);
123
+ return report;
124
+ }
125
+
126
+ // src/render/environment/environmentRadiance.ts
127
+ var WIDTH = 64;
128
+ var HEIGHT = 32;
129
+ function unmeasured(reason) {
130
+ return { status: "unknown", meanRadiance: null, meanRGB: null, reason };
131
+ }
132
+ function sampledRadiance(samples2, intensity) {
133
+ if (!(samples2 instanceof Float32Array) || samples2.length !== WIDTH * HEIGHT * 4)
134
+ return unmeasured("GPU readback did not provide the qualified float RGBA sample layout.");
135
+ const sums = [0, 0, 0];
136
+ const weights = Array.from(
137
+ { length: HEIGHT },
138
+ (_, y) => Math.cos(Math.PI * y / HEIGHT) - Math.cos(Math.PI * (y + 1) / HEIGHT)
139
+ );
140
+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0) * WIDTH;
141
+ for (const [offset, value] of samples2.entries()) {
142
+ const channel = offset % 4;
143
+ if (channel === 3) continue;
144
+ if (!Number.isFinite(value) || value < 0)
145
+ return unmeasured("GPU radiance samples must be finite and nonnegative.");
146
+ const weight = weights[Math.floor(offset / (WIDTH * 4))] ?? 0;
147
+ sums[channel] = (sums[channel] ?? 0) + value * weight;
148
+ }
149
+ const meanRGB = sums.map((sum) => sum / totalWeight * intensity);
150
+ const meanRadiance = meanRGB[0] * 0.2126 + meanRGB[1] * 0.7152 + meanRGB[2] * 0.0722;
151
+ if (!meanRGB.every(Number.isFinite) || !Number.isFinite(meanRadiance))
152
+ return unmeasured("GPU radiance accumulation overflowed.");
153
+ return {
154
+ status: "measured",
155
+ meanRGB,
156
+ meanRadiance,
157
+ reason: "Estimated linear scene-environment source radiance from 64x32 GPU samples, spherical row weighting and active intensity; not material-specific BRDF contribution."
158
+ };
159
+ }
160
+ function captureEnvironmentSnapshot(scene) {
161
+ const source = scene.environment;
162
+ return {
163
+ source,
164
+ intensity: scene.environmentIntensity,
165
+ textureVersion: source?.version ?? null,
166
+ sourceVersion: source?.source.version ?? null,
167
+ colorSpace: source?.colorSpace ?? null,
168
+ mapping: source?.mapping ?? null,
169
+ image: source?.image ?? null
170
+ };
171
+ }
172
+ function environmentSnapshotCurrent(scene, snapshot) {
173
+ const source = scene.environment;
174
+ return source === snapshot.source && scene.environmentIntensity === snapshot.intensity && (source?.version ?? null) === snapshot.textureVersion && (source?.source.version ?? null) === snapshot.sourceVersion && (source?.colorSpace ?? null) === snapshot.colorSpace && (source?.mapping ?? null) === snapshot.mapping && (source?.image ?? null) === snapshot.image;
175
+ }
176
+ function samplingSourceSupported(source) {
177
+ return source.mapping === EquirectangularReflectionMapping && (/* @__PURE__ */ new Set([NoColorSpace, LinearSRGBColorSpace, SRGBColorSpace])).has(source.colorSpace);
178
+ }
179
+
180
+ // src/render/environment/environmentSampleCache.ts
181
+ var samples = /* @__PURE__ */ new WeakMap();
182
+ function cachedEnvironmentSample(renderer, scene) {
183
+ if (scene.environment === null) return void 0;
184
+ const sample = samples.get(renderer)?.get(scene.environment);
185
+ return sample !== void 0 && environmentSnapshotCurrent(scene, sample) ? copySample(sample) : void 0;
186
+ }
187
+ function cacheEnvironmentSample(renderer, scene, sample) {
188
+ if (sample.source === null || sample.measurement.status !== "measured" || !environmentSnapshotCurrent(scene, sample))
189
+ return;
190
+ let byTexture = samples.get(renderer);
191
+ if (byTexture === void 0) {
192
+ byTexture = /* @__PURE__ */ new WeakMap();
193
+ samples.set(renderer, byTexture);
194
+ }
195
+ byTexture.set(sample.source, copySample(sample));
196
+ }
197
+ function copySample(sample) {
198
+ return {
199
+ ...sample,
200
+ measurement: {
201
+ ...sample.measurement,
202
+ meanRGB: sample.measurement.meanRGB === null ? null : [...sample.measurement.meanRGB]
203
+ }
204
+ };
205
+ }
206
+
207
+ // src/render/environment/gate.ts
208
+ function materialLightingEnabled(tier, environment) {
209
+ return tier === "high" && environment.web && environment.rendererKind === "webgpu" && environment.mobile !== true && environment.software !== true && environment.webglFallback !== true;
210
+ }
211
+ function isWebGLFallbackRenderer(renderer) {
212
+ if (renderer === null || typeof renderer !== "object") return false;
213
+ const backend = Reflect.get(renderer, "backend");
214
+ return backend !== null && typeof backend === "object" && Reflect.get(backend, "isWebGLBackend") === true;
215
+ }
216
+
217
+ // src/render/environment/environmentSampling.ts
218
+ var ENVIRONMENT_READBACK_TIMEOUT_MS = 1e3;
219
+ var WIDTH2 = 64;
220
+ var HEIGHT2 = 32;
221
+ async function sampleEnvironment(renderer, scene, environment) {
222
+ const snapshot = captureEnvironmentSnapshot(scene);
223
+ const { source, intensity } = snapshot;
224
+ const result = (measurement) => ({
225
+ ...snapshot,
226
+ measurement
227
+ });
228
+ const unknown2 = (reason) => result({ status: "unknown", meanRadiance: null, meanRGB: null, reason });
229
+ if (!materialLightingEnabled("high", environment) || isWebGLFallbackRenderer(renderer))
230
+ return unknown2("Environment GPU sampling is unqualified on this platform/renderer.");
231
+ if (source === null) return result(measureEnvironment(scene, WIDTH2 * HEIGHT2));
232
+ if (!samplingSourceSupported(source))
233
+ return unknown2("Environment mapping/color-space is not qualified for the bounded GPU sample.");
234
+ if (!Number.isFinite(intensity) || intensity < 0)
235
+ return unknown2("Environment intensity must be finite and nonnegative.");
236
+ if (!samplingRendererSupported(renderer))
237
+ return unknown2("Raw Three.js renderer lacks the qualified sampling/readback methods.");
238
+ const raw = renderer;
239
+ const cached = cachedEnvironmentSample(raw, scene);
240
+ if (cached !== void 0) return cached;
241
+ let state;
242
+ try {
243
+ state = {
244
+ target: raw.getRenderTarget(),
245
+ face: raw.getActiveCubeFace(),
246
+ mip: raw.getActiveMipmapLevel(),
247
+ toneMapping: raw.toneMapping,
248
+ colorSpace: raw.outputColorSpace,
249
+ autoClear: raw.autoClear
250
+ };
251
+ } catch {
252
+ return unknown2("Raw renderer state could not be saved; GPU sample skipped.");
253
+ }
254
+ const target = new RenderTarget(WIDTH2, HEIGHT2, {
255
+ type: FloatType,
256
+ format: RGBAFormat,
257
+ depthBuffer: false,
258
+ stencilBuffer: false
259
+ });
260
+ target.texture.colorSpace = LinearSRGBColorSpace;
261
+ const material = new MeshBasicNodeMaterial();
262
+ material.toneMapped = false;
263
+ material.colorNode = texture(source, uv()).rgb;
264
+ const quad = new QuadMesh(material);
265
+ let pendingReadback;
266
+ let readbackSettled = false;
267
+ let cleaned = false;
268
+ function cleanup() {
269
+ if (cleaned) return;
270
+ cleaned = true;
271
+ try {
272
+ material.dispose();
273
+ } finally {
274
+ target.dispose();
275
+ }
276
+ }
277
+ try {
278
+ try {
279
+ raw.toneMapping = NoToneMapping;
280
+ raw.outputColorSpace = LinearSRGBColorSpace;
281
+ raw.autoClear = true;
282
+ raw.setRenderTarget(target, 0, 0);
283
+ quad.render(raw);
284
+ pendingReadback = Promise.resolve(
285
+ raw.readRenderTargetPixelsAsync(target, 0, 0, WIDTH2, HEIGHT2)
286
+ ).then(
287
+ (value) => {
288
+ readbackSettled = true;
289
+ return value;
290
+ },
291
+ (error) => {
292
+ readbackSettled = true;
293
+ throw error;
294
+ }
295
+ );
296
+ } finally {
297
+ try {
298
+ raw.setRenderTarget(state.target, state.face, state.mip);
299
+ } finally {
300
+ raw.toneMapping = state.toneMapping;
301
+ raw.outputColorSpace = state.colorSpace;
302
+ raw.autoClear = state.autoClear;
303
+ }
304
+ }
305
+ const outcome = await waitForReadback(pendingReadback);
306
+ if (outcome.timedOut)
307
+ return unknown2(
308
+ `Environment GPU readback exceeded ${ENVIRONMENT_READBACK_TIMEOUT_MS} ms budget; scratch resources retained until readback settles.`
309
+ );
310
+ const samples2 = outcome.samples;
311
+ if (!environmentSnapshotCurrent(scene, snapshot))
312
+ return unknown2(
313
+ "Environment source/content/interpretation changed while GPU readback was pending; sample refused."
314
+ );
315
+ const sampled = result(sampledRadiance(samples2, intensity));
316
+ cacheEnvironmentSample(raw, scene, sampled);
317
+ return sampled;
318
+ } catch (error) {
319
+ return unknown2(`Environment GPU sample/readback unavailable: ${String(error)}`);
320
+ } finally {
321
+ finishSampleCleanup(pendingReadback, readbackSettled, cleanup);
322
+ }
323
+ }
324
+ async function waitForReadback(readback) {
325
+ let timer;
326
+ try {
327
+ return await Promise.race([
328
+ readback.then((samples2) => ({ timedOut: false, samples: samples2 })),
329
+ new Promise((resolve) => {
330
+ timer = setTimeout(() => resolve({ timedOut: true }), ENVIRONMENT_READBACK_TIMEOUT_MS);
331
+ })
332
+ ]);
333
+ } finally {
334
+ if (timer !== void 0) clearTimeout(timer);
335
+ }
336
+ }
337
+ function samplingRendererSupported(renderer) {
338
+ return renderer !== null && typeof renderer === "object" && Reflect.get(renderer, "isWebGPURenderer") === true && [
339
+ "render",
340
+ "getRenderTarget",
341
+ "getActiveCubeFace",
342
+ "getActiveMipmapLevel",
343
+ "setRenderTarget",
344
+ "readRenderTargetPixelsAsync"
345
+ ].every((name) => typeof Reflect.get(renderer, name) === "function");
346
+ }
347
+ function finishSampleCleanup(readback, settled, cleanup) {
348
+ if (readback !== void 0 && !settled) void readback.then(cleanup, cleanup);
349
+ else cleanup();
350
+ }
351
+
352
+ export { cacheEnvironmentSample, cachedEnvironmentSample, captureEnvironmentSnapshot, environmentSnapshotCurrent, isWebGLFallbackRenderer, materialLightingEnabled, measureEnvironment, reportEnvironmentContribution, sampleEnvironment, sampledRadiance, samplingSourceSupported };
@@ -1,5 +1,6 @@
1
1
  import { Vector2, Texture, RenderTarget, Object3D, Matrix4, Camera, BufferGeometry, DepthTexture } from 'three';
2
2
  import { MRTNode, Node, StorageBufferAttribute, ReadbackBuffer } from 'three/webgpu';
3
+ import { R as RendererToneMapping } from './default-tone-mapping-GgKPTiBP.js';
3
4
 
4
5
  /**
5
6
  * Host-boundary counters, default-off, on the frame budget's own record.
@@ -78,25 +79,6 @@ declare class FrameCounters {
78
79
  uninstall(): void;
79
80
  }
80
81
 
81
- /**
82
- * Where the main-thread frame goes, by stage (PRD-771).
83
- *
84
- * The frame budget's `render` phase wraps one synchronous `renderer.render()` call, and on the owned
85
- * Wasm engine that call holds the scene walk, the draw plan, the encode, the post passes and the queue
86
- * submit, all in C++. A phase that large with nothing named inside it is a question, not a measurement.
87
- * This splits it with one clock read per boundary, so the split rides every window rather than a
88
- * diagnostic flag:
89
- *
90
- * - the JS before the engine call (cull, `beforeRender`, reconcile, LOD, matrix walk) and after it;
91
- * - the engine's own CPU stages, from the running totals the Wasm facade publishes in
92
- * `renderer.info.engine.cpuMs` (three-native `gpu-stages.ts`), differenced per frame;
93
- * - what is left of the call, named: JS inside `render()` around the Wasm call, and Wasm time no stage owns.
94
- *
95
- * The stages partition the render phase. `wasmOther` and `engineJs` are subtractions, published as
96
- * stages (`wasmRendererGap` is what `Renderer::render` spends outside its plan and encode halves) so the unlocated time is a number and never a quiet category. On an engine that publishes no
97
- * stage totals (upstream three), the whole call is `engineJs`.
98
- */
99
-
100
82
  /** The stages of the render phase, in the order a frame spends them. They sum to the frame's `render` phase. */
101
83
  declare const RENDER_STAGES: readonly ["jsBefore", "engineJs", "wasmScene", "wasmPlan", "wasmCompute", "wasmEncode", "wasmPost", "wasmSubmit", "wasmPoll", "wasmTail", "wasmRendererGap", "wasmDatabaseGap", "wasmTargets", "wasmOther", "jsAfter"];
102
84
  type RenderStage = (typeof RENDER_STAGES)[number];
@@ -182,8 +164,8 @@ interface IStageGpuReading {
182
164
  declare function stageGpuReading(renderer: unknown): IStageGpuReading | undefined;
183
165
 
184
166
  type PlatformRuntime = "web" | "native";
185
- type PlatformOS = "android" | "ios" | "linux" | "macos" | "windows" | "unknown";
186
- type PlatformFormFactor = "mobile" | "desktop" | "unknown";
167
+ type PlatformOS = "android" | "ios" | "linux" | "macos" | "windows" | "ps4" | "unknown";
168
+ type PlatformFormFactor = "mobile" | "desktop" | "console" | "unknown";
187
169
  interface IPlatformInfo {
188
170
  readonly runtime: PlatformRuntime;
189
171
  readonly os: PlatformOS;
@@ -194,6 +176,10 @@ declare function getPlatform(): Readonly<IPlatformInfo>;
194
176
  declare function isWeb(): boolean;
195
177
  declare function isNative(): boolean;
196
178
  declare function isMobile(): boolean;
179
+ /** A games console (PS4): a pad is the input, there is no keyboard, mouse or touchscreen. */
180
+ declare function isConsole(): boolean;
181
+ /** A PlayStation 4: the pad is a DualShock 4, so its buttons are ✕ ○ □ △ and OPTIONS. */
182
+ declare function isPs4(): boolean;
197
183
  declare function isTouchscreenAvailable(): boolean;
198
184
 
199
185
  /**
@@ -277,9 +263,9 @@ declare function resolveTargetFps(config: ITargetFpsConfig | undefined, platform
277
263
  */
278
264
 
279
265
  /** Marker printed once per report window. */
280
- declare const FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET";
266
+ declare const FRAME_BUDGET_MARKER: "TN_FRAME_BUDGET";
281
267
  /** Marker printed the moment a gap between presented frames exceeds `hitchMs`. */
282
- declare const FRAME_HITCH_MARKER = "TN_FRAME_HITCH";
268
+ declare const FRAME_HITCH_MARKER: "TN_FRAME_HITCH";
283
269
  /**
284
270
  * The named parts of one presented frame. They partition the frame: `hostGap` is the time before
285
271
  * the callback (present wait plus whatever the host did between callbacks), and `update`,
@@ -631,9 +617,11 @@ interface IFrameBudgetWindow {
631
617
  interface IFrameBudgetSimulation {
632
618
  readonly tick: () => number;
633
619
  readonly step: number;
620
+ /** False counts presented frames while the simulation has not advanced in the window. */
621
+ readonly clockFrozen?: boolean;
634
622
  }
635
623
  interface IFrameBudgetOptions {
636
- /** Simulation ticks per report window when a clock is supplied, otherwise presented frames. Default 300. */
624
+ /** Simulation ticks per window; presented frames without a clock or while a live one is held. Default 300. */
637
625
  readonly reportEvery?: number;
638
626
  /** Minimum measured rendered frames per report window. Default 1. */
639
627
  readonly minFrames?: number;
@@ -705,6 +693,10 @@ declare class FrameBudget {
705
693
  * @param nowMs the monotonic clock at callback entry.
706
694
  */
707
695
  dispose(): void;
696
+ /** Marks the following frames as behind the presentation cover: no hot-call line for them. */
697
+ markCovered(): void;
698
+ /** Marks the cover lifted: the next window that begins reports hot calls again. */
699
+ markRevealed(): void;
708
700
  beginFrame(timestampMs: number, nowMs: number): void;
709
701
  /** The boundary between the fixed-step simulation and everything the render phase does. */
710
702
  markSimulationEnd(nowMs: number, substeps: number): void;
@@ -779,8 +771,9 @@ declare class FrameBudget {
779
771
  */
780
772
  addStages(stages: IFrameStageSample): void;
781
773
  /**
782
- * Closes the frame and returns its phase split, or `undefined` when the frame was a hitch and
783
- * therefore excluded — a 27-second startup stall is not a frame time and must not enter a
774
+ * Closes the frame and returns its phase split, or `undefined` when `wantSample` is false. A hitch
775
+ * still returns its split — `loop.ts` feeds it to the per-frame diagnostics — and the window meters
776
+ * below are what exclude it: a 27-second startup stall is not a frame time and must not enter a
784
777
  * percentile anybody is asked to act on.
785
778
  *
786
779
  * `wantSample` is false when the caller is going to discard the split, which is the default
@@ -1089,9 +1082,6 @@ interface IGpuFrameObservation {
1089
1082
  dispose(): void;
1090
1083
  }
1091
1084
 
1092
- /** `filmic` is a fresh Unreal 5.8.3 project's curve and the default; the rest are the named overrides. */
1093
- type RendererToneMapping = "filmic" | "aces" | "agx" | "neutral" | "none";
1094
-
1095
1085
  /** The marker shared by alpha-antialiasing logs, playtests, and native diagnostics. */
1096
1086
  declare const ALPHA_ANTIALIASING_MARKER = "TN_ALPHA_ANTIALIASING";
1097
1087
  interface IAlphaAntialiasingReport {
@@ -1504,6 +1494,20 @@ type RenderOutputSetter = ((node: unknown, worldPass?: unknown, options?: IRende
1504
1494
  * ancestor or its siblings.
1505
1495
  */
1506
1496
  declare function prewarm(object: Object3D | readonly Object3D[]): void;
1497
+ /** Where one resolved frame's GPU time went, when the renderer times its own passes (the owned engine). */
1498
+ interface IGpuFrameSplit {
1499
+ /** The scene (main colour) pass. */
1500
+ readonly main: number;
1501
+ /** Every shadow map the frame drew: the sun's and the lamps'. */
1502
+ readonly shadow: number;
1503
+ /** Everything else: post chain, output, global illumination gather. */
1504
+ readonly other: number;
1505
+ }
1506
+ /** One resolved GPU frame: its duration, the Three.js frame id it belongs to, and its pass split when known. */
1507
+ interface IGpuFrameSample extends Partial<IGpuFrameSplit> {
1508
+ readonly frame: number;
1509
+ readonly ms: number;
1510
+ }
1507
1511
  interface IRendererLike {
1508
1512
  readonly domElement: HTMLCanvasElement;
1509
1513
  readonly kind: RendererKind;
@@ -1636,8 +1640,14 @@ interface IRendererLike {
1636
1640
  * Ordinary textures and the WebGL fallback retain their existing paths and report no work.
1637
1641
  * `onProgress` receives the completed unique compressed texture count after each preparation
1638
1642
  * promise resolves; queued textures and writes that have not settled receive no credit.
1643
+ *
1644
+ * Pass `replacements` to receive caller-owned `original -> prepared` pairs. The renderer owns
1645
+ * the prepared GPU textures and publishes the map only after the whole call succeeds; an abort
1646
+ * or failure leaves the caller's map unchanged. Without it the call keeps the numeric contract
1647
+ * and prepared compressed replacements stay unpublished, so a material that samples the
1648
+ * original keeps its borrowed identity.
1639
1649
  */
1640
- prepareTextures?(textures: Iterable<Texture>, signal?: AbortSignal, onProgress?: (completed: number) => void): Promise<number>;
1650
+ prepareTextures?(textures: Iterable<Texture>, signal?: AbortSignal, onProgress?: (completed: number) => void, replacements?: Map<Texture, Texture>): Promise<number>;
1641
1651
  /**
1642
1652
  * Copies one GPU storage attribute back to the CPU, asynchronously.
1643
1653
  *
@@ -1703,10 +1713,7 @@ interface IRendererLike {
1703
1713
  * resolve twice. Optional like `gpuFrameAge`, for stubs that implement only the drawing
1704
1714
  * contract. `createRenderer` always provides it.
1705
1715
  */
1706
- gpuFrameSample?(): {
1707
- readonly frame: number;
1708
- readonly ms: number;
1709
- } | undefined;
1716
+ gpuFrameSample?(): IGpuFrameSample | undefined;
1710
1717
  /**
1711
1718
  * Observes complete allocated render-query groups without changing ordinary sampling.
1712
1719
  * Frame IDs are Three query IDs, including any overlay draws; callers map world callbacks.
@@ -1829,4 +1836,4 @@ interface IRendererOptions {
1829
1836
  }>) => unknown;
1830
1837
  }
1831
1838
 
1832
- export { RENDER_CHAIN_STAGE_ORDER as $, type IRenderChainBudgetWindow as A, type IRenderChainDroppedStage as B, type IRenderChainOptions as C, DEFAULT_PIPELINE_CENSUS_LIMIT as D, type IRenderChainRenderer as E, type FramePassKind as F, type IRenderChainRequest as G, type IRenderChainStage as H, type IRendererLike as I, type IRenderChainStageContext as J, type IRenderChainVelocityMeasurement as K, type IRenderChainVelocityReport as L, type IRenderChainVelocityRequest as M, type IRenderChainVelocityResult as N, type ITargetFps as O, type IVelocityRenderPass as P, MAX_TARGET_FPS as Q, type MainDrawSource as R, PIPELINE_CENSUS_CAPABILITY as S, PIPELINE_CENSUS_VERSION as T, PipelineCensus as U, type PipelineCensusMode as V, type PipelineCensusStatus as W, type PlatformFormFactor as X, type PlatformOS as Y, type PlatformRuntime as Z, RENDER_CHAIN_MARKER as _, type IFrameBudgetWindow as a, RENDER_CHAIN_TIERS as a0, RenderChain as a1, type RenderChainSource as a2, type RenderChainStageId as a3, type RenderChainStageName as a4, type RenderChainTier as a5, type RenderChainTierRequest as a6, type RenderChainVelocitySource as a7, type RendererToneMapping as a8, type TargetFpsSource as a9, VELOCITY_OUTPUT_NAME as aa, VELOCITY_PREVIOUS_BONE_MATRICES as ab, VELOCITY_PREVIOUS_INSTANCE_MATRICES as ac, VELOCITY_PREVIOUS_WORLD_MATRIX as ad, VelocityTracker as ae, counterDeviceOf as af, createPipelineCensus as ag, ensureVelocityOutput as ah, getPlatform as ai, isMobile as aj, isNative as ak, isTouchscreenAvailable as al, isWeb as am, prewarm as an, readRenderChainObservation as ao, readRenderChainReport as ap, readVelocityPreviousBoneMatrices as aq, readVelocityPreviousMatrices as ar, readVelocityPreviousWorldMatrix as as, resolveTargetFps as at, snapRefreshRate as au, stageGpuReading as av, velocityTexture as aw, withVelocityContext as ax, type IFrameBudgetSimulation as b, type IRenderPassSample as c, type IFramePhaseSample as d, type IPipelineCensus as e, type IRendererOptions as f, type IFrameBudgetOptions as g, type IStageGpuReading as h, DEFAULT_TARGET_FPS as i, FRAME_BUDGET_MARKER as j, FRAME_BUDGET_PHASES as k, FRAME_HITCH_MARKER as l, FrameBudget as m, type FrameBudgetPhase as n, FrameCounters as o, type ICounterDevice as p, type IFrameBudgetPassSummary as q, type IFrameBudgetSummary as r, type IFrameCounters as s, type IPipelineCensusCounts as t, type IPipelineCensusEvent as u, type IPipelineCensusOptions as v, type IPipelineProvenance as w, type IPipelineShaderObservation as x, type IPlatformInfo as y, type IRenderChainApplied as z };
1839
+ export { RENDER_CHAIN_STAGE_ORDER as $, type IRenderChainBudgetWindow as A, type IRenderChainDroppedStage as B, type IRenderChainOptions as C, DEFAULT_PIPELINE_CENSUS_LIMIT as D, type IRenderChainRenderer as E, type FramePassKind as F, type IRenderChainRequest as G, type IRenderChainStage as H, type IRendererLike as I, type IRenderChainStageContext as J, type IRenderChainVelocityMeasurement as K, type IRenderChainVelocityReport as L, type IRenderChainVelocityRequest as M, type IRenderChainVelocityResult as N, type ITargetFps as O, type IVelocityRenderPass as P, MAX_TARGET_FPS as Q, type MainDrawSource as R, PIPELINE_CENSUS_CAPABILITY as S, PIPELINE_CENSUS_VERSION as T, PipelineCensus as U, type PipelineCensusMode as V, type PipelineCensusStatus as W, type PlatformFormFactor as X, type PlatformOS as Y, type PlatformRuntime as Z, RENDER_CHAIN_MARKER as _, type IFrameBudgetWindow as a, RENDER_CHAIN_TIERS as a0, RenderChain as a1, type RenderChainSource as a2, type RenderChainStageId as a3, type RenderChainStageName as a4, type RenderChainTier as a5, type RenderChainTierRequest as a6, type RenderChainVelocitySource as a7, type TargetFpsSource as a8, VELOCITY_OUTPUT_NAME as a9, VELOCITY_PREVIOUS_BONE_MATRICES as aa, VELOCITY_PREVIOUS_INSTANCE_MATRICES as ab, VELOCITY_PREVIOUS_WORLD_MATRIX as ac, VelocityTracker as ad, counterDeviceOf as ae, createPipelineCensus as af, ensureVelocityOutput as ag, getPlatform as ah, isConsole as ai, isMobile as aj, isNative as ak, isPs4 as al, isTouchscreenAvailable as am, isWeb as an, prewarm as ao, readRenderChainObservation as ap, readRenderChainReport as aq, readVelocityPreviousBoneMatrices as ar, readVelocityPreviousMatrices as as, readVelocityPreviousWorldMatrix as at, resolveTargetFps as au, snapRefreshRate as av, stageGpuReading as aw, velocityTexture as ax, withVelocityContext as ay, type IFrameBudgetSimulation as b, type IRenderPassSample as c, type IFramePhaseSample as d, type IRendererOptions as e, type IPipelineCensus as f, type IFrameBudgetOptions as g, type IStageGpuReading as h, DEFAULT_TARGET_FPS as i, FRAME_BUDGET_MARKER as j, FRAME_BUDGET_PHASES as k, FRAME_HITCH_MARKER as l, FrameBudget as m, type FrameBudgetPhase as n, FrameCounters as o, type ICounterDevice as p, type IFrameBudgetPassSummary as q, type IFrameBudgetSummary as r, type IFrameCounters as s, type IPipelineCensusCounts as t, type IPipelineCensusEvent as u, type IPipelineCensusOptions as v, type IPipelineProvenance as w, type IPipelineShaderObservation as x, type IPlatformInfo as y, type IRenderChainApplied as z };