@threenative/core 0.3.10 → 0.3.12

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