@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,331 @@
1
+ /**
2
+ * KTX 2.0 mip residency math, pure and container-free: how many mips a screen size can justify
3
+ * (Unreal's `StreamingTexture.cpp` rule) and which byte ranges in the file still have to arrive.
4
+ *
5
+ * The container parser is the KTX 2.0 header (Khronos spec, "KTX 2.0 File Format"):
6
+ *
7
+ * 0 identifier 12 bytes «KTX 20» \r\n\x1A\n
8
+ * 12 vkFormat u32 typeSize u32 pixelWidth u32
9
+ * 20 pixelHeight u32 pixelDepth u32 layerCount u32
10
+ * 32 faceCount u32 levelCount u32 supercompressionScheme u32
11
+ * 48 dfdByteOffset u32, dfdByteLength u32, kvdByteOffset u32, kvdByteLength u32,
12
+ * sgdByteOffset u64, sgdByteLength u64
13
+ * 80 level index: levelCount entries of { byteOffset u64, byteLength u64, uncompressedByteLength u64 }
14
+ *
15
+ * Level 0 is the largest mip; the last entry is the 1x1. A file that says `levelCount` 0 has one.
16
+ */
17
+
18
+ const KTX2_IDENTIFIER: readonly number[] = [
19
+ 0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a,
20
+ ];
21
+
22
+ const KTX2_INDEX_BYTES = 80;
23
+ const KTX2_LEVEL_ENTRY_BYTES = 24;
24
+ const MAX_SAFE_U64 = BigInt(Number.MAX_SAFE_INTEGER);
25
+
26
+ /** One level index entry: where a mip lives in the file and how big it is once decompressed. */
27
+ export interface IKtx2Level {
28
+ readonly byteOffset: number;
29
+ readonly byteLength: number;
30
+ readonly uncompressedByteLength: number;
31
+ }
32
+
33
+ /** The header fields streaming needs, plus the level index. `levelCount` is effective: 0 reads as 1. */
34
+ export interface IKtx2LevelIndex {
35
+ readonly vkFormat: number;
36
+ readonly typeSize: number;
37
+ readonly pixelWidth: number;
38
+ readonly pixelHeight: number;
39
+ readonly pixelDepth: number;
40
+ readonly layerCount: number;
41
+ readonly faceCount: number;
42
+ readonly levelCount: number;
43
+ readonly supercompressionScheme: number;
44
+ /** BasisLZ (scheme 1) needs this global block to transcode any level, so a range stream fetches it with the header. */
45
+ readonly sgdByteOffset: number;
46
+ readonly sgdByteLength: number;
47
+ readonly levels: readonly IKtx2Level[];
48
+ }
49
+
50
+ function headerFailure(reason: string): Error {
51
+ return new Error(`TN_KTX2_HEADER: ${reason}`);
52
+ }
53
+
54
+ /** The level index entry count a file declares: 0 means one mip, never zero. */
55
+ function levelEntryCount(levelCount: number): number {
56
+ return Number.isFinite(levelCount) ? Math.max(1, Math.trunc(levelCount)) : 1;
57
+ }
58
+
59
+ /** Byte length of the header plus level index for a file declaring `levelCount` mips. */
60
+ export function ktx2HeaderBytes(levelCount: number): number {
61
+ return KTX2_INDEX_BYTES + KTX2_LEVEL_ENTRY_BYTES * levelEntryCount(levelCount);
62
+ }
63
+
64
+ function readU64(view: DataView, offset: number, field: string): number {
65
+ const value = view.getBigUint64(offset, true);
66
+ if (value > MAX_SAFE_U64) {
67
+ throw headerFailure(`${field} is ${value.toString()}, above Number.MAX_SAFE_INTEGER`);
68
+ }
69
+ return Number(value);
70
+ }
71
+
72
+ /** Parses a KTX2 header and level index. Throws `TN_KTX2_HEADER: …` on anything malformed. */
73
+ export function parseKtx2LevelIndex(bytes: Uint8Array): IKtx2LevelIndex {
74
+ if (bytes.byteLength < KTX2_IDENTIFIER.length) {
75
+ throw headerFailure(
76
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the identifier: ${String(KTX2_IDENTIFIER.length)}`,
77
+ );
78
+ }
79
+ for (let i = 0; i < KTX2_IDENTIFIER.length; i += 1) {
80
+ if (bytes[i] !== KTX2_IDENTIFIER[i]) {
81
+ throw headerFailure(`byte ${String(i)} is not the KTX 2.0 identifier`);
82
+ }
83
+ }
84
+ if (bytes.byteLength < KTX2_INDEX_BYTES) {
85
+ throw headerFailure(
86
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the 80-byte header and index`,
87
+ );
88
+ }
89
+
90
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
91
+ const levelCount = levelEntryCount(view.getUint32(40, true));
92
+ const required = ktx2HeaderBytes(levelCount);
93
+ if (bytes.byteLength < required) {
94
+ throw headerFailure(
95
+ `buffer is ${String(bytes.byteLength)} bytes, ${String(levelCount)} level(s) need ${String(required)}`,
96
+ );
97
+ }
98
+
99
+ const levels: IKtx2Level[] = [];
100
+ for (let level = 0; level < levelCount; level += 1) {
101
+ const at = KTX2_INDEX_BYTES + level * KTX2_LEVEL_ENTRY_BYTES;
102
+ levels.push({
103
+ byteOffset: readU64(view, at, `level ${String(level)} byteOffset`),
104
+ byteLength: readU64(view, at + 8, `level ${String(level)} byteLength`),
105
+ uncompressedByteLength: readU64(
106
+ view,
107
+ at + 16,
108
+ `level ${String(level)} uncompressedByteLength`,
109
+ ),
110
+ });
111
+ }
112
+
113
+ return {
114
+ vkFormat: view.getUint32(12, true),
115
+ typeSize: view.getUint32(16, true),
116
+ pixelWidth: view.getUint32(20, true),
117
+ pixelHeight: view.getUint32(24, true),
118
+ pixelDepth: view.getUint32(28, true),
119
+ layerCount: view.getUint32(32, true),
120
+ faceCount: view.getUint32(36, true),
121
+ levelCount,
122
+ supercompressionScheme: view.getUint32(44, true),
123
+ sgdByteOffset: readU64(view, 64, "sgdByteOffset"),
124
+ sgdByteLength: readU64(view, 72, "sgdByteLength"),
125
+ levels,
126
+ };
127
+ }
128
+
129
+ /** The first read of a streamed file: the header, level index and metadata, and usually the tail too. */
130
+ const KTX2_PROBE_BYTES = 64 * 1024;
131
+ /** Mips at or below this side stay resident from the first read (Unreal keeps a mip tail, `TextureDerivedData.cpp:2658`). */
132
+ const KTX2_TAIL_MAX_PX = 64;
133
+ /** Level data alignment in a rebuilt file: a multiple of every block size (8, 16) and lcm(texel, 4) (4, 8, 12, 16). */
134
+ const KTX2_LEVEL_ALIGN = 48;
135
+ const BASISLZ = 1;
136
+ const BASISLZ_SGD_HEADER_BYTES = 20;
137
+ const BASISLZ_IMAGE_DESC_BYTES = 20;
138
+
139
+ /** A KTX2 file read by `Range`, coarse mips first. */
140
+ export interface IKtx2Stream {
141
+ readonly index: IKtx2LevelIndex;
142
+ /** Mip levels on hand, counted from the smallest; `index.levelCount` once the file is whole. */
143
+ readonly residentLevels: number;
144
+ /** False when the host ignored `Range` and sent the whole file, which then stays whole. */
145
+ readonly ranged: boolean;
146
+ /** Bytes read from the host so far. */
147
+ readonly bytesRead: number;
148
+ /** A complete KTX2 file of the resident levels, which any KTX2 decoder takes as it is. */
149
+ file(): Uint8Array;
150
+ /** Reads levels until `levels` are resident. The new file, or undefined when nothing was missing. */
151
+ want(levels: number): Promise<Uint8Array | undefined>;
152
+ }
153
+
154
+ /** The fetch a stream reads through; `globalThis.fetch` by default. */
155
+ export type RangeFetch = (url: string, init: RequestInit) => Promise<Response>;
156
+
157
+ function alignUp(value: number, alignment: number): number {
158
+ return Math.ceil(value / alignment) * alignment;
159
+ }
160
+
161
+ /** The BasisLZ global data for the levels from `first` on: one image descriptor per kept image. */
162
+ function trimBasisLzGlobalData(sgd: Uint8Array, index: IKtx2LevelIndex, first: number): Uint8Array {
163
+ const images = (level: number) =>
164
+ Math.max(1, index.layerCount) * index.faceCount * Math.max(1, index.pixelDepth >> level);
165
+ let dropped = 0;
166
+ for (let level = 0; level < first; level += 1) dropped += images(level);
167
+ let total = dropped;
168
+ for (let level = first; level < index.levelCount; level += 1) total += images(level);
169
+ const descs = BASISLZ_SGD_HEADER_BYTES;
170
+ const rest = descs + total * BASISLZ_IMAGE_DESC_BYTES;
171
+ if (sgd.byteLength < rest)
172
+ throw headerFailure(
173
+ `BasisLZ global data is ${String(sgd.byteLength)} bytes, ${String(rest)} needed`,
174
+ );
175
+ const out = new Uint8Array(sgd.byteLength - dropped * BASISLZ_IMAGE_DESC_BYTES);
176
+ out.set(sgd.subarray(0, descs));
177
+ out.set(sgd.subarray(descs + dropped * BASISLZ_IMAGE_DESC_BYTES), descs);
178
+ return out;
179
+ }
180
+
181
+ /**
182
+ * A KTX2 file of the levels from `first` (the finest kept) to the 1x1, from the bytes of a file read
183
+ * up to them: the header names the smaller base size, the level index the moved data, and the
184
+ * descriptor, key/value and BasisLZ global data come along.
185
+ */
186
+ function trimmedKtx2(src: Uint8Array, index: IKtx2LevelIndex, first: number): Uint8Array {
187
+ const view = new DataView(src.buffer, src.byteOffset, src.byteLength);
188
+ // A section past the bytes on hand is a broken file or a short read, never a shorter section.
189
+ const slice = (offset: number, length: number) => {
190
+ if (offset + length > src.byteLength)
191
+ throw new Error(
192
+ `TN_KTX2_HEADER: a section at ${String(offset)}+${String(length)} lies past the ${String(src.byteLength)} bytes read`,
193
+ );
194
+ return src.subarray(offset, offset + length);
195
+ };
196
+ const dfd = slice(view.getUint32(48, true), view.getUint32(52, true));
197
+ const kvd = slice(view.getUint32(56, true), view.getUint32(60, true));
198
+ let sgd = slice(index.sgdByteOffset, index.sgdByteLength);
199
+ if (index.supercompressionScheme === BASISLZ && sgd.byteLength > 0)
200
+ sgd = trimBasisLzGlobalData(sgd, index, first);
201
+ const kept = index.levels.slice(first);
202
+ const dfdAt = ktx2HeaderBytes(kept.length);
203
+ const kvdAt = dfdAt + dfd.byteLength;
204
+ const sgdAt = alignUp(kvdAt + kvd.byteLength, 8);
205
+ // Smallest level first, as the KTX2 spec stores them.
206
+ const placed: number[] = [];
207
+ let end = sgdAt + sgd.byteLength;
208
+ for (let i = kept.length - 1; i >= 0; i -= 1) {
209
+ const at = alignUp(end, KTX2_LEVEL_ALIGN);
210
+ placed[i] = at;
211
+ end = at + (kept[i]?.byteLength ?? 0);
212
+ }
213
+ const out = new Uint8Array(end);
214
+ const write = new DataView(out.buffer);
215
+ out.set(src.subarray(0, 48));
216
+ write.setUint32(20, Math.max(1, index.pixelWidth >> first), true);
217
+ if (index.pixelHeight > 0) write.setUint32(24, Math.max(1, index.pixelHeight >> first), true);
218
+ if (index.pixelDepth > 0) write.setUint32(28, Math.max(1, index.pixelDepth >> first), true);
219
+ write.setUint32(40, kept.length, true);
220
+ write.setUint32(48, dfd.byteLength > 0 ? dfdAt : 0, true);
221
+ write.setUint32(52, dfd.byteLength, true);
222
+ write.setUint32(56, kvd.byteLength > 0 ? kvdAt : 0, true);
223
+ write.setUint32(60, kvd.byteLength, true);
224
+ write.setBigUint64(64, BigInt(sgd.byteLength > 0 ? sgdAt : 0), true);
225
+ write.setBigUint64(72, BigInt(sgd.byteLength), true);
226
+ out.set(dfd, dfdAt);
227
+ out.set(kvd, kvdAt);
228
+ out.set(sgd, sgdAt);
229
+ kept.forEach((level, i) => {
230
+ const at = KTX2_INDEX_BYTES + i * KTX2_LEVEL_ENTRY_BYTES;
231
+ write.setBigUint64(at, BigInt(placed[i] ?? 0), true);
232
+ write.setBigUint64(at + 8, BigInt(level.byteLength), true);
233
+ write.setBigUint64(at + 16, BigInt(level.uncompressedByteLength), true);
234
+ out.set(slice(level.byteOffset, level.byteLength), placed[i]);
235
+ });
236
+ return out;
237
+ }
238
+
239
+ /**
240
+ * Opens a KTX2 file for mip streaming: one `Range` read takes the header, metadata and the mip tail
241
+ * (levels of 64 px or less, at least the 1x1), and `want` reads finer levels later, coarse first. The
242
+ * KTX2 spec stores levels smallest first, so the bytes on hand are always one prefix of the file. A
243
+ * host that answers 200 sent the whole file, which is kept whole: nothing is fetched twice.
244
+ */
245
+ export async function openKtx2Stream(
246
+ url: string,
247
+ fetchRange: RangeFetch = (target, init) => fetch(target, init),
248
+ ): Promise<IKtx2Stream> {
249
+ let have = new Uint8Array(0);
250
+ let ranged = true;
251
+ let bytesRead = 0;
252
+ const readTo = async (end: number): Promise<void> => {
253
+ if (!ranged || end <= have.byteLength) return;
254
+ const start = have.byteLength;
255
+ const response = await fetchRange(url, {
256
+ headers: { range: `bytes=${String(start)}-${String(end - 1)}` },
257
+ });
258
+ if (!response.ok)
259
+ throw new Error(`TN_KTX2_FETCH: '${url}' answered ${String(response.status)}`);
260
+ const body = new Uint8Array(await response.arrayBuffer());
261
+ bytesRead += body.byteLength;
262
+ if (response.status !== 206) {
263
+ have = body;
264
+ ranged = false;
265
+ return;
266
+ }
267
+ const from = /^bytes (\d+)-/u.exec(response.headers.get("content-range") ?? "")?.[1];
268
+ if (from !== undefined && Number(from) !== start)
269
+ throw new Error(
270
+ `TN_KTX2_FETCH: '${url}' answered bytes from ${from}, ${String(start)} asked`,
271
+ );
272
+ const next = new Uint8Array(start + body.byteLength);
273
+ next.set(have);
274
+ next.set(body, start);
275
+ have = next;
276
+ };
277
+ await readTo(KTX2_PROBE_BYTES);
278
+ const index = parseKtx2LevelIndex(have);
279
+ const { levels } = index;
280
+ const last = levels.length - 1;
281
+ const levelEnd = (level: number) =>
282
+ (levels[level]?.byteOffset ?? 0) + (levels[level]?.byteLength ?? 0);
283
+ // A writer that broke the smallest-first order has no coarse prefix: read the file whole.
284
+ const ordered = levels.every(
285
+ (level, i) => i === last || level.byteOffset > (levels[i + 1]?.byteOffset ?? 0),
286
+ );
287
+ if (!ordered) await readTo(Math.max(...levels.map((_, i) => levelEnd(i))));
288
+ let tail = 1;
289
+ while (
290
+ tail < levels.length &&
291
+ Math.max(index.pixelWidth, index.pixelHeight) >> (levels.length - 1 - tail) <= KTX2_TAIL_MAX_PX
292
+ )
293
+ tail += 1;
294
+ await readTo(levelEnd(levels.length - tail));
295
+ const resident = (): number => {
296
+ if (!ranged) return levels.length;
297
+ let count = 0;
298
+ while (count < levels.length && levelEnd(last - count) <= have.byteLength) count += 1;
299
+ return count;
300
+ };
301
+ const file = (): Uint8Array => {
302
+ const count = resident();
303
+ // A host that answered a short 206 left not even the 1x1 level: no file to hand on.
304
+ if (count === 0)
305
+ throw new Error(
306
+ `TN_KTX2_FETCH: '${url}' sent ${String(have.byteLength)} bytes, short of its smallest mip level`,
307
+ );
308
+ return count === levels.length && !ranged
309
+ ? have
310
+ : trimmedKtx2(have, index, levels.length - count);
311
+ };
312
+ return {
313
+ index,
314
+ get residentLevels() {
315
+ return resident();
316
+ },
317
+ get ranged() {
318
+ return ranged;
319
+ },
320
+ get bytesRead() {
321
+ return bytesRead;
322
+ },
323
+ file,
324
+ want: async (count) => {
325
+ const target = Math.min(levels.length, Math.max(1, Math.trunc(count)));
326
+ if (target <= resident()) return undefined;
327
+ await readTo(levelEnd(levels.length - target));
328
+ return file();
329
+ },
330
+ };
331
+ }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-version.mjs - do not edit. Source: package.json.
2
- export const CORE_VERSION = "0.3.11";
2
+ export const CORE_VERSION = "0.3.13";
package/src/warmup.ts CHANGED
@@ -233,6 +233,19 @@ export interface IWarmUpReport {
233
233
  readonly visibilityForced?: number;
234
234
  }
