@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,592 @@
1
+ import {
2
+ type Box3,
3
+ type Camera,
4
+ Frustum,
5
+ InstancedMesh,
6
+ type Material,
7
+ Matrix4,
8
+ type Object3D,
9
+ } from "three";
10
+ import { markEngineRenderHook } from "./engine-render-hook.js";
11
+ import type { IRendererLike } from "./renderer.js";
12
+ import { SharedBatch } from "./world-cell-batches.js";
13
+ import type { IBatchShape, IPrewarmEntry } from "./world-cell-data.js";
14
+ import type { IAssetState } from "./world-cell-models.js";
15
+
16
+ export interface ICellPrewarmHost {
17
+ released(): boolean;
18
+ parent(): Object3D | null;
19
+ invalidateShadows(): void;
20
+ backlog(): number;
21
+ /**
22
+ * Whether this world can still queue a prewarm: a cell resident (its builds acquire the asset),
23
+ * or a model load in flight or queued (its completion queues the keys). False is a world with
24
+ * nothing left to ask with; see `drainPrewarm`.
25
+ */
26
+ workPending(): boolean;
27
+ keysForShadow(): boolean;
28
+ hasShared(key: string): boolean;
29
+ hasRetired(key: string): boolean;
30
+ runMax(asset: string): number | undefined;
31
+ residentCells(): number;
32
+ extentBounds(): Box3;
33
+ smallCaster(asset: string): boolean;
34
+ dressMesh(shared: SharedBatch, receiveShadow: boolean): void;
35
+ receiveShadow(): boolean;
36
+ adoptGpu(shared: SharedBatch, asset: string, key: string, level: number, part: number): void;
37
+ setShared(key: string, shared: SharedBatch): void;
38
+ attach(shared: SharedBatch): void;
39
+ casts(level: number): boolean;
40
+ preserveAuthoredParts(): boolean;
41
+ wideOwed(asset: string, part: number): boolean;
42
+ followCluster(): string;
43
+ wideShape(
44
+ asset: IAssetState | undefined,
45
+ level: number,
46
+ part: number,
47
+ fallback: IBatchShape,
48
+ ): IBatchShape;
49
+ /** The material the swap draws this level and part with; see `CellGpuDress#lodSurface`. */
50
+ lodSurface(asset: string, level: number, part: number, source: Material): Material;
51
+ }
52
+
53
+ /**
54
+ * Prewarmed batches minted per update, and the updates a minted batch must survive before it counts
55
+ * as drawn. Three keys its render-object/node cache by `object.uuid`, so every InstancedMesh it has
56
+ * never drawn costs a NodeBuilder build the first frame it is projected (~9 ms in the main pass, and
57
+ * again in the shadow pass for a level that casts): hundreds of them land in a few seconds of
58
+ * walking, which is the walk-time frame cost this pays earlier instead.
59
+ *
60
+ * The rate is a rate of *rendered* updates, not of `update` calls. Minting a batch is cheap (an
61
+ * InstancedMesh and a zeroed buffer) and its build is paid by the next render, so an unbounded queue
62
+ * would hand the whole map's seconds of builds to one frame. 8 per update is ~150 ms of build on the
63
+ * frame that pays it, which the loading screen covers.
64
+ */
65
+ const PREWARM_PER_UPDATE = 8;
66
+ /**
67
+ * Two updates is the honest floor for "drawn at least once in both the main and the shadow
68
+ * context": the mesh is added during one update and the next render projects it. Tracking it per
69
+ * context would mean hooking the renderer, which this class does not own.
70
+ */
71
+ const PREWARM_WARM_UPDATES = 2;
72
+ /**
73
+ * Updates a mesh may still be owed a prewarm draw after the gate settled before its borrow is handed
74
+ * back anyway. An empty prewarmed batch draws, so this is the ceiling on the ones that never will —
75
+ * a projection that collapsed the world, a camera that never reached the mesh — and not a diagnosis
76
+ * of any of them. Without it those meshes would hold their hook for the whole walk.
77
+ */
78
+ const PREWARM_RELEASE_UPDATES = 8;
79
+ /** The whole ring, as one caster cluster: `@*` is every square's records in one mesh. */
80
+ export const WIDE_CLUSTER = "*";
81
+
82
+ export class CellPrewarm {
83
+ readonly #drawBatches = new WeakMap<InstancedMesh, SharedBatch>();
84
+ readonly #submitted = new WeakSet<InstancedMesh>();
85
+ readonly #drawBorrows = new Map<
86
+ InstancedMesh,
87
+ { before: unknown; release(): void; settle(): void }
88
+ >();
89
+
90
+ /** Strict CPU submission gate; idle legacy prewarm settlement is not a submitted draw. */
91
+ pendingCpuDrawsInView(root: Object3D, camera: Camera, renderer?: IRendererLike): number {
92
+ camera.updateWorldMatrix(true, false);
93
+ root.updateWorldMatrix(true, true);
94
+ const frustum = new Frustum().setFromProjectionMatrix(
95
+ new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
96
+ camera.coordinateSystem,
97
+ );
98
+ const active = new Set<InstancedMesh>();
99
+ let pending = 0;
100
+ root.traverseVisible((object) => {
101
+ if (!(object instanceof InstancedMesh)) return;
102
+ const batch = this.#drawBatches.get(object);
103
+ if (
104
+ !batch ||
105
+ batch.gpu !== undefined ||
106
+ batch.role !== "main" ||
107
+ object.count <= 0 ||
108
+ !camera.layers.test(object.layers) ||
109
+ !frustum.intersectsObject(object)
110
+ )
111
+ return;
112
+ // An engine that calls onBeforeRender alone (the owned engine, for a main draw it submits) counts
113
+ // the frame once render() returns: the next query settles it.
114
+ this.#drawBorrows.get(object)?.settle();
115
+ if (this.#submitted.has(object)) return;
116
+ pending++;
117
+ active.add(object);
118
+ const previous = this.#drawBorrows.get(object);
119
+ if (previous && object.onBeforeRender !== previous.before) previous.release();
120
+ if (this.#drawBorrows.has(object) || renderer === undefined) return;
121
+ const ownBefore = object.onBeforeRender;
122
+ const ownAfter = object.onAfterRender;
123
+ const hadBefore = Object.hasOwn(object, "onBeforeRender");
124
+ const hadAfter = Object.hasOwn(object, "onAfterRender");
125
+ let before: number | undefined;
126
+ // Renders finished when the hook ran: three's `info.render.calls` and the facade's both only grow.
127
+ let hookedAt: number | undefined;
128
+ const renders = (): number | undefined => {
129
+ const value = (renderer.info as { render?: { calls?: number } }).render?.calls;
130
+ return Number.isSafeInteger(value) ? value : undefined;
131
+ };
132
+ const calls = (): number | undefined => {
133
+ const value = (renderer.info as { render?: { drawCalls?: number; calls?: number } }).render;
134
+ const count = value?.drawCalls ?? value?.calls;
135
+ return Number.isSafeInteger(count) && (count as number) >= 0 ? count : undefined;
136
+ };
137
+ const submitted = this.#submitted;
138
+ const release = () => {
139
+ if (object.onBeforeRender === beforeHook) this.#handBack(object, hadBefore, ownBefore);
140
+ if (object.onAfterRender === afterHook) {
141
+ if (hadAfter) object.onAfterRender = ownAfter;
142
+ else Reflect.deleteProperty(object, "onAfterRender");
143
+ }
144
+ this.#drawBorrows.delete(object);
145
+ };
146
+ const beforeHook: typeof object.onBeforeRender = function (this: InstancedMesh, ...args) {
147
+ before = undefined;
148
+ ownBefore.apply(this, args);
149
+ before = args[2] === camera && renderer.compiling !== true ? calls() : undefined;
150
+ hookedAt = before === undefined ? undefined : renders();
151
+ };
152
+ const afterHook: typeof object.onAfterRender = function (this: InstancedMesh, ...args) {
153
+ const after = calls();
154
+ if (
155
+ args[2] === camera &&
156
+ renderer.compiling !== true &&
157
+ object.count > 0 &&
158
+ before !== undefined &&
159
+ after !== undefined &&
160
+ after > before
161
+ ) {
162
+ submitted.add(object);
163
+ release();
164
+ }
165
+ before = undefined;
166
+ hookedAt = undefined;
167
+ ownAfter.apply(this, args);
168
+ };
169
+ markEngineRenderHook(beforeHook);
170
+ markEngineRenderHook(afterHook);
171
+ object.onBeforeRender = beforeHook;
172
+ object.onAfterRender = afterHook;
173
+ // The owned engine calls onBeforeRender alone, and only for a main draw it submits after its cull,
174
+ // so the hook plus a render that finished after it is the draw. three's after-hook clears `hookedAt`.
175
+ const settle = () => {
176
+ const now = hookedAt === undefined ? undefined : renders();
177
+ if (object.count > 0 && now !== undefined && hookedAt !== undefined && now > hookedAt) {
178
+ submitted.add(object);
179
+ release();
180
+ }
181
+ };
182
+ this.#drawBorrows.set(object, { before: beforeHook, release, settle });
183
+ });
184
+ for (const [mesh, borrow] of this.#drawBorrows) if (!active.has(mesh)) borrow.release();
185
+ return pending;
186
+ }
187
+ /**
188
+ * Every `asset:level:part` of a loaded asset is minted empty, before any placement wants it, so
189
+ * the node build lands in the loading phase instead of the frame a cell row first draws the key.
190
+ * `#prewarmQueue` is the keys still to mint, `#prewarmKeys` the ones queued (a retried load must
191
+ * not queue the same key twice), and `#prewarmPending` the ones minted but not yet
192
+ * `PREWARM_WARM_UPDATES` updates old. `prewarmed` is the game's gate for "safe to show me this
193
+ * world"; `stats().pendingPrewarm` is the same thing as a number.
194
+ */
195
+ readonly #prewarmQueue: IPrewarmEntry[] = [];
196
+ readonly #prewarmKeys = new Set<string>();
197
+ #prewarmPending = 0;
198
+ /** Every mint so far, so a loading bar can read minted / (minted + pending). */
199
+ #prewarmMinted = 0;
200
+ /**
201
+ * Minted meshes whose first draw has been submitted, and the meshes still owed one. A mint is
202
+ * only half the work: the node is built when the mesh is first submitted, and that is the frame
203
+ * the loading bar used to sit still for. `pendingPrewarm` reports this pair, so the bar counts the
204
+ * draw half instead of jumping from minting straight to done. The gate is a promise about batches
205
+ * (`#prewarmPending`), never about these: a companion no shadow level covers is owed a draw
206
+ * forever, and the gate must not wait on it.
207
+ */
208
+ #prewarmOwed = 0;
209
+ #prewarmDrawn = 0;
210
+ #prewarmEpoch = 0;
211
+ #prewarmWait = 0; /**
212
+ * Awaited meshes that only a shadow level can draw, and the share of them that have had one.
213
+ *
214
+ * A caster's node is built in the shadow context, so a walk-time first shadow draw of a streamed
215
+ * key is a `NodeBuilder.build` inside a shadow pass — a third of the shadow lane's CPU on the
216
+ * 2 km walk. Counting them separately is what `TN_WORLD_PREWARM`'s `shadowPrewarmed` reports and
217
+ * what the gate waits on; a count of "every batch drew once" cannot tell the two apart.
218
+ */
219
+ #prewarmCasterMinted = 0;
220
+ #prewarmCasterOwed = 0;
221
+ #prewarmCasterDrawn = 0;
222
+ /**
223
+ * Meshes still carrying a prewarm borrow, with the hook each one has to be handed back, the batch
224
+ * holding it visible, and the post-settle updates it has waited; see
225
+ * {@link #releaseImpossibleBorrows}.
226
+ */
227
+ readonly #awaited = new Map<
228
+ InstancedMesh,
229
+ {
230
+ batch: SharedBatch;
231
+ borrow: unknown;
232
+ own: unknown;
233
+ hadOwn: boolean;
234
+ waited: number;
235
+ epoch: number;
236
+ }
237
+ >();
238
+ #prewarmSettled = false;
239
+ #prewarmAsked = false;
240
+ #prewarmResolve: () => void = () => {
241
+ // replaced in the field initialiser below, once `this` exists
242
+ };
243
+ readonly #prewarmed: Promise<void> = new Promise<void>((resolve) => {
244
+ this.#prewarmResolve = resolve;
245
+ });
246
+
247
+ /**
248
+ * Mint this update's prewarm allowance, then settle the readiness signal.
249
+ *
250
+ * A batch minted while the world is not in a scene is projected by nothing and builds nothing, so
251
+ * the ready count only advances on an update that had somewhere to draw: a `load()` loop filling
252
+ * the ring mints the whole ring and still leaves the gate shut, which is the honest answer.
253
+ */
254
+ drainPrewarm(): void {
255
+ if (this.#host.released()) return;
256
+ // The loading rate drops to the same 2-per-update a fresh mesh costs once the loading screen is
257
+ // gone. 8 per update is ~150 ms of node builds on the frame that pays it, and the loading
258
+ // screen is the only thing that was covering it: a walk that streams a new asset in afterwards
259
+ // used to hand that frame's builds to a frame that is trying to hold its rate.
260
+ const perUpdate = this.#prewarmSettled ? 2 : PREWARM_PER_UPDATE;
261
+ let minted = 0;
262
+ while (minted < perUpdate && this.#prewarmQueue.length > 0) {
263
+ const entry = this.#prewarmQueue.shift() as IPrewarmEntry;
264
+ this.#prewarmKeys.delete(entry.key);
265
+ this.#mintPrewarm(entry);
266
+ minted += 1;
267
+ }
268
+ // A minted batch is only *owed* a draw by `#awaitDraw`; nothing made anything draw it. A main
269
+ // batch is drawn by the next main render, but a caster is drawn by a shadow level, and the
270
+ // levels render when their window moves or something invalidates them — on a loading screen the
271
+ // follow point stands still, so every caster minted after the first frame sat in the graph with
272
+ // a node no level had ever asked for and the walk's first window move built all of them in one
273
+ // shadow pass. Invalidating while the gate is open, minting or not, is what makes the prewarm
274
+ // prewarm: the build is paid by the loading screen, which is the only frame rate hiding it.
275
+ if (minted > 0) this.#prewarmWait = 0;
276
+ // A caster's draw is a shadow level's, and the levels render at most one per frame, so the gate
277
+ // keeps asking them to while one is owed — bounded, because a borrow nothing draws is handed
278
+ // back by `#releaseImpossibleBorrows` below and a world that never draws one settles anyway.
279
+ const waitingOnCasters = this.#host.parent() !== null && this.#prewarmCasterOwed > 0;
280
+ if (minted > 0 || waitingOnCasters) this.#host.invalidateShadows();
281
+ else if (this.#host.parent() !== null) this.#prewarmWait += 1;
282
+ this.#releaseImpossibleBorrows();
283
+ if (this.#prewarmQueue.length > 0) return;
284
+ // Nothing to settle until an asset has asked; once one has, an ask whose keys were all already
285
+ // built minted nothing and is owed nothing, so it settles like a drained one. A world that has
286
+ // asked nothing yet settles too, as long as nothing of it can ask later: no resident cell and
287
+ // no model load in flight means no later update of this load queues a prewarm — a world whose
288
+ // cells all lie outside the follow point's ring, which is what a game awaiting the draw gate of
289
+ // every world it streams holds (the Strata spawn gate waited its whole 120 s deadline on one).
290
+ // The trade is the one `PREWARM_RELEASE_UPDATES` makes: a gate that settles early costs the
291
+ // walk a first-draw build, and a gate that never settles costs the game its load. A resident
292
+ // cell keeps the asked-nothing gate shut exactly as before, so a world that is about to ask
293
+ // still waits for it.
294
+ if (this.#prewarmPending <= 0 && !this.#prewarmAsked && this.#host.workPending()) return;
295
+ if (this.#prewarmWait < PREWARM_WARM_UPDATES) return;
296
+ // A caster still owed a draw is a build the walk would otherwise pay inside a shadow pass, so the
297
+ // gate holds for it until its borrow is handed back, which is the bound.
298
+ if (waitingOnCasters) return;
299
+ // A build still owed draws nothing until it lands. When the scene comes up over a ring built
300
+ // without it, that is the whole ring re-seeded: the gate settled over 1,378 owed builds and a
301
+ // third of Machinefall's forest arrived in the first 4 s of play (PRD-478). The loading screen
302
+ // covers them instead.
303
+ if (this.#host.backlog() > 0) return;
304
+ this.#prewarmPending = 0;
305
+ // The gate is settled, so nothing is owed a draw. A companion no shadow level covers leaves its
306
+ // pair non-zero, and `pendingPrewarm` is documented `0` from here on.
307
+ this.#prewarmOwed = 0;
308
+ this.#prewarmDrawn = 0;
309
+ // Retained first-draw hooks belong to the counters just cleared, not later streamed work.
310
+ this.#prewarmEpoch += 1;
311
+ this.#prewarmWait = 0;
312
+ this.#settlePrewarm();
313
+ }
314
+
315
+ /**
316
+ * The empty batch for one prewarmed key, built exactly as `#batchFor` builds the real one so a
317
+ * placement that later wants it draws into this mesh and keeps the node three built for it. Both
318
+ * halves of the split are queued: the main key, and the follow point's own caster cluster, which
319
+ * is the one the first shadow level render asks for.
320
+ */
321
+ #mintPrewarm(entry: IPrewarmEntry): void {
322
+ // A world whose shadow levels draw its keys mints no caster half: the two are the same
323
+ // placements by two routes, and a level's map can only draw one of them, so a prewarmed half is
324
+ // a build behind the gate that pays for nothing and an owed draw the gate waits on until it
325
+ // gives up. Decided at the mint rather than at the queue, which is filled before the first
326
+ // renderer hands the GPU scene over. The shadow keys are prewarmed where they are minted
327
+ // instead; see `#shadowKeyFor`.
328
+ if (entry.role !== "main" && this.#host.keysForShadow()) return;
329
+ // A key the retained set is holding needs no prewarmed batch: `#batchFor` rebinds that mesh
330
+ // when the walk comes back, and rebinding is the whole point of keeping it. The prewarm did not
331
+ // ask, so it minted a second InstancedMesh for a key that already had one — a uuid three built a
332
+ // node for twice, in the main pass and in every shadow pass, for the whole of a walk back.
333
+ if (
334
+ this.#host.released() ||
335
+ this.#host.hasShared(entry.key) ||
336
+ this.#host.hasRetired(entry.key)
337
+ )
338
+ return;
339
+ // Minted with the material the swap draws (`shapeFor`): the raw part material builds a program no
340
+ // placement ever draws, and the LOD-masked one is then built by the first placement, after the reveal.
341
+ const shared = new SharedBatch(
342
+ entry.geometry,
343
+ this.#host.lodSurface(entry.asset, entry.level, entry.part, entry.material),
344
+ this.#host.runMax(entry.asset) ?? 1,
345
+ this.#host.residentCells() + 1,
346
+ entry.key,
347
+ this.#host.extentBounds(),
348
+ entry.role,
349
+ entry.level,
350
+ );
351
+ shared.smallCaster = this.#host.smallCaster(entry.asset);
352
+ this.#host.dressMesh(shared, entry.role === "main" && this.#host.receiveShadow());
353
+ // Dressed here, before the walk that fills it: the prewarm is what mints every key of an asset
354
+ // before its first placement is swapped, so this is where the whole gate table comes from.
355
+ this.#host.adoptGpu(shared, entry.asset, entry.key, entry.level, entry.part);
356
+ this.#host.setShared(entry.key, shared);
357
+ this.#host.attach(shared);
358
+ this.#prewarmPending += 1;
359
+ this.#prewarmMinted += 1;
360
+ // Every role is owed a draw by `#awaitDraw` and is shown while empty until that draw is counted:
361
+ // the node, the bindings and the pipeline are built by a submission, and one zero-count
362
+ // submission per prewarmed batch is the price of having the walk never pay for it. A caster's
363
+ // submission is a shadow level's, not the main pass's — which is why `#drainPrewarm` keeps the
364
+ // levels rendering while one is owed, and why `VirtualShadowNode`'s `#probe` renders both caster
365
+ // layers when it finds one. A caster that is not awaited here is built on the first shadow draw
366
+ // of the walk, inside a shadow pass, which is the cost this prewarm exists to move.
367
+ this.awaitDraw(shared);
368
+ }
369
+
370
+ /** Count this batch's first submitted draw, once, then hand `onBeforeRender` back to whoever had it. */
371
+ awaitDraw(shared: SharedBatch): void {
372
+ const mesh = shared.mesh;
373
+ this.#drawBatches.set(mesh, shared);
374
+ const caster = shared.role !== "main";
375
+ this.#prewarmOwed += 1;
376
+ if (caster) {
377
+ this.#prewarmCasterMinted += 1;
378
+ this.#prewarmCasterOwed += 1;
379
+ }
380
+ shared.awaitPrewarmDraw();
381
+ // three's `Object3D` carries an inherited no-op, so reading `onBeforeRender` off a fresh mesh
382
+ // hands back a function that was never an own property. Writing it back as one leaves every
383
+ // batch that has drawn since looking permanently hooked, and the projection's `hasRenderHook`
384
+ // reads own properties — so the borrow has to remember whether there was one to give back.
385
+ const hadOwn = Object.hasOwn(mesh, "onBeforeRender");
386
+ this.#borrowDraw(shared, mesh, hadOwn, hadOwn ? mesh.onBeforeRender : undefined);
387
+ }
388
+
389
+ /**
390
+ * The borrow that counts `mesh`'s first submitted draw and then gives the mesh its own hook back,
391
+ * keyed by the mesh object — so an object that is replaced has to be handed the borrow of the one
392
+ * it replaces; see `#carryPrewarm`.
393
+ */
394
+ #borrowDraw(
395
+ shared: SharedBatch,
396
+ mesh: InstancedMesh,
397
+ hadOwn: boolean,
398
+ own: unknown,
399
+ epoch = this.#prewarmEpoch,
400
+ ): void {
401
+ const caster = shared.role !== "main";
402
+ const borrow = own as ((...args: unknown[]) => void) | undefined;
403
+ const counted = (...args: unknown[]): void => {
404
+ if (epoch === this.#prewarmEpoch) this.#prewarmDrawn += 1;
405
+ if (caster) {
406
+ this.#prewarmCasterOwed -= 1;
407
+ this.#prewarmCasterDrawn += 1;
408
+ }
409
+ this.#handBack(mesh, hadOwn, own);
410
+ this.#awaited.delete(mesh);
411
+ // The node is built and the pipeline is compiled: the batch owes nothing more, so an empty one
412
+ // goes back to hiding.
413
+ shared.prewarmDrew();
414
+ borrow?.(...args);
415
+ };
416
+ // Engine bookkeeping, not a claim on the mesh: the scene-render projection's `hasRenderHook`
417
+ // ignores a marked borrow, so a streamed world's prewarmed batches stay eligible for the
418
+ // collapse they exist to be folded into. Unmarked, 202 of them permanently declined it.
419
+ markEngineRenderHook(counted);
420
+ this.#awaited.set(mesh, { batch: shared, borrow: counted, own, hadOwn, waited: 0, epoch });
421
+ mesh.onBeforeRender = counted as typeof mesh.onBeforeRender;
422
+ }
423
+
424
+ /**
425
+ * Hand back the borrow of a mesh whose prewarm draw can never come, so no hook outlives the
426
+ * prewarm it served.
427
+ *
428
+ * A mesh that is merely empty now draws — `visible` at count 0 is what builds its node and its
429
+ * pipeline, and the borrow is counted off that one submission — so emptiness is no longer a
430
+ * reason to release anything. What is left is a mesh nothing can draw, and which mesh that is
431
+ * depends on the role: a main batch is drawn by the main pass, so a world projected by nothing
432
+ * (`parent === null`, which is a `load()` loop's prewarm and settles the moment the world joins a
433
+ * scene) still owes it one, while a *caster* is drawn by a shadow level, and a world nothing
434
+ * projects has no level to draw it — its visible-at-count-0 exception is handed straight back
435
+ * rather than held for the whole load. Otherwise a level is a frame's schedule away and the
436
+ * borrow waits `PREWARM_RELEASE_UPDATES` updates for it. That is a ceiling rather than a
437
+ * diagnosis — a projection that collapsed the world, a camera that never reached the mesh, a game
438
+ * that passed no `shadows.invalidate` for the levels to be told by — and it is here so those
439
+ * meshes neither hold a hook nor sit visible at count 0 for the whole walk.
440
+ */
441
+ #releaseImpossibleBorrows(): void {
442
+ const projected = this.#host.parent() !== null;
443
+ for (const [mesh, entry] of [...this.#awaited]) {
444
+ entry.waited += 1;
445
+ const caster = entry.batch.role !== "main";
446
+ if (projected === true && entry.waited < PREWARM_RELEASE_UPDATES) continue;
447
+ if (projected === false && caster === false) continue;
448
+ if (mesh.onBeforeRender === entry.borrow) this.#handBack(mesh, entry.hadOwn, entry.own);
449
+ this.#awaited.delete(mesh);
450
+ if (caster) this.#prewarmCasterOwed -= 1;
451
+ entry.batch.prewarmDrew();
452
+ }
453
+ }
454
+
455
+ /** Give a borrowed mesh back the hook it had, or none at all when it never had one of its own. */
456
+ #handBack(mesh: InstancedMesh, hadOwn: boolean, own: unknown): void {
457
+ if (hadOwn) mesh.onBeforeRender = own as typeof mesh.onBeforeRender;
458
+ // Deleted rather than assigned `undefined`: three calls `object.onBeforeRender(...)`
459
+ // unconditionally, and an own `undefined` shadows the prototype's no-op and throws.
460
+ // quality-allow: the hook must go back to the prototype, which only `delete` can restore.
461
+ // biome-ignore lint/performance/noDelete: restoring the prototype lookup is the point.
462
+ else delete (mesh as Partial<InstancedMesh>).onBeforeRender;
463
+ }
464
+
465
+ /**
466
+ * Every level and every part of one asset, queued to be minted empty: the main key, and the one
467
+ * caster cluster under the follow point. One square because a cluster per cell of the map would
468
+ * be a prewarm of the whole package, and the squares a walk reaches first are minted by
469
+ * residency, two an update.
470
+ */
471
+ queuePrewarm(asset: IAssetState): void {
472
+ this.#prewarmAsked = true;
473
+ const wideKey = `${asset.id}:*@${WIDE_CLUSTER}`;
474
+ for (const [level, parts] of asset.levels.entries()) {
475
+ for (const [part, entry] of parts.entries()) {
476
+ const key = `${asset.id}:${String(level)}:${String(part)}`;
477
+ for (const role of ["main", "cluster", "wide"] as const) {
478
+ const terminalImpostor =
479
+ asset.impostor !== undefined && level === asset.levels.length - 1;
480
+ const terminalFarCaster =
481
+ role === "wide" &&
482
+ terminalImpostor &&
483
+ this.#host.casts(0) &&
484
+ (!this.#host.preserveAuthoredParts() ||
485
+ asset.definition.impostorDistance !== undefined);
486
+ // Only a level that casts has a caster half at all; see `#casts`.
487
+ if (role !== "main" && !this.#host.casts(level) && !terminalFarCaster) continue;
488
+ // One whole-asset representation covers the far shadow; see `#wideOwed`.
489
+ if (role === "wide" && !this.#host.wideOwed(asset.id, part)) continue;
490
+ // A baked impostor's far half is one mesh per asset, not one per level; prewarm the mesh the
491
+ // handoff will keep rather than a per-level key it would retire one frame later.
492
+ const name =
493
+ role === "main"
494
+ ? key
495
+ : role === "wide" &&
496
+ asset.impostor !== undefined &&
497
+ !this.#host.preserveAuthoredParts()
498
+ ? wideKey
499
+ : `${key}@${role === "cluster" ? this.#host.followCluster() : WIDE_CLUSTER}`;
500
+ // A retained key is already paid for; see `#mintPrewarm`.
501
+ if (
502
+ this.#host.hasShared(name) ||
503
+ this.#host.hasRetired(name) ||
504
+ this.#prewarmKeys.has(name)
505
+ )
506
+ continue;
507
+ // The wide half is prewarmed with the same shape the swap draws; see `#wideShape`.
508
+ const shape = role === "wide" ? this.#host.wideShape(asset, level, part, entry) : entry;
509
+ this.#prewarmKeys.add(name);
510
+ this.#prewarmQueue.push({
511
+ asset: asset.id,
512
+ role,
513
+ geometry: shape.geometry,
514
+ key: name,
515
+ level,
516
+ material: shape.material,
517
+ part,
518
+ });
519
+ }
520
+ }
521
+ }
522
+ }
523
+
524
+ #settlePrewarm(): void {
525
+ if (this.#prewarmSettled) return;
526
+ this.#prewarmSettled = true;
527
+ // The one line a walk's log needs to say the prewarm paid what it exists to pay:
528
+ // `shadowPrewarmed` is the casters whose shadow-context node was built behind the gate, and
529
+ // `castersUnbuilt` the ones it could not reach — a non-zero there is the walk-time first shadow
530
+ // build the prewarm was supposed to move, named rather than inferred.
531
+ console.info(
532
+ `TN_WORLD_PREWARM minted=${String(this.#prewarmMinted)} ` +
533
+ `shadowPrewarmed=${String(this.#prewarmCasterDrawn)} ` +
534
+ `castersUnbuilt=${String(Math.max(0, this.#prewarmCasterMinted - this.#prewarmCasterDrawn))}`,
535
+ );
536
+ this.#prewarmResolve();
537
+ }
538
+
539
+ /**
540
+ * Hand a replaced mesh's prewarm borrow to the object that replaced it.
541
+ *
542
+ * The borrow is keyed by the mesh object and counts *that* object's first submitted draw, so an
543
+ * object that goes away before its draw would take the owed draw with it: the batch would sit
544
+ * visible at count 0 for the rest of the load, and the owed counters would never balance. Nothing
545
+ * new is prewarmed here — the batch still owes exactly the one draw it owed.
546
+ */
547
+ carryPrewarm(old: InstancedMesh, next: InstancedMesh): void {
548
+ const batch = this.#drawBatches.get(old);
549
+ if (batch) this.#drawBatches.set(next, batch);
550
+ const entry = this.#awaited.get(old);
551
+ if (entry === undefined) return;
552
+ this.#awaited.delete(old);
553
+ this.#borrowDraw(entry.batch, next, entry.hadOwn, entry.own, entry.epoch);
554
+ }
555
+ constructor(readonlyHost: ICellPrewarmHost) {
556
+ this.#host = readonlyHost;
557
+ }
558
+ readonly #host: ICellPrewarmHost;
559
+ get prewarmed(): Promise<void> {
560
+ return this.#prewarmed;
561
+ }
562
+ get queued(): number {
563
+ return this.#prewarmQueue.length;
564
+ }
565
+ get pending(): number {
566
+ return this.#prewarmPending;
567
+ }
568
+ get owed(): number {
569
+ return this.#prewarmOwed;
570
+ }
571
+ get drawn(): number {
572
+ return this.#prewarmDrawn;
573
+ }
574
+ get minted(): number {
575
+ return this.#prewarmMinted;
576
+ }
577
+ get settled(): boolean {
578
+ return this.#prewarmSettled;
579
+ }
580
+ releaseHooks(): void {
581
+ for (const borrow of this.#drawBorrows.values()) borrow.release();
582
+ for (const [mesh, entry] of [...this.#awaited]) {
583
+ if (mesh.onBeforeRender === entry.borrow) this.#handBack(mesh, entry.hadOwn, entry.own);
584
+ }
585
+ this.#awaited.clear();
586
+ }
587
+ settleDisposal(): void {
588
+ this.#prewarmQueue.length = 0;
589
+ this.#prewarmKeys.clear();
590
+ this.#settlePrewarm();
591
+ }
592
+ }