@threenative/core 0.3.11 → 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 (157) 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 +10566 -22552
  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-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,745 @@
1
+ import { type Box3, Vector3 } from "three";
2
+ import type { Camera } from "three";
3
+ import type { IRendererLike } from "./renderer.js";
4
+ import type { CellChunks } from "./world-cell-chunks.js";
5
+ import type {
6
+ IBuildJob,
7
+ IResidentCell,
8
+ IWorldCellsBudget,
9
+ IWorldCellsFollow,
10
+ } from "./world-cell-data.js";
11
+ import { cellKey } from "./world-cell-data.js";
12
+ import { PLACEMENT_RECORD_BYTES } from "./world-cell-impostors.js";
13
+ import type { CellImpostors } from "./world-cell-impostors.js";
14
+ import type { IAssetState } from "./world-cell-models.js";
15
+ import type { CellModels } from "./world-cell-models.js";
16
+ import { ADMISSION_SLICE_PLACEMENTS, SETTLED_FOLLOW_METRES } from "./world-cell-options.js";
17
+ import {
18
+ type CellPlacements,
19
+ newBatches,
20
+ newBoxes,
21
+ publishCount,
22
+ } from "./world-cell-placements.js";
23
+ import type { CellPrewarm } from "./world-cell-prewarm.js";
24
+ import type { CellRender } from "./world-cell-render.js";
25
+ import type { IWorldCell, IWorldRun } from "./world-package.js";
26
+ import {
27
+ type IAdmissionBudget,
28
+ type IWorldTilesLodView,
29
+ TerrainTileBudgetError,
30
+ } from "./world-tiles.js";
31
+ import type { TerrainTiles } from "./world-tiles.js";
32
+
33
+ /** Bytes one resident cell pays for a record: see `#admit`. */
34
+ const LOD_RANGE_RECORD_BYTES = 16;
35
+
36
+ /** The five collaborators a residency pass drives, as one read. */
37
+ interface ICellResidencyParts {
38
+ readonly render: CellRender;
39
+ readonly chunks: CellChunks;
40
+ readonly models: CellModels;
41
+ readonly impostor: CellImpostors;
42
+ readonly prewarm: CellPrewarm;
43
+ readonly placements: CellPlacements;
44
+ readonly terrain: TerrainTiles | undefined;
45
+ }
46
+
47
+ /**
48
+ * What a residency pass asks its world for. The pass owns the ring, the build queue and the counters
49
+ * below; every other number is the world's, read through this interface.
50
+ */
51
+ export interface ICellResidencyHost {
52
+ released(): boolean;
53
+ cells(): readonly IWorldCell[];
54
+ /** The world grid's origin and cell side. */
55
+ extent(): { readonly cellSize: number; readonly minX: number; readonly minZ: number };
56
+ ring(): number;
57
+ budgets(): IWorldCellsBudget;
58
+ follow(): IWorldCellsFollow;
59
+ /** The world's clock: admission pricing and the prefetch lookahead read it. */
60
+ now(): number;
61
+ /** Seconds the ring is led by the follow point's smoothed velocity. */
62
+ prefetchSeconds(): number;
63
+ lodHysteresis(): number;
64
+ /** `camera` or `follow`: where the LOD eye is measured from. */
65
+ lodFrom(): "camera" | "follow";
66
+ asset(id: string): IAssetState | undefined;
67
+ canonical(id: string): string;
68
+ parts(): ICellResidencyParts;
69
+ /** Hands one finished build's shadow bounds to the game's publication hook. */
70
+ published(bounds: Box3): void;
71
+ addFailures(count: number): void;
72
+ }
73
+
74
+ /**
75
+ * The resident ring, the build queue that fills it, and the counters both report.
76
+ *
77
+ * One pass decides which cells are wanted around the follow point and admits what the budgets allow;
78
+ * the queue that follows spends one admission budget on the cell-asset builds it left, nearest cell
79
+ * first, and each build is taken to completion, so a cell draws whole levels. Eviction returns
80
+ * a cell's records to the far aggregate, drops its queued work and releases what it held.
81
+ *
82
+ * The residency decision itself runs only when the follow point moved or something is pending; see
83
+ * `stale`, which is what keeps a standing world from re-deriving the set it already holds.
84
+ */
85
+ export class CellResidency {
86
+ readonly #host: ICellResidencyHost;
87
+ readonly #resident = new Map<string, IResidentCell>();
88
+ /** Cell-asset builds waiting for budget, in admission order: nearest cell first. */
89
+ #jobs: IBuildJob[] = [];
90
+ /** The (cell, run) pairs already queued, so a refilter cannot queue itself twice. */
91
+ readonly #queued = new Set<IWorldRun>();
92
+ readonly #pressure = { cells: 0, instances: 0, bytes: 0 };
93
+ #instances = 0;
94
+ #bytes = 0;
95
+ #evictions = 0;
96
+ /** Completed admission steps; queued, refused and discarded work does not count. */
97
+ #admissionCompletedUnits = 0;
98
+ /** The follow point the last full residency pass ran for; see `stale`. */
99
+ readonly #residencyPoint = new Vector3(Number.NaN, 0, Number.NaN);
100
+ /** No pass has run yet: a fresh world owes its first ring whatever the follow point reads. */
101
+ #passed = false;
102
+ /** Actual cell at the last residency pass; only a jump reclaims retained hysteresis. */
103
+ #residencyCell: { readonly x: number; readonly z: number } | undefined;
104
+ /** Bumped by every admission and eviction, so a residency change owes a refilter that update. */
105
+ #residencyEpoch = 0;
106
+ /** Smoothed follow velocity (m/s) and the sample it was last updated from. */
107
+ #velocityX = 0;
108
+ #velocityZ = 0;
109
+ #lastSample: { readonly x: number; readonly z: number; readonly t: number } | undefined;
110
+ /** The point levels and `maxDistance` are measured from this update; see `updateEye`. */
111
+ readonly #eye = new Vector3();
112
+ /** The follow point `updateEye` pulls the camera toward. */
113
+ readonly #eyeFollow = new Vector3();
114
+ #generation = 0;
115
+ /** The world grid, read once: a package's origin and cell side do not change for a world's life. */
116
+ #grid: { readonly cellSize: number; readonly minX: number; readonly minZ: number } | undefined;
117
+
118
+ constructor(host: ICellResidencyHost) {
119
+ this.#host = host;
120
+ }
121
+
122
+ /** The resident ring, by cell key. */
123
+ get resident(): ReadonlyMap<string, IResidentCell> {
124
+ return this.#resident;
125
+ }
126
+ /** The LOD eye: where this update's levels and `maxDistance` are measured from. */
127
+ get eye(): Vector3 {
128
+ return this.#eye;
129
+ }
130
+ /** Builds waiting for budget. */
131
+ get queuedBuilds(): number {
132
+ return this.#jobs.length;
133
+ }
134
+ get instances(): number {
135
+ return this.#instances;
136
+ }
137
+ get bytes(): number {
138
+ return this.#bytes;
139
+ }
140
+ get residencyEpoch(): number {
141
+ return this.#residencyEpoch;
142
+ }
143
+ /** Whether a build for this cell is still queued, so its content is not finished. */
144
+ hasBuild(cell: IResidentCell): boolean {
145
+ return this.#jobs.some((job) => job.cell === cell);
146
+ }
147
+
148
+ /** The counters a world reports; see `IWorldCellsStats`. */
149
+ counters(): {
150
+ readonly admissionCompletedUnits: number;
151
+ readonly bytes: number;
152
+ readonly evictions: number;
153
+ readonly instances: number;
154
+ readonly pressure: {
155
+ readonly cells: number;
156
+ readonly instances: number;
157
+ readonly bytes: number;
158
+ };
159
+ readonly residentCells: number;
160
+ } {
161
+ return {
162
+ admissionCompletedUnits: this.#admissionCompletedUnits,
163
+ bytes: this.#bytes,
164
+ evictions: this.#evictions,
165
+ instances: this.#instances,
166
+ pressure: { ...this.#pressure },
167
+ residentCells: this.#resident.size,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * One residency pass: the terrain ring follows, then the wanted cells are admitted against the
173
+ * budgets, each one led by the follow point's own lookahead.
174
+ */
175
+ pass(
176
+ x: number,
177
+ z: number,
178
+ budget: IAdmissionBudget,
179
+ renderer: IRendererLike | undefined,
180
+ camera: Camera | undefined,
181
+ terrainView: IWorldTilesLodView | undefined,
182
+ ): void {
183
+ this.#grid ??= this.#host.extent();
184
+ const { cellSize, minX, minZ } = this.#grid;
185
+ this.#passed = true;
186
+ this.#residencyPoint.set(x, this.#host.parts().placements.followY(), z);
187
+ try {
188
+ this.#host.parts().terrain?.follow({ x, z }, budget, terrainView);
189
+ this.#host.parts().terrain?.process(renderer, camera, undefined, terrainView);
190
+ } catch (error) {
191
+ if (!(error instanceof TerrainTileBudgetError)) throw error;
192
+ this.#pressure.bytes += 1;
193
+ }
194
+ const ahead = this.ahead(x, z);
195
+ this.#pass(
196
+ {
197
+ x: Math.floor((ahead.x - minX) / cellSize),
198
+ z: Math.floor((ahead.z - minZ) / cellSize),
199
+ },
200
+ ahead.x,
201
+ ahead.z,
202
+ );
203
+ }
204
+
205
+ /** Evict every resident cell, for a teardown that has already disposed the rest of the world. */
206
+ evictAll(): void {
207
+ for (const cell of [...this.#resident.values()]) this.evict(cell);
208
+ }
209
+
210
+ /**
211
+ * Does this update have to run the residency pass, or is the follow point still inside the half
212
+ * metre it last moved less than and the world holding still?
213
+ *
214
+ * "Still" is every kind of work the pass exists to hand on: a model load in flight or queued, a
215
+ * cell build in `#jobs` (which is also what queues refilters), a prewarm mint owed or in flight, a
216
+ * terrain admission or collider the admission budget refused, and a companion that has not been
217
+ * rebuilt since the follow point last moved. A world standing still on a loaded ring answers none
218
+ * of those, so the pass is skipped; the first update after anything changes is a full pass again.
219
+ */
220
+ stale(x: number, z: number): boolean {
221
+ if (!this.#passed) return true;
222
+ if (
223
+ Math.hypot(
224
+ x - this.#residencyPoint.x,
225
+ this.#host.parts().placements.followY() - this.#residencyPoint.y,
226
+ z - this.#residencyPoint.z,
227
+ ) >= SETTLED_FOLLOW_METRES
228
+ )
229
+ return true;
230
+ return (
231
+ this.#host.parts().models.loadsInFlight > 0 ||
232
+ this.#host.parts().models.loadsQueued > 0 ||
233
+ this.#jobs.length > 0 ||
234
+ this.#host.parts().placements.owed ||
235
+ this.#host.parts().prewarm.queued > 0 ||
236
+ this.#host.parts().prewarm.pending > 0 ||
237
+ this.#host.parts().render.shadowMoved === true ||
238
+ (this.#host.parts().terrain?.deferredAdmissions ?? 0) > 0
239
+ );
240
+ }
241
+
242
+ /**
243
+ * The LOD eye: the render camera's world position, or `follow` before a camera has reached
244
+ * `update` or under `lodFrom: "follow"`. Height counts only where `placementReach` makes the
245
+ * distances 3D, exactly as `#followY` does for the follow point. The camera's offset from
246
+ * `follow` counts only past the world's first gate: an orbit or chase camera inside it grades
247
+ * exactly as `follow` does, so turning in place swaps no level and pays no CPU rebuild, and a
248
+ * camera far off grades from a point at most that gate short of it. Continuous, so a camera
249
+ * resting near the gate does not flip the eye between the two.
250
+ */
251
+ updateEye(): void {
252
+ const follow = this.#eyeFollow.set(
253
+ this.#host.follow().position.x,
254
+ this.#host.parts().placements.followY(),
255
+ this.#host.follow().position.z,
256
+ );
257
+ const camera = this.#host.lodFrom() === "camera" ? this.#host.parts().chunks.camera : undefined;
258
+ if (camera === undefined) {
259
+ this.#eye.copy(follow);
260
+ return;
261
+ }
262
+ this.#eye.setFromMatrixPosition(camera.matrixWorld);
263
+ if (this.#host.parts().placements.placementReach === undefined) this.#eye.y = 0;
264
+ const inside = this.#host.parts().placements.firstGate;
265
+ const offset = this.#eye.distanceTo(follow);
266
+ this.#eye.lerp(follow, offset > inside ? inside / offset : 1);
267
+ }
268
+
269
+ /**
270
+ * Where the ring centres: the follow point led by its smoothed velocity. Samples closer than a
271
+ * few milliseconds are the same frame and move nothing; a jump longer than the ring is a teleport
272
+ * and resets the velocity rather than reading as speed.
273
+ */
274
+ ahead(x: number, z: number): { x: number; z: number } {
275
+ this.#grid ??= this.#host.extent();
276
+ const { cellSize } = this.#grid;
277
+ if (this.#host.prefetchSeconds() === 0) return { x, z };
278
+ const now = this.#host.now();
279
+ const last = this.#lastSample;
280
+ if (last === undefined) {
281
+ this.#lastSample = { t: now, x, z };
282
+ } else {
283
+ const seconds = (now - last.t) / 1000;
284
+ if (seconds >= 0.004) {
285
+ const dx = x - last.x;
286
+ const dz = z - last.z;
287
+ if (Math.hypot(dx, dz) > cellSize * this.#host.ring()) {
288
+ this.#velocityX = 0;
289
+ this.#velocityZ = 0;
290
+ } else {
291
+ // ~0.25 s smoothing, so one jittery frame does not swing the ring.
292
+ const blend = Math.min(1, seconds / 0.25);
293
+ this.#velocityX += (dx / seconds - this.#velocityX) * blend;
294
+ this.#velocityZ += (dz / seconds - this.#velocityZ) * blend;
295
+ }
296
+ this.#lastSample = { t: now, x, z };
297
+ }
298
+ }
299
+ let leadX = this.#velocityX * this.#host.prefetchSeconds();
300
+ let leadZ = this.#velocityZ * this.#host.prefetchSeconds();
301
+ const limit = cellSize * this.#host.ring() * 0.75;
302
+ const length = Math.hypot(leadX, leadZ);
303
+ if (length > limit) {
304
+ leadX *= limit / length;
305
+ leadZ *= limit / length;
306
+ }
307
+ return { x: x + leadX, z: z + leadZ };
308
+ }
309
+
310
+ #pass(followCell: { x: number; z: number }, x: number, z: number): void {
311
+ this.#grid ??= this.#host.extent();
312
+ const { cellSize, minX, minZ } = this.#grid;
313
+ const wanted: Array<{ cell: IWorldCell; distance: number }> = [];
314
+ for (const cell of this.#host.cells()) {
315
+ if (
316
+ Math.max(Math.abs(cell.x - followCell.x), Math.abs(cell.z - followCell.z)) >
317
+ this.#host.ring()
318
+ )
319
+ continue;
320
+ const centerX = minX + (cell.x + 0.5) * cellSize;
321
+ const centerZ = minZ + (cell.z + 0.5) * cellSize;
322
+ wanted.push({ cell, distance: Math.hypot(x - centerX, z - centerZ) });
323
+ }
324
+ wanted.sort((a, b) => a.distance - b.distance || a.cell.z - b.cell.z || a.cell.x - b.cell.x);
325
+
326
+ for (const resident of [...this.#resident.values()]) {
327
+ if (
328
+ Math.max(Math.abs(resident.x - followCell.x), Math.abs(resident.z - followCell.z)) >
329
+ this.#host.ring() + 1
330
+ )
331
+ this.evict(resident);
332
+ }
333
+ // A follow point that crossed more than one cell in one pass jumped (a teleport, a review
334
+ // camera). Only then does the hysteresis ring yield. Read off the follow point itself, not the
335
+ // lookahead `followCell`: that leads by up to 1.5 cells, so a walk that stopped and started moved
336
+ // it by two, and yielding there evicted and re-admitted a whole row each time.
337
+ const here = {
338
+ x: Math.floor((this.#host.follow().position.x - minX) / cellSize),
339
+ z: Math.floor((this.#host.follow().position.z - minZ) / cellSize),
340
+ };
341
+ const last = this.#residencyCell;
342
+ const jumped =
343
+ last !== undefined && Math.max(Math.abs(last.x - here.x), Math.abs(last.z - here.z)) > 1;
344
+ this.#residencyCell = here;
345
+
346
+ for (const candidate of wanted) {
347
+ const key = cellKey(candidate.cell.x, candidate.cell.z);
348
+ if (this.#resident.has(key)) continue;
349
+ const instances = candidate.cell.runs.reduce((total, run) => total + run.count, 0);
350
+ const rangeRoots =
351
+ this.#host.lodHysteresis() > 0 && !this.#host.parts().render.gpuOn ? instances : 0;
352
+ // One 16 B range record per root, which is what the batch allocates for them
353
+ // (`capacity * LOD_RANGE_STRIDE` in world-cell-batches.ts); the repack scratch that copies
354
+ // them is one shared pool, not a second record per cell.
355
+ const bytes = instances * PLACEMENT_RECORD_BYTES + rangeRoots * LOD_RANGE_RECORD_BYTES;
356
+ // After a jump, a cell the one-ring hysteresis above kept is not wanted, so it yields its share
357
+ // of the budgets to one that is. Without this the budgets stayed full of the ring the camera
358
+ // jumped from and the cells around it were refused until it moved again.
359
+ while (
360
+ jumped &&
361
+ (this.#resident.size >= this.#host.budgets().residentCells ||
362
+ this.#instances + this.#host.parts().impostor.farInstances + instances >
363
+ this.#host.budgets().instances ||
364
+ this.#bytes +
365
+ this.#host.parts().impostor.farBytes +
366
+ this.#host.parts().chunks.bytes +
367
+ bytes >
368
+ this.#host.budgets().bytes)
369
+ ) {
370
+ const spare = this.#farthestUnwanted(followCell);
371
+ if (spare === undefined) break;
372
+ this.evict(spare);
373
+ }
374
+ if (this.#resident.size >= this.#host.budgets().residentCells) {
375
+ this.#pressure.cells += 1;
376
+ continue;
377
+ }
378
+ // The retained far aggregates are physical allocations the renderer holds too, so they are
379
+ // charged against the same declared limits as the near ring: admitting a cell over the top of
380
+ // them would put the world past `budgets.instances`/`budgets.bytes` with the far half invisible
381
+ // to this check. See `#farBudgetRefuses`, the far half of the same total.
382
+ if (
383
+ this.#instances + this.#host.parts().impostor.farInstances + instances >
384
+ this.#host.budgets().instances
385
+ ) {
386
+ this.#pressure.instances += 1;
387
+ continue;
388
+ }
389
+ if (
390
+ this.#bytes +
391
+ this.#host.parts().impostor.farBytes +
392
+ this.#host.parts().chunks.bytes +
393
+ bytes >
394
+ this.#host.budgets().bytes
395
+ ) {
396
+ this.#pressure.bytes += 1;
397
+ continue;
398
+ }
399
+ this.#admit(candidate.cell, instances, bytes);
400
+ }
401
+ }
402
+
403
+ /** The resident cell farthest outside the wanted ring, or none when every resident is wanted. */
404
+ #farthestUnwanted(followCell: { x: number; z: number }): IResidentCell | undefined {
405
+ let farthest: IResidentCell | undefined;
406
+ let reach = this.#host.ring();
407
+ for (const resident of this.#resident.values()) {
408
+ const away = Math.max(
409
+ Math.abs(resident.x - followCell.x),
410
+ Math.abs(resident.z - followCell.z),
411
+ );
412
+ if (away > reach) {
413
+ reach = away;
414
+ farthest = resident;
415
+ }
416
+ }
417
+ return farthest;
418
+ }
419
+
420
+ #admit(cell: IWorldCell, instances: number, bytes: number): void {
421
+ const state: IResidentCell = {
422
+ mainChunkMeshes: [],
423
+ chunkInstances: new Map(),
424
+ completedRuns: new Set(),
425
+ chunksLoaded: (cell.chunks?.length ?? 0) === 0,
426
+ chunkFailed: false,
427
+ batches: [],
428
+ bytes,
429
+ cell,
430
+ chunks: [],
431
+ filterFar: Number.NEGATIVE_INFINITY,
432
+ filterNear: Number.POSITIVE_INFINITY,
433
+ generation: this.#generation++,
434
+ instances,
435
+ key: cellKey(cell.x, cell.z),
436
+ retainedModelPaths: [],
437
+ x: cell.x,
438
+ z: cell.z,
439
+ };
440
+ this.#resident.set(state.key, state);
441
+ this.#host.parts().render.cullResident(cell);
442
+ this.#residencyEpoch += 1;
443
+ this.#instances += instances;
444
+ this.#bytes += bytes;
445
+ for (const run of cell.runs) this.#host.parts().models.acquire(run, state);
446
+ if (cell.chunks !== undefined && cell.chunks.length > 0)
447
+ this.#host.parts().chunks.startChunkLoad(state);
448
+ }
449
+
450
+ /**
451
+ * Ask for one cell-asset run to be built, and do not build it yet.
452
+ *
453
+ * Admission is the only thing in this class that has no frame-time ceiling, so it is the only
454
+ * thing that became a queue: the cell keeps its residency slot from `#admit`, the work waits for
455
+ * a frame with budget in it, and a game that outruns the backlog sees it as `admission.backlog`
456
+ * rather than as a frozen frame. A run already queued is not queued twice, which is what stops a
457
+ * refilter — stale for as many frames as it waits — from stacking a second copy of itself.
458
+ *
459
+ * `replaced` is a refilter's outgoing batches, captured now and kept drawn until the replacement
460
+ * is attached, so a rebuild that waits three frames shows the old level for those three frames
461
+ * instead of a hole.
462
+ */
463
+ queueBuild(
464
+ asset: IAssetState,
465
+ cell: IResidentCell,
466
+ run: IWorldRun,
467
+ replace = false,
468
+ force = false,
469
+ ): void {
470
+ // Keyed on the run, not the asset: one cell can hold two runs of the same canonical asset —
471
+ // two names for one model — and each has its own records to build. A token per asset made the
472
+ // second run a no-op and dropped its placements on the floor.
473
+ if (this.#queued.has(run)) return;
474
+ // A cell that already draws this run is not built again, which is where an adopted asset's
475
+ // second acquire over a still-resident cell lands.
476
+ if (!replace && cell.batches.some((entry) => entry.asset === asset.id && entry.run === run))
477
+ return;
478
+ this.#queued.add(run);
479
+ this.#jobs.push({
480
+ asset,
481
+ batches: undefined,
482
+ boxes: undefined,
483
+ placed: undefined,
484
+ lodRanges: undefined,
485
+ cell,
486
+ force,
487
+ gpuByLevel: undefined,
488
+ filterY: this.#host.parts().placements.followY(),
489
+ filterX: this.#host.follow().position.x,
490
+ filterZ: this.#host.follow().position.z,
491
+ lodX: this.#eye.x,
492
+ lodY: this.#eye.y,
493
+ lodZ: this.#eye.z,
494
+ fresh: [],
495
+ replacement: replace,
496
+ next: 0,
497
+ published: 0,
498
+ records: undefined,
499
+ replaced: replace
500
+ ? cell.batches.filter((entry) => entry.asset === asset.id && entry.run === run)
501
+ : [],
502
+ roots: undefined,
503
+ run,
504
+ sources: undefined,
505
+ });
506
+ }
507
+
508
+ /**
509
+ * Spend the frame's budget on queued builds, one unit each, and stop when it is gone.
510
+ *
511
+ * The queue is served in admission order, which is nearest cell first, and a build is taken to
512
+ * completion before the next one starts: the units of one run are cheaper together than the
513
+ * per-frame bookkeeping of interleaving them, and the cell behind it is the same distance away.
514
+ * A build whose cell or asset has gone is dropped rather than resumed — there is nothing left to
515
+ * draw it into — and a frame that runs out of budget leaves the rest of the queue for the next.
516
+ */
517
+ drain(budget: IAdmissionBudget): void {
518
+ const index = 0;
519
+ while (index < this.#jobs.length) {
520
+ this.#frontNearest();
521
+ const job = this.#jobs[index] as IBuildJob;
522
+ if (this.#resident.get(job.cell.key) !== job.cell || job.asset.levels.length === 0) {
523
+ this.#forget(index, job);
524
+ continue;
525
+ }
526
+ let finished = false;
527
+ if (
528
+ !budget.admit(() => {
529
+ finished = this.#step(job);
530
+ })
531
+ )
532
+ break;
533
+ // Out of fresh meshes this frame: later jobs would only stall the same way.
534
+ if (this.#host.parts().render.meshStalled) break;
535
+ // A finished build leaves the queue at this index, so the next one is served without a skip.
536
+ if (finished) {
537
+ for (const entry of job.fresh)
538
+ if (entry.batch.count > 0 && entry.shadowBounds !== undefined)
539
+ this.#host.published(entry.shadowBounds);
540
+ job.cell.completedRuns.add(job.run);
541
+ this.#forget(index, job);
542
+ // A camera that moved during this bounded build may already have consumed the global
543
+ // refilter step before these batches existed. Owe one pass after publication, even if
544
+ // it now stands still, so the coherent old snapshot can converge to the latest pose.
545
+ if (
546
+ Math.hypot(
547
+ this.#host.follow().position.x - job.filterX,
548
+ this.#host.parts().placements.followY() - job.filterY,
549
+ this.#host.follow().position.z - job.filterZ,
550
+ ) >= this.#host.parts().placements.stepMetres()
551
+ )
552
+ this.#host.parts().placements.owe();
553
+ }
554
+ }
555
+ }
556
+
557
+ /**
558
+ * Put the unstarted build nearest the follow point at the front, unless a build is mid-way.
559
+ * Each model's load queues every resident cell at once, so append order is load order: the
560
+ * spawn cell of the last model to load waited behind the whole ring.
561
+ */
562
+ #frontNearest(): void {
563
+ this.#grid ??= this.#host.extent();
564
+ const { cellSize, minX, minZ } = this.#grid;
565
+ const front = this.#jobs[0];
566
+ if (front === undefined || front.next > 0 || front.batches !== undefined) return;
567
+ const { x, z } = this.#host.follow().position;
568
+ let nearest = 0;
569
+ let best = Number.POSITIVE_INFINITY;
570
+ for (let i = 0; i < this.#jobs.length; i++) {
571
+ const job = this.#jobs[i] as IBuildJob;
572
+ if (job.next > 0 || job.batches !== undefined) continue;
573
+ const d = Math.hypot(
574
+ minX + (job.cell.x + 0.5) * cellSize - x,
575
+ minZ + (job.cell.z + 0.5) * cellSize - z,
576
+ );
577
+ if (d < best) {
578
+ best = d;
579
+ nearest = i;
580
+ }
581
+ }
582
+ if (nearest > 0) this.#jobs.unshift(...this.#jobs.splice(nearest, 1));
583
+ }
584
+
585
+ #forget(index: number, job: IBuildJob): void {
586
+ this.#jobs.splice(index, 1);
587
+ this.#queued.delete(job.run);
588
+ }
589
+
590
+ /** Placement slices and meshes left to publish, plus the terrain's outstanding admission. */
591
+ backlog(): number {
592
+ let units = this.#host.parts().terrain?.deferredAdmissions ?? 0;
593
+ for (const job of this.#jobs) {
594
+ const meshes = job.batches === undefined ? 0 : publishCount(job.batches);
595
+ units +=
596
+ Math.ceil(Math.max(0, job.run.count - job.next) / ADMISSION_SLICE_PLACEMENTS) +
597
+ Math.max(0, meshes - job.published);
598
+ }
599
+ return units;
600
+ }
601
+
602
+ /**
603
+ * One unit of one build: a slice of placements, or one mesh built, or the swap that attaches the
604
+ * finished batch and retires what a refilter replaced. `true` means the job is done.
605
+ */
606
+ #step(job: IBuildJob): boolean {
607
+ // A queued run may wait behind admission or fresh-mesh work while the camera moves.
608
+ // Take its filter snapshot when the first placement slice actually starts, then keep
609
+ // that snapshot for every slice so one publication never mixes different camera poses.
610
+ if (job.next === 0 && job.batches === undefined) {
611
+ job.filterX = this.#host.follow().position.x;
612
+ job.filterY = this.#host.parts().placements.followY();
613
+ job.filterZ = this.#host.follow().position.z;
614
+ job.lodX = this.#eye.x;
615
+ job.lodY = this.#eye.y;
616
+ job.lodZ = this.#eye.z;
617
+ }
618
+ if (job.next < job.run.count) {
619
+ job.batches ??= newBatches(job.asset);
620
+ if (this.#host.lodHysteresis() > 0 && job.asset.distances.length > 1)
621
+ job.lodRanges ??= job.batches.map((levels) => levels.map(() => []));
622
+ // One box per `(level, part)` beside the batches it measures, so the swap that hands the
623
+ // records to the renderer can name where they are; see `#addPlacements`.
624
+ job.boxes ??= newBoxes(job.batches);
625
+ const end = Math.min(job.next + ADMISSION_SLICE_PLACEMENTS, job.run.count);
626
+ this.#host.parts().placements.addPlacements(job, job.next, end);
627
+ job.next = end;
628
+ this.#admissionCompletedUnits += 1;
629
+ return false;
630
+ }
631
+ const batches = job.batches;
632
+ // A run with nothing placed in it publishes nothing, exactly as an unbounded build would.
633
+ if (batches === undefined) return true;
634
+ if (job.published < publishCount(batches)) {
635
+ const published = job.published;
636
+ this.#host.parts().placements.buildOne(job, batches);
637
+ if (job.published > published) this.#admissionCompletedUnits += 1;
638
+ return false;
639
+ }
640
+ const swapped = this.#host.parts().render.swap(job);
641
+ if (swapped) this.#admissionCompletedUnits += 1;
642
+ return swapped;
643
+ }
644
+
645
+ /**
646
+ * Rebuild every resident run once, so a scene that came up after the ring was built is given the
647
+ * source records it was built without.
648
+ *
649
+ * `WorldCells.update` can be called before it has a renderer, and a renderer that is not WebGPU
650
+ * never turns the scene on at all; either way the cells that were swapped in while it was off hold
651
+ * placements the dispatches have never heard of, and nothing else in the class would ever hand them
652
+ * over. One rebuild of the ring is the whole fix, and it is the same build every first-seen asset
653
+ * takes: `replace` keeps the old batches drawn until each new one is attached, so the rebuild is
654
+ * not a frame of holes.
655
+ */
656
+ seedGpuSources(): void {
657
+ // A pending build may already have consumed CPU-only slices. Restart it before any swap can
658
+ // publish a partial source list; its outgoing batches keep drawing until the new build lands.
659
+ const pending = this.#jobs;
660
+ this.#jobs = [];
661
+ for (const job of pending) {
662
+ this.#queued.delete(job.run);
663
+ for (const entry of job.fresh) this.#host.parts().render.clearSegment(entry);
664
+ this.queueBuild(job.asset, job.cell, job.run, true, job.force);
665
+ }
666
+ for (const cell of this.#resident.values())
667
+ for (const batch of cell.batches) {
668
+ const asset = this.#host.parts().models.asset(batch.asset);
669
+ if (asset === undefined || asset.levels.length === 0) continue;
670
+ // One rebuild per run, not per batch: a run's placements are one build, and queueing it per
671
+ // batch would rebuild the same placements once per level and part.
672
+ this.queueBuild(asset, cell, batch.run, true);
673
+ }
674
+ }
675
+
676
+ cellLive(cell: IResidentCell, generation: number): boolean {
677
+ return (
678
+ !this.#host.released() &&
679
+ this.#resident.get(cell.key) === cell &&
680
+ cell.generation === generation
681
+ );
682
+ }
683
+
684
+ evict(cell: IResidentCell): void {
685
+ this.#host.parts().chunks.evictProxy(cell);
686
+ this.#residencyEpoch += 1;
687
+ // Every run this cell held goes back to the far mesh BEFORE the near batches below are cleared:
688
+ // the far mesh owns the ORIGINAL roots and this is the same synchronous block, so no frame draws
689
+ // the cell twice or not at all. Skipped at teardown, where the far aggregates are drained whole.
690
+ if (!this.#host.released())
691
+ for (const run of cell.cell.runs) this.#host.parts().impostor.restoreFar(run);
692
+ // Work queued for a cell that has left is dropped, not resumed: a later frame would build
693
+ // batches into a graph that no longer holds the cell, and the residency slot is already gone.
694
+ this.#jobs = this.#jobs.filter((job) => {
695
+ if (job.cell !== cell) return true;
696
+ this.#queued.delete(job.run);
697
+ // A swap that ran out of fresh meshes leaves its claims in `fresh`, which is not in
698
+ // `cell.batches` until the swap completes. Dropping the job without handing those blocks back
699
+ // keeps them reserved and unwritten, so `mesh.count` never falls to zero, the asset's release
700
+ // retires a batch that still counts records and drops the key outright, and the walk back
701
+ // mints a second mesh for it.
702
+ for (const entry of job.fresh) this.#host.parts().render.clearSegment(entry);
703
+ return false;
704
+ });
705
+ for (const entry of cell.batches) this.#host.parts().render.clearSegment(entry);
706
+ // The same invalidation `#swap` makes, for the eviction path: the records that just left the
707
+ // ring are ground the levels were drawing, and they are named one batch at a time.
708
+ // Each placement's own box when the cell kept the list, so an evicted neighbour does not redraw
709
+ // the finest level under the player; the batch union otherwise.
710
+ if (cell.placed !== undefined && cell.placed.size > 0)
711
+ for (const placed of cell.placed.values())
712
+ this.#host.parts().render.tellPlacementChanges(placed, []);
713
+ else
714
+ this.#host
715
+ .parts()
716
+ .render.shadowRecordsMoved(this.#host.parts().render.changedBounds(cell.batches));
717
+ cell.batches.length = 0;
718
+ cell.placed?.clear();
719
+ // The cell's record of those chunks goes with them, so a replay can never draw a cell the world
720
+ // has released — before they leave the group, which is where it counts what it holds. See
721
+ // `#addChunk`.
722
+ this.#host.parts().render.dropChunkBundles(cell);
723
+ for (const chunk of cell.chunks) {
724
+ chunk.removeFromParent();
725
+ this.#host.addFailures(this.#host.parts().models.disposeLoaded(chunk));
726
+ }
727
+ cell.chunks.length = 0;
728
+ // The cell's chunk sources go back to the loader here, on the last cell that named them, exactly
729
+ // as an asset's levels do in `#release`. Run even at teardown: the loader is never cleared, so a
730
+ // path this world asked for must be handed back however the world leaves.
731
+ this.#host.parts().models.releaseModelPaths(cell.retainedModelPaths);
732
+ this.#resident.delete(cell.key);
733
+ this.#host.parts().render.cullEvicted(cell);
734
+ this.#instances -= cell.instances;
735
+ this.#bytes -= cell.bytes;
736
+ this.#evictions += 1;
737
+ // Room just freed: retry the far aggregates a full budget refused, so a species held back while
738
+ // the ring was tight appears without another scan. Skipped at teardown, where the far half drains.
739
+ if (!this.#host.released()) this.#host.parts().impostor.retryFar();
740
+ // One per run, so the canonical's refcount reaches zero exactly when the last run naming any
741
+ // member of its group has left the ring.
742
+ for (const run of cell.cell.runs)
743
+ this.#host.parts().models.release(this.#host.canonical(run.asset));
744
+ }
745
+ }