235
235
 
236
+ const warmUpCompletions = new WeakMap<IWarmUpReport, Promise<void>>();
237
+
238
+ /** Internal launch-gate result. The live compiler promise stays out of the serializable report. */
239
+ export async function warmUpSceneWithCompletion(
240
+ renderer: IWarmUpRenderer,
241
+ scene: Object3D,
242
+ camera: Camera,
243
+ options: IWarmUpOptions = {},
244
+ ): Promise<{ readonly report: IWarmUpReport; readonly completion: Promise<void> }> {
245
+ const report = await warmUpScene(renderer, scene, camera, options);
246
+ return { report, completion: warmUpCompletions.get(report) ?? Promise.resolve() };
247
+ }
248
+
236
249
  /** The narrow slice of the renderer this needs. Structural so a test needs no renderer. */
237
250
  export interface IWarmUpRenderer {
238
251
  compileAsync?: (scene: Object3D, camera: Camera, targetScene?: Object3D) => Promise<void>;
@@ -814,24 +827,31 @@ interface IReflectorNodeLike {
814
827
  *
815
828
  * Three's `reflector()` hangs a `_reflectorBaseNode` off a `ReflectorNode` that a material's
816
829
  * `colorNode` (or a node composed around it) references. The walk is bounded and only descends
817
- * real nodes, so a material with no reflector costs one shallow pass.
830
+ * real nodes, so a material with no reflector costs one shallow pass. `seen` holds the shallowest
831
+ * depth each node was reached at: a TSL graph shares subgraphs, and without it every path to a
832
+ * shared node walks it again.
818
833
  */
819
- function nodeHasReflector(root: unknown, depth: number): boolean {
834
+ function nodeHasReflector(root: unknown, depth: number, seen: WeakMap<object, number>): boolean {
820
835
  if (depth > 64 || typeof root !== "object" || root === null) return false;
821
836
  const node = root as IReflectorNodeLike;
822
837
  if (node._reflectorBaseNode !== undefined) return true;
823
838
  if (node.isNode !== true || typeof node.getChildren !== "function") return false;
839
+ const reached = seen.get(root);
840
+ if (reached !== undefined && reached <= depth) return false;
841
+ seen.set(root, depth);
824
842
  try {
825
843
  for (const child of node.getChildren()) {
826
- if (nodeHasReflector(child, depth + 1)) return true;
844
+ if (nodeHasReflector(child, depth + 1, seen)) return true;
827
845
  }
828
846
  } catch {
847
+ seen.delete(root);
829
848
  return false;
830
849
  }
831
850
  return false;
832
851
  }
833
852
 
834
853
  function hasReflector(scene: Object3D): boolean {
854
+ const seen = new WeakMap<object, number>();
835
855
  const stack: Object3D[] = [scene];
836
856
  // A material is read once however many objects draw with it: on the engine, every field of its
837
857
  // values is a call into the host.
@@ -847,7 +867,7 @@ function hasReflector(scene: Object3D): boolean {
847
867
  ) {
848
868
  read.add(material);
849
869
  for (const value of Object.values(material as Record<string, unknown>)) {
850
- if (nodeHasReflector(value, 0)) return true;
870
+ if (nodeHasReflector(value, 0, seen)) return true;
851
871
  }
852
872
  }
853
873
  const children = object.children ?? [];
@@ -1170,6 +1190,7 @@ export async function warmUpScene(
1170
1190
  }
1171
1191
  const compileAsync = renderer.compileAsync.bind(renderer);
1172
1192
  let attempted = 0;
1193
+ const pendingCompiles: Promise<void>[] = [];
1173
1194
  const invokeCompile = (object: Object3D, targetScene?: Object3D): Promise<void> => {
1174
1195
  const compileDeadline =
1175
1196
  (options.granularity ?? "scene") === "scene"
@@ -1205,12 +1226,33 @@ export async function warmUpScene(
1205
1226
  .then(async () => {
1206
1227
  const pass = await renderWarmPassesOnce();
1207
1228
  if (pass === undefined) {
1229
+ // Skipped because the budget ran out first: lazy work, like any compile that never
1230
+ // started. Rejecting here failed a held startup whose compile merely ran long.
1231
+ if (passError === undefined && now() >= startedAt + budgetMs) return;
1208
1232
  throw passError ?? new Error("covered world warm render did not settle");
1209
1233
  }
1210
1234
  });
1211
1235
  };
1212
1236
 
1213
1237
  let gpuDrainSettled = true;
1238
+ const compileWithinDeadline = async (
1239
+ deadline: number,
1240
+ work: Promise<void>,
1241
+ yieldFrame: () => Promise<void>,
1242
+ now: () => number,
1243
+ ): Promise<boolean> => {
1244
+ // `withinDeadline` answers one `false` both for work the deadline outran and for work that
1245
+ // rejected, and only the first is something a held launch may still wait on: a compile that
1246
+ // already failed belongs to the frame that needs its pipeline, where the error belongs.
1247
+ let settled = false;
1248
+ const track = (): void => {
1249
+ settled = true;
1250
+ };
1251
+ void work.then(track, track);
1252
+ const finished = await withinDeadline(deadline, work, yieldFrame, now);
1253
+ if (!finished && !settled) pendingCompiles.push(work);
1254
+ return finished;
1255
+ };
1214
1256
  const finish = (report: IWarmUpReport): IWarmUpReport => {
1215
1257
  const coveredPassIncomplete =
1216
1258
  renderer.warmUpWorldPass !== undefined && passResult === undefined;
@@ -1239,7 +1281,13 @@ export async function warmUpScene(
1239
1281
  complete && cacheIdentity !== undefined
1240
1282
  ? storeWarmUpCache(cacheIdentity, candidates, computeNodes.length)
1241
1283
  : cacheStatus;
1242
- return reconcileWarmUpObservation({ ...normalized, cache: finalCache });
1284
+ const finishedReport = reconcileWarmUpObservation({ ...normalized, cache: finalCache });
1285
+ if (pendingCompiles.length > 0) {
1286
+ const completion = Promise.all(pendingCompiles).then(() => undefined);
1287
+ void completion.catch(() => undefined);
1288
+ warmUpCompletions.set(finishedReport, completion);
1289
+ }
1290
+ return finishedReport;
1243
1291
  };
1244
1292
 
1245
1293
  // The hidden pass render runs once, after the compile and before the ending census snapshot, so
@@ -1305,7 +1353,7 @@ export async function warmUpScene(
1305
1353
  const deadline = startedAt + budgetMs;
1306
1354
  const finished =
1307
1355
  now() < deadline
1308
- ? await withinDeadline(deadline, invokeSceneCompile(), yieldFrame, now)
1356
+ ? await compileWithinDeadline(deadline, invokeSceneCompile(), yieldFrame, now)
1309
1357
  : false;
1310
1358
  options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
1311
1359
  await renderWarmPassesOnce();
@@ -1328,7 +1376,7 @@ export async function warmUpScene(
1328
1376
  const remaining = Math.max(0, startedAt + budgetMs - now());
1329
1377
  const finished =
1330
1378
  remaining > 0
1331
- ? await withinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now)
1379
+ ? await compileWithinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now)
1332
1380
  : false;
1333
1381
  options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
1334
1382
  await renderWarmPassesOnce();
@@ -1391,7 +1439,7 @@ export async function warmUpScene(
1391
1439
  // identity; this layer must not guess which objects are safe to drop before it observes them.
1392
1440
  //
1393
1441
  // Bounded, because an unbounded await here is what held a real launch open forever.
1394
- const finished = await withinDeadline(
1442
+ const finished = await compileWithinDeadline(
1395
1443
  Math.min(deadline, now() + compileTimeoutMs),
1396
1444
  invokeCompile(renderables[index] as Object3D, options.targetScene ?? scene),
1397
1445
  yieldFrame,
@@ -181,7 +181,9 @@ export class WaterSurface3D {
181
181
  // a replay refreshes only listed draws, so those keep the camera they were recorded with. The
182
182
  // mirror renders outside the record, and the record gets its bundle back. A pass three never
183
183
  // updates (the native engine draws it and records no JS bundle) has no render to guard.
184
- if (pass.updateBeforeType !== "none") {
184
+ // The native engine draws the mirror pass itself and exposes no JS update to wrap.
185
+ const jsPass = pass.updateBeforeType !== "none";
186
+ if (jsPass) {
185
187
  const mirror = pass.updateBefore.bind(pass);
186
188
  pass.updateBefore = (frame: IReflectionFrame): void => {
187
189
  const host = frame.renderer as { _currentRenderBundle?: unknown };
@@ -209,7 +211,11 @@ export class WaterSurface3D {
209
211
  return virtual;
210
212
  };
211
213
  }
212
- if (reflection.layers === undefined) {
214
+ if (!jsPass && (reflection.layers === undefined || refreshInterval > 1))
215
+ console.info(
216
+ `TN_WATER_REFLECTION_NATIVE: ${JSON.stringify({ minSizeFilter: false, refreshInterval: 1, reason: "the engine draws the mirror pass natively" })}`,
217
+ );
218
+ if (jsPass && reflection.layers === undefined) {
213
219
  const minSize = finite("reflection.minSize", reflection.minSize ?? 10);
214
220
  if (minSize <= 0) throw new Error("WaterSurface3D.reflection.minSize must be positive.");
215
221
  const render = pass.updateBefore.bind(pass);
@@ -253,7 +259,7 @@ export class WaterSurface3D {
253
259
  }
254
260
  };
255
261
  }
256
- if (refreshInterval > 1) {
262
+ if (jsPass && refreshInterval > 1) {
257
263
  // Every frame the pass redraws the world into its target and binds the result. The render is
258
264
  // the expensive part; the binding is not. Skipping the whole `updateBefore` on the frames
259
265
  // between leaves the previous frame's texture bound and the render target intact, so the
package/src/worker.ts CHANGED
@@ -711,6 +711,7 @@ export function startWorkerGame(
711
711
  }
712
712
  };
713
713
 
714
+ let started = false;
714
715
  let resolveReady: () => void = () => undefined;
715
716
  let rejectReady: (error: Error) => void = () => undefined;
716
717
  const ready = new Promise<void>((resolve, reject) => {
@@ -789,6 +790,7 @@ export function startWorkerGame(
789
790
  installMirror(message.name, message.epoch);
790
791
  break;
791
792
  case "tn-worker-started":
793
+ started = true;
792
794
  resolveReady();
793
795
  break;
794
796
  case "tn-worker-failed":
@@ -833,8 +835,16 @@ export function startWorkerGame(
833
835
 
834
836
  listen(worker, "message", onWorkerMessage);
835
837
  const onWorkerError = (event: Event): void => {
836
- const message = (event as ErrorEvent).message;
837
- stop(new Error(message || `TN_WORKER_FAILED: worker ${event.type}.`));
838
+ // A worker's ErrorEvent carries where it threw; without it the page sees only the message, and a
839
+ // stack-less "worker died" is unactionable (the 0.3.13 release proof lost a red this way).
840
+ const error = event as ErrorEvent;
841
+ const origin = [error.filename, error.lineno, error.colno].filter(Boolean).join(":");
842
+ const message = `${error.message || `worker ${event.type}`}${origin ? ` (${origin})` : ""}`;
843
+ // Once started, nothing awaits `ready`: without this line a frame that threw removed the canvas
844
+ // and printed nothing (PRD-857).
845
+ if (started && !stopped)
846
+ console.error(`TN_WORKER_FAILED: the running worker game stopped: ${message}`);
847
+ stop(new Error(message));
838
848
  };
839
849
  listen(worker, "error", onWorkerError);
840
850
  listen(worker, "messageerror", onWorkerError);