@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,1074 @@
1
+ import { type BufferGeometry, type Material, Matrix4, Mesh, Object3D, SkinnedMesh } from "three";
2
+ import { type IAssetLoader, createAssetLoader } from "./assets.js";
3
+ import { type ILodChain, lodChainOf } from "./model-lod.js";
4
+ import { displacesVertices } from "./projection-plan.js";
5
+ import { cutoutSurface } from "./render/foliage-alpha.js";
6
+ import { materialKey } from "./render/material-key.js";
7
+ import { dropPooledFor } from "./render/mesh-pool.js";
8
+ import { levelTriangles, release, resolveRelative } from "./world-cell-chunks.js";
9
+ import type { IAssetPart, IResidentCell, IWorldCellsLoadOptions } from "./world-cell-data.js";
10
+ import { positiveInteger } from "./world-cell-data.js";
11
+ import {
12
+ DEFAULT_CUTOUT_ALPHA,
13
+ type IImpostorState,
14
+ cullDistance,
15
+ isAlphaFoliage,
16
+ } from "./world-cell-impostors.js";
17
+ import { cellProxySourceSafe } from "./world-cell-proxy.js";
18
+ import { worldOwned } from "./world-chunk-shadow.js";
19
+ import { ModelLoadLimiter } from "./world-load-limiter.js";
20
+ import type { IWorldAsset, IWorldPackage, IWorldRun } from "./world-package.js";
21
+
22
+ /** A surface every part with the same material content draws with, and who still uses it. */
23
+ interface ISharedSurface {
24
+ readonly material: Material;
25
+ /** The canonical source and any cutout made from it, torn down with the last user. */
26
+ readonly owned: readonly Material[];
27
+ users: number;
28
+ }
29
+
30
+ export interface IAssetState {
31
+ readonly id: string;
32
+ readonly definition: IWorldAsset;
33
+ /**
34
+ * The distance at which each level takes over, index-aligned with `glbs`; level 0 never does.
35
+ *
36
+ * Mutable because a chain is only known once the asset's own model has loaded: an asset with no
37
+ * authored `lods` is widened with the levels that model's baked chain carries, and every consumer
38
+ * of this reads it at build time — after `#adoptAsset` — so nothing has to be rebuilt.
39
+ */
40
+ distances: readonly number[];
41
+ /** The package-relative GLB per level, index-aligned with `distances`. */
42
+ readonly glbs: readonly string[];
43
+ /**
44
+ * The scene each level draws, index-aligned with `glbs`; `undefined` means the file's own default
45
+ * scene, which is every package that stores one level per file.
46
+ */
47
+ readonly scenes: readonly (string | undefined)[];
48
+ /** Every distance the level or cull answer changes at, `threshold` being the nearest. */
49
+ gates: readonly number[];
50
+ /** The nearest distance this asset's batching can be crossed at, or `undefined` when it cannot. */
51
+ threshold: number | undefined;
52
+ refcount: number;
53
+ hlodSafe: boolean;
54
+ pending: boolean;
55
+ failed: boolean;
56
+ disposed: boolean;
57
+ /**
58
+ * The exact `assets.model` cache paths this state asked the loader for, held in `#modelPaths`
59
+ * until the last state naming each one is released. Empty when `loadModel` bypasses the cache;
60
+ * filled once per state, so a load retried after an empty answer does not count twice.
61
+ */
62
+ retainedPaths: string[];
63
+ /**
64
+ * One part list per entry in `glbs`, so a level that failed to load reuses the level below it and
65
+ * the batch builder never has to know a level is missing.
66
+ */
67
+ levels: readonly (readonly IAssetPart[])[];
68
+ /**
69
+ * Parts taken out of DRAW but still owned here until teardown. Authored levels now keep their own
70
+ * geometry, so this stays empty; it is drained once with the asset on release.
71
+ */
72
+ spilled: readonly IAssetPart[];
73
+ /**
74
+ * The loader's resolved cooked url for LOD0, recorded at load. It is the atlas cache key's model
75
+ * half, so two package entries that fetch the same cooked bytes share one bake even when their
76
+ * `lods`/`maxDistance` metadata stopped them aliasing. See `#impostorKey`.
77
+ */
78
+ resolvedGlb: string;
79
+ /** The whole-asset impostor level this asset appended, once its bake landed. See `#finishImpostor`. */
80
+ impostor?: IImpostorState;
81
+ }
82
+
83
+ export async function loadModelWith(
84
+ assets: IAssetLoader,
85
+ path: string,
86
+ sceneName?: string,
87
+ ): Promise<Object3D> {
88
+ // A cell load is one the ring asks for ahead of the camera, so it takes `soon`: a direct
89
+ // `ctx.assets.model` call from the running scene still starts first.
90
+ const gltf = await assets.model<{ scene?: Object3D; scenes?: Object3D[] }>(path, {
91
+ priority: "soon",
92
+ });
93
+ // One file can hold every level of a model; its levels select a scene instead of a file. Each
94
+ // level is then its own scene graph sharing that file's textures, never a second parse.
95
+ const scene =
96
+ sceneName === undefined ? gltf?.scene : gltf?.scenes?.find((s) => s.name === sceneName);
97
+ if (!(scene instanceof Object3D))
98
+ throw new Error(
99
+ sceneName === undefined
100
+ ? `World asset '${path}' loaded without an Object3D scene.`
101
+ : `World asset '${path}' has no scene '${sceneName}'.`,
102
+ );
103
+ return scene;
104
+ }
105
+
106
+ /**
107
+ * Mip compensation for scattered foliage. Golus's 0.25 suits dense cards; a needle atlas at ~9 %
108
+ * coverage averages to ~0.09 alpha by mip 8, where a tree 150 m out samples, so 0.25 still drops
109
+ * every needle. 0.75 keeps the cutoff under that average through mip 8.
110
+ * ponytail: one tuned constant; coverage-preserving mips at cook time are the upgrade path.
111
+ */
112
+ const SCATTER_MIP_ALPHA_SCALE = 0.75;
113
+
114
+ /**
115
+ * The surface a scattered part draws with, and the cutout this class owns when it made one.
116
+ *
117
+ * An `InstancedMesh` cannot sort its instances, so a `transparent` material on scattered foliage
118
+ * draws in submission order — wrong against itself, and overdraw on top of it. A cutout keeps the
119
+ * part's own alpha shape, keeps the depth buffer, and lets the draw reject what is behind it. The
120
+ * GLB's material is never mutated: the cutout is per asset part, so every cell batch of the asset
121
+ * shares one and a game that still wants blending asks for it.
122
+ *
123
+ * The cutout itself is `cutoutSurface`, because a cutout that ignores the mip chain deletes itself
124
+ * at distance: the needle card's mips average to a tenth, and every needle is discarded.
125
+ */
126
+ function scatterMaterial(
127
+ material: Material,
128
+ transparentScatter: "cutout" | "blend",
129
+ ): { readonly material: Material; readonly owned: readonly Material[] } {
130
+ if (transparentScatter === "blend" || !material.transparent)
131
+ return { material, owned: [material] };
132
+ const cutout = cutoutSurface(
133
+ material,
134
+ material.alphaTest > 0 ? material.alphaTest : DEFAULT_CUTOUT_ALPHA,
135
+ SCATTER_MIP_ALPHA_SCALE,
136
+ );
137
+ // The authored material is owned too: the batch draws the cutout, and the GLB's own surface is
138
+ // still this asset's to hand back.
139
+ worldOwned.add(cutout);
140
+ return { material: cutout, owned: [material, cutout] };
141
+ }
142
+
143
+ /**
144
+ * Every drawable part of a loaded model: one per `Mesh`, each with its shape, its surface, and
145
+ * where it sits relative to the model root.
146
+ *
147
+ * A GLB authored as a tree — bark `OPAQUE`, needles `BLEND` — is one node carrying one mesh with
148
+ * two primitives, which three loads as a `Group` of one child `Mesh` per primitive. Taking only the
149
+ * first of those drew 62k bare trunks, so every one of them is a part and each keeps its own
150
+ * material.
151
+ *
152
+ * `SkinnedMesh` is skipped deliberately: its vertices are posed per frame from a skeleton, and one
153
+ * `InstancedMesh` of the geometry would draw the rest pose once per placement. `Points` and
154
+ * `LineSegments` are not `Mesh`es and are skipped with them.
155
+ */
156
+ function renderableParts(
157
+ model: Object3D,
158
+ surfaceFor: (material: Material) => { readonly key: string; readonly material: Material },
159
+ ): readonly IAssetPart[] {
160
+ model.updateMatrixWorld(true);
161
+ const rootInverse = new Matrix4().copy(model.matrixWorld).invert();
162
+ const local = new Matrix4();
163
+ const parts: IAssetPart[] = [];
164
+ model.traverse((object: Object3D) => {
165
+ if (object instanceof SkinnedMesh || !(object instanceof Mesh)) return;
166
+ const material = Array.isArray(object.material) ? object.material[0] : object.material;
167
+ if (object.geometry === undefined || material === undefined) return;
168
+ const surface = surfaceFor(material);
169
+ parts.push({
170
+ geometry: object.geometry,
171
+ local: local.multiplyMatrices(rootInverse, object.matrixWorld).clone(),
172
+ material: surface.material,
173
+ surface: surface.key,
174
+ });
175
+ });
176
+ return parts;
177
+ }
178
+
179
+ function disposeModel(model: Object3D): number {
180
+ let failed = 0;
181
+ model.traverse((object: Object3D) => {
182
+ if (!(object instanceof Mesh)) return;
183
+ if (release(object.geometry)) failed += 1;
184
+ const materials: Material[] = Array.isArray(object.material)
185
+ ? object.material
186
+ : [object.material];
187
+ // A world-owned surface is one chunk's proxy material, and the next chunk's teardown would
188
+ // otherwise release a material this world's remaining proxies are still drawing with. It is
189
+ // released with the world that owns it; see `WorldCells#dispose`.
190
+ for (const material of materials)
191
+ if (!worldOwned.has(material) && release(material)) failed += 1;
192
+ });
193
+ return failed;
194
+ }
195
+
196
+ /**
197
+ * The levels one asset is drawn at, and the distances its batching can be crossed at.
198
+ *
199
+ * Level 0 is the asset's own `glb` and never switches; `lods[i - 1].distance` is where an instance
200
+ * that far out draws `lods[i]` instead. A `lods` entry at or beyond the cull distance is dropped:
201
+ * an instance that far out is culled, so its shape can never be drawn. `gates` is every distance
202
+ * the level or cull answer changes at — `threshold` is the nearest of them, so a follow point that
203
+ * has moved an eighth of it may have moved an instance either way.
204
+ */
205
+ function assetLevels(definition: IWorldAsset): {
206
+ readonly distances: readonly number[];
207
+ readonly gates: readonly number[];
208
+ readonly glbs: readonly string[];
209
+ readonly scenes: readonly (string | undefined)[];
210
+ readonly threshold: number | undefined;
211
+ } {
212
+ const maxDistance = definition.maxDistance;
213
+ const distances: number[] = [0];
214
+ const glbs: string[] = [definition.glb];
215
+ const scenes: (string | undefined)[] = [undefined];
216
+ const gates: number[] = [];
217
+ for (const lod of definition.lods ?? []) {
218
+ // A level at or beyond the cull distance is never drawn: an instance that far out is gone by
219
+ // the time the level would take over, so its GLB is never asked for.
220
+ if (maxDistance !== undefined && lod.distance >= maxDistance) continue;
221
+ distances.push(lod.distance);
222
+ glbs.push(lod.glb);
223
+ scenes.push(lod.scene);
224
+ gates.push(lod.distance);
225
+ }
226
+ const cull = cullDistance(maxDistance);
227
+ if (cull !== undefined) gates.push(cull);
228
+ return {
229
+ distances,
230
+ gates,
231
+ glbs,
232
+ scenes,
233
+ threshold: gates.length === 0 ? undefined : Math.min(...gates),
234
+ };
235
+ }
236
+
237
+ /**
238
+ * The batched shape of one definition, as the loader will actually fetch it: the url the manifest
239
+ * gives its `glb`, the url and switch distance of every `lods` entry in order, its `maxDistance` and
240
+ * its bounds. Two definitions that agree on all of it are the same draw — same geometry, same
241
+ * materials, same levels, same gates — so one model serves both and their placements batch together.
242
+ *
243
+ * `undefined` when the loader cannot resolve a path at all: a path the manifest does not list makes
244
+ * `resolve` throw, and the load that asks for it will say so. Such a definition never aliases,
245
+ * which is the same behaviour it has today.
246
+ */
247
+ async function assetSignature(
248
+ assets: IAssetLoader,
249
+ definition: IWorldAsset,
250
+ logicalBase: string,
251
+ ): Promise<string | undefined> {
252
+ const url = async (glb: string): Promise<string> => {
253
+ const candidates = await assets.resolve(resolveRelative(logicalBase, glb));
254
+ return candidates[0] ?? glb;
255
+ };
256
+ try {
257
+ const parts = [await url(definition.glb)];
258
+ // A scene names the level inside a shared file, so two levels of one file never alias.
259
+ for (const lod of definition.lods ?? [])
260
+ parts.push(`${await url(lod.glb)}#${lod.scene ?? ""}@${String(lod.distance)}`);
261
+ parts.push(
262
+ definition.maxDistance === undefined ? "" : String(definition.maxDistance),
263
+ definition.impostorDistance === undefined ? "" : String(definition.impostorDistance),
264
+ definition.bounds.min.join(","),
265
+ definition.bounds.max.join(","),
266
+ );
267
+ return parts.join("|");
268
+ } catch {
269
+ return undefined;
270
+ }
271
+ }
272
+
273
+ /**
274
+ * `alias id -> canonical id` for every definition that is another name for the same cooked model,
275
+ * which is what a 374-asset package with 273 duplicates is: one model exported under many object
276
+ * names, cooked once and fetched once.
277
+ *
278
+ * The canonical is the lexicographically smallest id of the group, so it does not depend on the
279
+ * order the exporter happened to write them in. An empty map — every definition its own model, or a
280
+ * package whose paths resolve to nothing — leaves the whole runtime exactly as it is.
281
+ */
282
+ export async function assetAliases(
283
+ assets: IAssetLoader,
284
+ manifest: IWorldPackage,
285
+ logicalBase: string,
286
+ ): Promise<ReadonlyMap<string, string>> {
287
+ const canonicalBySignature = new Map<string, string>();
288
+ const aliases = new Map<string, string>();
289
+ // Sorted, so the first id to claim a signature is the smallest one in its group.
290
+ for (const id of Object.keys(manifest.assets).sort()) {
291
+ const definition = manifest.assets[id];
292
+ if (definition === undefined) continue;
293
+ const signature = await assetSignature(assets, definition, logicalBase);
294
+ if (signature === undefined) continue;
295
+ const canonical = canonicalBySignature.get(signature);
296
+ if (canonical === undefined) canonicalBySignature.set(signature, id);
297
+ else aliases.set(id, canonical);
298
+ }
299
+ return aliases;
300
+ }
301
+
302
+ /** What a baked chain gives a batched draw: the extra levels, where they take over, what they cost. */
303
+ interface IChainLevels {
304
+ /** Index-aligned with `distances`; index 0 is the parts the asset already had. */
305
+ readonly levels: (readonly IAssetPart[])[];
306
+ /** `distances[0]` is 0 and never switches; the rest are the synthesized switch distances. */
307
+ readonly distances: number[];
308
+ /** Triangles every level submits, all its parts together, index-aligned with `levels`. */
309
+ readonly triangles: number[];
310
+ }
311
+
312
+ /**
313
+ * The extra levels an asset's baked AutoLOD chain gives a batched draw, or `undefined` when none of
314
+ * its parts carries a chain.
315
+ *
316
+ * A `ModelLod` swaps one mesh's geometry, so a world that batches thousands of placements of one
317
+ * model into a handful of instanced draws never reaches that selection: every placement drew
318
+ * LOD0, which on a 2 km map is the whole triangle bill at every distance. The chain already holds
319
+ * the reduced shapes, so this derives the levels a batch can hold and the distance each one takes
320
+ * over at — the same screen-space test `ModelLod` runs, solved for depth:
321
+ * `error * pixelsPerUnit / maxPixelError`, with each part's own registered budget.
322
+ *
323
+ * Level `i` is `chain.levels[min(i, length - 1)]` per part, so a part without a chain — and one
324
+ * whose chain ran out below `i` — keeps the shape above it. The switch distances come from the
325
+ * parts that descend the furthest, the **max** across those at each level, so the deepest chain's
326
+ * whole ladder survives. A part with a shallower chain clamps to its last level and does not set a
327
+ * switch: it cannot be drawn finer there anyway, so its error must not push the switch past the
328
+ * deepest chain's own last error and collapse the ladder to one far step.
329
+ */
330
+ function chainDistances(
331
+ chains: readonly (ILodChain | undefined)[],
332
+ pixelsPerUnit: number,
333
+ maxPixelError: number,
334
+ maxDistance: number | undefined,
335
+ ): number[] {
336
+ let deepest = 1;
337
+ for (const chain of chains)
338
+ if (chain !== undefined) deepest = Math.max(deepest, chain.levels.length);
339
+ const distances = [0];
340
+ for (let level = 1; level < deepest; level += 1) {
341
+ let error = 0;
342
+ for (const chain of chains) {
343
+ // Only the parts that descend the furthest set the schedule. A part whose chain ran out has
344
+ // no finer shape to offer past its last level, so letting its — often terminal, and so huge —
345
+ // error gate this switch cannot buy that part any detail back. It would only deny every
346
+ // sibling the coarser level and collapse the chain to a single far switch, which is how a
347
+ // bark primitive's 2-level chain truncated a pine's 4-level needles chain to two levels.
348
+ if (chain === undefined || chain.levels.length !== deepest) continue;
349
+ error = Math.max(error, chain.errors[level] ?? 0);
350
+ }
351
+ const at = (error * pixelsPerUnit) / maxPixelError;
352
+ // A chain's errors only ascend, so a switch that does not move outward — or that lands at or
353
+ // past the cull — ends the list: every level above it is further out still, and none of them
354
+ // can be selected or drawn. That keeps the thresholds strictly increasing and inside
355
+ // `maxDistance`, exactly as `assetLevels` keeps authored ones.
356
+ if (at <= (distances[level - 1] as number)) break;
357
+ if (maxDistance !== undefined && at >= maxDistance) break;
358
+ distances.push(at);
359
+ }
360
+ return distances;
361
+ }
362
+
363
+ /** One level's parts, and what they submit: the chain's shape where it has one, the one above where not. */
364
+ function chainLevelParts(
365
+ parts: readonly IAssetPart[],
366
+ chains: readonly (ILodChain | undefined)[],
367
+ level: number,
368
+ ): { readonly parts: IAssetPart[]; readonly triangles: number } {
369
+ const at: IAssetPart[] = [];
370
+ let triangles = 0;
371
+ for (const [index, part] of parts.entries()) {
372
+ const chain = chains[index];
373
+ // A part with no chain keeps its own shape, in its own slot: the batch builder and
374
+ // `#addPlacements` index every level's parts by the same number.
375
+ const geometry =
376
+ chain === undefined
377
+ ? part.geometry
378
+ : (chain.levels[Math.min(level, chain.levels.length - 1)] as BufferGeometry);
379
+ at.push(geometry === part.geometry ? part : { ...part, geometry });
380
+ triangles += levelTriangles(geometry);
381
+ }
382
+ return { parts: at, triangles };
383
+ }
384
+
385
+ /**
386
+ * The extra levels an asset's baked AutoLOD chain gives a batched draw, or `undefined` when none of
387
+ * its parts carries a chain.
388
+ *
389
+ * A `ModelLod` swaps one mesh's geometry, so a world that batches thousands of placements of one
390
+ * model into a handful of instanced draws never reaches that selection: every placement drew
391
+ * LOD0, which on a 2 km map is the whole triangle bill at every distance. The chain already holds
392
+ * the reduced shapes, so this derives the levels a batch can hold and the distance each one takes
393
+ * over at — the same screen-space test `ModelLod` runs, solved for depth:
394
+ * `error * pixelsPerUnit / maxPixelError`, over the world's own `autoLod.maxPixelError` rather than
395
+ * the budget the loader registered the chain with. See
396
+ * {@link IWorldCellsLoadOptions.autoLod} for why a batch cannot use the registered one.
397
+ *
398
+ * Level `i` is `chain.levels[min(i, length - 1)]` per part, so a part without a chain — and one
399
+ * whose chain ran out below `i` — keeps the shape above it. The switch distances come from the
400
+ * parts that descend the furthest, the **max** across those at each level, so the deepest chain's
401
+ * whole ladder survives. A part with a shallower chain clamps to its last level and does not set a
402
+ * switch: it cannot be drawn finer there anyway, so its error must not push the switch past the
403
+ * deepest chain's own last error and collapse the ladder to one far step.
404
+ */
405
+ /** Prepared sources may have replaced attributes or cut a material section after cloning. */
406
+ function preparedChainSafe(part: IAssetPart): boolean {
407
+ const base = part.geometry;
408
+ const chain = lodChainOf(base);
409
+ if (chain === undefined) return true;
410
+ if (
411
+ base.drawRange.start !== 0 ||
412
+ base.drawRange.count !== Number.POSITIVE_INFINITY ||
413
+ base.groups.length > 0 ||
414
+ part.material.transparent ||
415
+ part.material.alphaTest > 0 ||
416
+ displacesVertices(part.material) ||
417
+ Reflect.get(part.material, "vertexNode") != null
418
+ )
419
+ return false;
420
+ const names = Object.keys(base.attributes);
421
+ return chain.levels.every(
422
+ (level) =>
423
+ Object.keys(level.attributes).length === names.length &&
424
+ names.every((name) => level.getAttribute(name) === base.getAttribute(name)),
425
+ );
426
+ }
427
+
428
+ function chainLevels(
429
+ parts: readonly IAssetPart[],
430
+ pixelsPerUnit: number,
431
+ maxPixelError: number,
432
+ maxDistance: number | undefined,
433
+ ): IChainLevels | undefined {
434
+ const chains: (ILodChain | undefined)[] = [];
435
+ for (const part of parts) chains.push(lodChainOf(part.geometry));
436
+ const distances = chainDistances(chains, pixelsPerUnit, maxPixelError, maxDistance);
437
+ if (distances.length === 1) return undefined;
438
+ const levels: (readonly IAssetPart[])[] = [parts];
439
+ // Level 0 leads, so the marker opens with what the asset submits today.
440
+ const triangles: number[] = [parts.reduce((sum, part) => sum + levelTriangles(part.geometry), 0)];
441
+ for (let level = 1; level < distances.length; level += 1) {
442
+ const at = chainLevelParts(parts, chains, level);
443
+ levels.push(at.parts);
444
+ triangles.push(at.triangles);
445
+ }
446
+ return { distances, levels, triangles };
447
+ }
448
+
449
+ /**
450
+ * The DRAW levels an authored asset gets: every level keeps the geometry, transform and surface it
451
+ * authored, and the root LOD0's alpha-cutout parts are appended to a level that authored fewer alpha
452
+ * slots than the root carries, so no middle level loses leaves its reduced card cannot honestly
453
+ * represent.
454
+ *
455
+ * An authored reduced foliage card has no honest twin — the automatic reducer's error metric cannot
456
+ * see the holes a cutout silhouette is made of — but a level that authored such a card keeps it:
457
+ * only the slots a level carries none of fall back to the root, in the root's own per-role order, so
458
+ * a middle with one reduced card and a root with two gets its own card plus the root's second. The
459
+ * fallback parts are appended after the level's authored parts, never reordered, so each level keeps
460
+ * its own part indices and counts. Nothing is spilled: a fallback shares the root part by reference,
461
+ * so one resource is still one teardown.
462
+ */
463
+ function coverAuthoredLevels(
464
+ levels: readonly (readonly IAssetPart[])[],
465
+ ): readonly (readonly IAssetPart[])[] {
466
+ const rootAlpha = (levels[0] ?? []).filter((part) => isAlphaFoliage(part.material));
467
+ if (rootAlpha.length === 0 || levels.length < 2) return levels;
468
+ const covered: (readonly IAssetPart[])[] = [levels[0] as readonly IAssetPart[]];
469
+ for (const parts of levels.slice(1)) {
470
+ let authoredAlpha = 0;
471
+ for (const part of parts) if (isAlphaFoliage(part.material)) authoredAlpha += 1;
472
+ if (authoredAlpha >= rootAlpha.length) {
473
+ covered.push(parts);
474
+ continue;
475
+ }
476
+ const mapped: IAssetPart[] = [...parts];
477
+ for (let slot = authoredAlpha; slot < rootAlpha.length; slot += 1)
478
+ mapped.push(rootAlpha[slot] as IAssetPart);
479
+ covered.push(mapped);
480
+ }
481
+ return covered;
482
+ }
483
+
484
+ /**
485
+ * Model loads in flight for a streamed world. `loadAll`'s six suits a scene's one-off load; a
486
+ * world crossing new asset types as it moves spends most of each load waiting on the network and
487
+ * the transcoder workers, so more in flight keeps the ring ahead of a fast camera.
488
+ */
489
+ const WORLD_LOAD_CONCURRENCY = 12;
490
+
491
+ /**
492
+ * Assets reported one by one before the `TN_WORLD_LOD_CHAIN` marker collapses into a single line.
493
+ * A 2 km package carries hundreds of chained assets, and a console line each is a wall of text that
494
+ * buries the one that matters.
495
+ */
496
+ const CHAIN_LOD_MARKER_LIMIT = 20;
497
+ export interface ICellModelsHost {
498
+ canonical(id: string): string;
499
+ noteGate(gate: number): void;
500
+ queueBuild(asset: IAssetState, cell: IResidentCell, run: IWorldRun, force?: boolean): void;
501
+ released(): boolean;
502
+ failures(): number;
503
+ setFailures(count: number): void;
504
+ reportCellFailure(
505
+ stage: "asset" | "attach" | "chunk",
506
+ key: string,
507
+ paths: readonly string[],
508
+ error: unknown,
509
+ ): void;
510
+ drainShared(assetId: string): number;
511
+ residentCells(): Iterable<IResidentCell>;
512
+ queuePrewarm(asset: IAssetState): void;
513
+ hasFarTemp(id: string): boolean;
514
+ releaseFarTemp(id: string): void;
515
+ maybeQueueImpostor(asset: IAssetState): void;
516
+ hasQueuedImpostor(id: string): boolean;
517
+ cancelImpostor(asset: IAssetState): void;
518
+ releaseImpostor(asset: IAssetState): void;
519
+ }
520
+ export interface ICellModelsSettings {
521
+ readonly lodHysteresis: number;
522
+ readonly manifest: IWorldPackage;
523
+ readonly baseUrl: string;
524
+ readonly logicalBase: string;
525
+ readonly preserveAuthoredParts: boolean;
526
+ readonly autoLodPixelsPerUnit: number;
527
+ readonly autoLodMaxPixelError: number;
528
+ readonly transparentScatter: "cutout" | "blend";
529
+ }
530
+
531
+ export class CellModels {
532
+ readonly #host: ICellModelsHost;
533
+
534
+ /** Parts already handed back, so a level that fell back to the one above releases it once. */
535
+ static readonly #releasedParts = new WeakSet<IAssetPart>();
536
+
537
+ readonly #loader: IAssetLoader;
538
+
539
+ /**
540
+ * Whether {@link #loader} was created here rather than supplied by the game. Only an internally
541
+ * owned loader may have its `model` cache released when this world's last cell stops naming a
542
+ * path: an explicitly supplied loader is the caller's, another world may hold the same cached
543
+ * model, and its own `release` is the caller's to call. See `#releaseModelPaths`.
544
+ */
545
+ readonly #ownsLoader: boolean;
546
+
547
+ readonly #loadModel: ((url: string) => Promise<Object3D>) | undefined;
548
+
549
+ readonly #limiter: ModelLoadLimiter;
550
+
551
+ readonly #assets = new Map<string, IAssetState>();
552
+
553
+ /**
554
+ * Exact `assets.model` cache paths this world holds, and how many of its asset states ask for
555
+ * each. Two distinct canonical assets can name the same path when their `lods`/`maxDistance`
556
+ * differ — the package's own aliasing leaves them separate — so the loader entry is released only
557
+ * when the last state naming the path goes. Keyed on the logical path requested, which is what the
558
+ * loader caches by, not the cooked url it resolves to. Empty under a `loadModel` override, which
559
+ * reaches no cache.
560
+ */
561
+ readonly #modelPaths = new Map<string, number>();
562
+
563
+ /** Surfaces shared by material content across every asset part; see `materialKey`. */
564
+ readonly #surfaces = new Map<string, ISharedSurface>();
565
+
566
+ /** Assets widened by their own chain so far, and whether the marker has already collapsed. */
567
+ #chainLodAssets = 0;
568
+
569
+ #chainLodSummarised = false;
570
+
571
+ readonly #lodHysteresis: number;
572
+
573
+ readonly #manifest: IWorldPackage;
574
+
575
+ readonly #baseUrl: string;
576
+
577
+ readonly #logicalBase: string;
578
+
579
+ readonly #preserveAuthoredParts: boolean;
580
+
581
+ /**
582
+ * Pixels per world unit at unit depth, the scale a baked chain's level errors are divided by to
583
+ * reach a switch distance. See `IWorldCellsLoadOptions.autoLod` and {@link chainLevels}.
584
+ */
585
+ readonly #autoLodPixelsPerUnit: number;
586
+
587
+ /** The screen-space error budget a synthesized level is switched at; see `autoLod`. */
588
+ readonly #autoLodMaxPixelError: number;
589
+
590
+ readonly #transparentScatter: "cutout" | "blend";
591
+ constructor(
592
+ init: Pick<IWorldCellsLoadOptions, "assets" | "loadModel" | "concurrency"> & {
593
+ readonly ownsAssets?: boolean;
594
+ },
595
+ settings: ICellModelsSettings,
596
+ host: ICellModelsHost,
597
+ ) {
598
+ this.#host = host;
599
+ this.#lodHysteresis = settings.lodHysteresis;
600
+ this.#manifest = settings.manifest;
601
+ this.#baseUrl = settings.baseUrl;
602
+ this.#logicalBase = settings.logicalBase;
603
+ this.#preserveAuthoredParts = settings.preserveAuthoredParts;
604
+ this.#autoLodPixelsPerUnit = settings.autoLodPixelsPerUnit;
605
+ this.#autoLodMaxPixelError = settings.autoLodMaxPixelError;
606
+ this.#transparentScatter = settings.transparentScatter;
607
+ this.#loader = init.assets ?? createAssetLoader();
608
+ this.#ownsLoader = init.ownsAssets ?? init.assets === undefined;
609
+ this.#loadModel = init.loadModel;
610
+ this.#limiter = new ModelLoadLimiter(
611
+ positiveInteger(init.concurrency ?? WORLD_LOAD_CONCURRENCY, "concurrency"),
612
+ );
613
+ }
614
+ get loadModel(): ((url: string) => Promise<Object3D>) | undefined {
615
+ return this.#loadModel;
616
+ }
617
+
618
+ cloneAssets(): { readonly assets: IAssetLoader; readonly ownsAssets: boolean } {
619
+ return {
620
+ assets: this.#ownsLoader ? createAssetLoader() : this.#loader,
621
+ ownsAssets: this.#ownsLoader,
622
+ };
623
+ }
624
+ get loadsInFlight(): number {
625
+ return this.#limiter.inFlight;
626
+ }
627
+ get loadsQueued(): number {
628
+ return this.#limiter.queued;
629
+ }
630
+ load(path: string, wanted: () => boolean): Promise<Object3D | undefined> {
631
+ return this.#limiter.load(() => this.model(path), wanted);
632
+ }
633
+ asset(id: string): IAssetState | undefined {
634
+ return this.#assets.get(id);
635
+ }
636
+ hasAsset(id: string): boolean {
637
+ return this.#assets.has(id);
638
+ }
639
+ assets(): Iterable<IAssetState> {
640
+ return this.#assets.values();
641
+ }
642
+ entries(): Iterable<[string, IAssetState]> {
643
+ return this.#assets.entries();
644
+ }
645
+ pathUsers(path: string): number {
646
+ return this.#modelPaths.get(path) ?? 0;
647
+ }
648
+ markReleasedPart(part: IAssetPart): void {
649
+ CellModels.#releasedParts.add(part);
650
+ }
651
+
652
+ /** One fresh asset state for a definition, registered and its gates noted. */
653
+ newAsset(id: string, definition: IWorldAsset): IAssetState {
654
+ const asset: IAssetState = {
655
+ ...assetLevels(definition),
656
+ definition,
657
+ disposed: false,
658
+ id,
659
+ levels: [],
660
+ pending: false,
661
+ failed: false,
662
+ refcount: 0,
663
+ hlodSafe: false,
664
+ retainedPaths: [],
665
+ resolvedGlb: "",
666
+ spilled: [],
667
+ };
668
+ this.ditherGates(asset);
669
+ this.#assets.set(id, asset);
670
+ for (const gate of asset.gates) this.#host.noteGate(gate);
671
+ return asset;
672
+ }
673
+
674
+ acquire(run: IWorldRun, cell: IResidentCell): void {
675
+ const id = this.#host.canonical(run.asset);
676
+ let asset = this.#assets.get(id);
677
+ if (asset === undefined) {
678
+ const definition = this.#manifest.assets[id];
679
+ if (definition === undefined) return;
680
+ asset = this.newAsset(id, definition);
681
+ }
682
+ asset.refcount += 1;
683
+ if (asset.levels.length > 0) {
684
+ this.#host.queueBuild(asset, cell, run);
685
+ return;
686
+ }
687
+ if (!asset.pending) this.startAssetLoad(asset);
688
+ }
689
+
690
+ /**
691
+ * One model, from the loader the package was given. `loadModel` keeps the override and takes the
692
+ * authored url, so a game's own GLB loader is unchanged; without it the logical path goes to
693
+ * `assets.model`, which is what makes a compiled package and its KTX2 textures work.
694
+ */
695
+ model(path: string, scene?: string): Promise<Object3D> {
696
+ return this.#loadModel === undefined
697
+ ? loadModelWith(this.#loader, path, scene)
698
+ : this.#loadModel(resolveRelative(this.#baseUrl, path));
699
+ }
700
+
701
+ /**
702
+ * Every level of one asset, through the same limiter and the same resolution as `lod0`, so a
703
+ * package's compiled output and compressed textures reach the renderer the game booted with. One
704
+ * level refusing is not the asset refusing: it is counted and `#adoptAsset` falls back to the
705
+ * level below it, so the far placements still draw.
706
+ */
707
+ startAssetLoad(asset: IAssetState): void {
708
+ asset.pending = true;
709
+ // The source models this state asks `assets.model` for are this world's to hand back; the
710
+ // loader caches by logical path and would otherwise pin every texture for the world's life.
711
+ // Counted once per state, so a load retried after an empty answer does not double-count.
712
+ // `loadModel` overrides the cache entirely, so it retains nothing.
713
+ if (this.#loadModel === undefined && asset.retainedPaths.length === 0) {
714
+ this.retainModelPaths(
715
+ Array.from(asset.glbs, (glb) => resolveRelative(this.#logicalBase, glb)),
716
+ asset.retainedPaths,
717
+ );
718
+ }
719
+ const wanted = (): boolean =>
720
+ !this.#host.released() && this.#assets.get(asset.id) === asset && !asset.disposed;
721
+ // `Promise.all` hands back the levels in `glbs` order, and the limiter is what bounds them: it
722
+ // already caps every load in flight across the resident cells, assets and chunks together.
723
+ const loads: Array<Promise<Object3D | undefined>> = [];
724
+ for (const [index, glb] of asset.glbs.entries()) {
725
+ const path = resolveRelative(this.#logicalBase, glb);
726
+ const scene = asset.scenes[index];
727
+ loads.push(
728
+ this.#limiter
729
+ .load(() => this.model(path, scene), wanted)
730
+ .catch((error: unknown) => {
731
+ asset.failed = true;
732
+ this.#host.setFailures(this.#host.failures() + 1);
733
+ this.#host.reportCellFailure("asset", asset.id, [path], error);
734
+ return undefined;
735
+ }),
736
+ );
737
+ }
738
+ // The cooked url LOD0 was actually fetched from, resolved the same way `assetSignature` does,
739
+ // so the atlas key names the bytes rather than the package entry. It is needed before adoption,
740
+ // so the two promises are awaited together; a path the loader cannot resolve falls back to the
741
+ // logical url, exactly as `assetSignature`'s caller does.
742
+ const lod0 = resolveRelative(this.#logicalBase, asset.glbs[0] as string);
743
+ const resolved = this.#loader
744
+ .resolve(lod0)
745
+ .then((candidates) => candidates[0] ?? lod0)
746
+ .catch(() => lod0);
747
+ void Promise.all([Promise.all(loads), resolved]).then(([models, url]) => {
748
+ // The state stays, refcount and all, whatever the loads answered: cells still resident are
749
+ // holding it, and the next acquire retries. Dropping it here would let a later cell refcount
750
+ // from zero and hand an eviction of an old cell the geometry a still-resident cell draws.
751
+ asset.resolvedGlb = url;
752
+ asset.pending = false;
753
+ this.#adoptAsset(asset, models);
754
+ });
755
+ }
756
+
757
+ /** One loaded model's drawable parts, or `undefined` when it carries nothing to draw. */
758
+ #partsOf(model: Object3D | undefined): readonly IAssetPart[] | undefined {
759
+ if (model === undefined) return undefined;
760
+ const parts = renderableParts(model, (material) => this.#surfaceFor(material));
761
+ if (parts.length === 0) {
762
+ // Same as a refused load: counted, released, and the next acquire retries.
763
+ this.#host.setFailures(this.#host.failures() + 1);
764
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
765
+ return undefined;
766
+ }
767
+ return parts;
768
+ }
769
+
770
+ /**
771
+ * One part list per loaded model: level 0 is the asset's own shape, and every level below it
772
+ * falls back to the one above when it did not load. `undefined` is the asset refusing to exist —
773
+ * no `lod0` to fall back to — and the levels that did load are released rather than held by an
774
+ * asset that draws nothing, cutout clones included. The refcounted state stays either way, so the
775
+ * next acquire retries.
776
+ */
777
+ #adoptLevels(
778
+ models: readonly (Object3D | undefined)[],
779
+ ): readonly (readonly IAssetPart[])[] | undefined {
780
+ const levels: (readonly IAssetPart[])[] = [];
781
+ for (const [index, model] of models.entries()) {
782
+ const level = this.#partsOf(model) ?? levels[index - 1];
783
+ if (level === undefined) {
784
+ for (const model of models.slice(index))
785
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
786
+ for (const parts of levels)
787
+ this.#host.setFailures(this.#host.failures() + this.#releaseParts(parts));
788
+ return undefined;
789
+ }
790
+ levels.push(level);
791
+ }
792
+ return levels;
793
+ }
794
+
795
+ /**
796
+ * An asset's levels are in, so every resident cell holding it needs its batches — queued, not
797
+ * built. This is the path that used to be worst: adopting one asset rebuilt every resident cell's
798
+ * batches for it in a single frame, and a 218-asset package pays it over and over as the ring
799
+ * moves. The queue turns it into the same per-frame allowance every other admission path gets.
800
+ */
801
+ #adoptAsset(asset: IAssetState, models: readonly (Object3D | undefined)[]): void {
802
+ if (this.#host.released() || this.#assets.get(asset.id) !== asset || asset.disposed) {
803
+ for (const model of models)
804
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
805
+ return;
806
+ }
807
+ asset.hlodSafe = models[0] !== undefined && cellProxySourceSafe(models[0]);
808
+ const adopted = this.#adoptLevels(models);
809
+ if (adopted === undefined) {
810
+ // A far-only asset that would not load has nothing to bake; drop the temporary reference so
811
+ // the source it did fetch is not held for the world's whole life.
812
+ if (this.#host.hasFarTemp(asset.id)) this.#host.releaseFarTemp(asset.id);
813
+ return;
814
+ }
815
+ // Before the prewarm and the queued builds, both of which read the levels, the distances and
816
+ // the gates: an asset whose chain widened it is batched at those levels from its first build.
817
+ asset.levels = this.#widenWithChain(asset, adopted);
818
+ // A far-only asset is drawn by no near run, so it takes no prewarm and queues no cell build:
819
+ // its whole job is the atlas behind the aggregate, and its source is released once that lands.
820
+ if (this.#host.hasFarTemp(asset.id)) {
821
+ this.#host.maybeQueueImpostor(asset);
822
+ // Nothing to bake (no alpha-cutout LOD0) and nothing queued: release the source now.
823
+ if (asset.impostor === undefined && !this.#host.hasQueuedImpostor(asset.id))
824
+ this.#host.releaseFarTemp(asset.id);
825
+ return;
826
+ }
827
+ // After the chain, so the impostor's switch sits beyond every synthesized gate; before the
828
+ // prewarm, so a cached atlas appends its level in this same admission.
829
+ this.#host.maybeQueueImpostor(asset);
830
+ // Every level and part of the asset now, before any of them is asked for. A level with no
831
+ // placement in it is not drawn and would otherwise mint its mesh — and pay its node build — on
832
+ // the frame a walk first moves far enough to switch into it.
833
+ this.#host.queuePrewarm(asset);
834
+ for (const cell of [...this.#host.residentCells()]) {
835
+ for (const run of cell.cell.runs) {
836
+ if (this.#host.canonical(run.asset) === asset.id) this.#host.queueBuild(asset, cell, run);
837
+ }
838
+ }
839
+ }
840
+
841
+ /**
842
+ * An asset's loaded levels, widened with the ones its model's baked AutoLOD chain carries.
843
+ *
844
+ * An asset with authored `lods` keeps its own switch distances and its own middle geometry: each
845
+ * level draws the shape the pipeline authored for it, with the root LOD0's alpha cutouts appended
846
+ * to any level that authored fewer of them so no middle loses its leaves; see
847
+ * `coverAuthoredLevels`. A chain the loader also happens to have registered is a fallback for a
848
+ * package that named no `lods`, not a second opinion over one that did. Everything downstream is
849
+ * unchanged either way — a level is a level, and its switch is a gate like any other — so the
850
+ * batch keys, the prewarm, the caster clusters and the retire/rebind pool all see the derived
851
+ * levels as ordinary ones.
852
+ */
853
+ #widenWithChain(
854
+ asset: IAssetState,
855
+ levels: readonly (readonly IAssetPart[])[],
856
+ ): readonly (readonly IAssetPart[])[] {
857
+ if ((asset.definition.lods?.length ?? 0) > 0)
858
+ return this.#preserveAuthoredParts ? levels : coverAuthoredLevels(levels);
859
+ // An empty list names no authored rung. Prepared static parts can use their existing chain,
860
+ // while sectioned/deforming or replaced-attribute copies keep their supplied source shape.
861
+ if (asset.definition.lods !== undefined && !(levels[0] ?? []).every(preparedChainSafe))
862
+ return levels;
863
+ const chained = chainLevels(
864
+ levels[0] as readonly IAssetPart[],
865
+ this.#autoLodPixelsPerUnit,
866
+ this.#autoLodMaxPixelError,
867
+ asset.definition.maxDistance,
868
+ );
869
+ if (chained === undefined) return levels;
870
+ asset.distances = chained.distances;
871
+ asset.gates = [...chained.distances.slice(1), ...asset.gates];
872
+ this.ditherGates(asset);
873
+ this.#reportChainLod(asset.id, chained);
874
+ return chained.levels;
875
+ }
876
+
877
+ ditherGates(asset: IAssetState): void {
878
+ const gates = new Set(asset.gates);
879
+ if (this.#lodHysteresis > 0) {
880
+ for (let level = 0; level < asset.distances.length; level += 1) {
881
+ const near = asset.distances[level] ?? 0;
882
+ const far = asset.distances[level + 1] ?? Number.POSITIVE_INFINITY;
883
+ const slack =
884
+ Math.max(near, Number.isFinite(far) ? far : near) * this.#lodHysteresis +
885
+ (asset.distances[1] ?? 6) / 8;
886
+ if (near > slack) gates.add(near - slack);
887
+ if (Number.isFinite(far)) gates.add(far + slack);
888
+ }
889
+ }
890
+ asset.gates = [...gates];
891
+ asset.threshold = asset.gates.length === 0 ? undefined : Math.min(...asset.gates);
892
+ for (const gate of asset.gates) this.#host.noteGate(gate);
893
+ }
894
+
895
+ /**
896
+ * `TN_WORLD_LOD_CHAIN`, one line per asset that was widened: how many levels it is now drawn at,
897
+ * where each takes over in metres to one decimal, and what each submits in triangles. Level 0
898
+ * leads, so the first triangle count is what the asset submits today and the last is what it
899
+ * submits past the last switch: the reduction is the whole point of the line.
900
+ */
901
+ #reportChainLod(id: string, chained: IChainLevels): void {
902
+ this.#chainLodAssets += 1;
903
+ if (this.#chainLodAssets > CHAIN_LOD_MARKER_LIMIT) {
904
+ if (this.#chainLodSummarised) return;
905
+ this.#chainLodSummarised = true;
906
+ console.info(
907
+ `TN_WORLD_LOD_CHAIN more than ${String(CHAIN_LOD_MARKER_LIMIT)} assets carry a chain; ` +
908
+ `the rest are one line: assets=${String(this.#chainLodAssets)}`,
909
+ );
910
+ return;
911
+ }
912
+ const listed: string[] = [];
913
+ for (const distance of chained.distances) listed.push(distance.toFixed(1));
914
+ console.info(
915
+ `TN_WORLD_LOD_CHAIN ${id}: levels=${String(chained.levels.length)} ` +
916
+ `distances=${listed.join(",")} tris=${chained.triangles.join(",")}`,
917
+ );
918
+ }
919
+
920
+ /**
921
+ * Release every part's shape and every surface it owns — its own material and, for a scattered
922
+ * transparent part, the cutout clone made for it.
923
+ *
924
+ * At most once per resource, the same contract `release` gives the single-shape case: two parts
925
+ * of one GLB routinely share a material, a level that fell back shares the level below's whole
926
+ * part list, and every cell batch of the asset drew the same one. A clone is a resource this
927
+ * class made, so it is released here and nowhere else.
928
+ *
929
+ * @returns how many teardowns threw, for the caller to count.
930
+ */
931
+ /**
932
+ * Tear down a model the loader handed this world, respecting who owns the loader.
933
+ *
934
+ * A model from the loader this world created is the world's to dispose. A model from an
935
+ * explicitly supplied loader is the caller's — another world or game may hold the same cached
936
+ * scene — so this world drops its batches but leaves the shapes and surfaces alone; the caller's
937
+ * own `release` ends that lifetime. See `#releaseModelPaths`.
938
+ */
939
+ disposeLoaded(model: Object3D | undefined): number {
940
+ if (model === undefined) return 0;
941
+ return this.#ownsLoader ? disposeModel(model) : 0;
942
+ }
943
+
944
+ /**
945
+ * Release an adopted source shape or authored surface, unless a caller-supplied loader owns it.
946
+ * The caller's cache holds another world's copy too, so only a world-owned loader disposes what
947
+ * it adopted; a cutout this world built is always its own. See `#disposeLoaded`.
948
+ */
949
+ releaseSource(target: { dispose: () => void } | undefined): boolean {
950
+ return this.#ownsLoader && release(target);
951
+ }
952
+
953
+ #releaseParts(parts: readonly IAssetPart[]): number {
954
+ let failed = 0;
955
+ for (const part of parts) {
956
+ if (CellModels.#releasedParts.has(part)) continue;
957
+ CellModels.#releasedParts.add(part);
958
+ // A parked mesh holds the part's own geometry and material, so once those are released the
959
+ // parked mesh can never be handed out again — it would give the next cell that asks for one a
960
+ // buffer waiting on a disposed resource. Dropped here, so it does not sit in the pool counting
961
+ // against the meshes a walk can park.
962
+ dropPooledFor(part.geometry, part.material);
963
+ if (this.releaseSource(part.geometry)) failed += 1;
964
+ failed += this.#releaseSurface(part.surface);
965
+ }
966
+ return failed;
967
+ }
968
+
969
+ /**
970
+ * The shared surface for a material's content: the first material seen for a key becomes the
971
+ * canonical one (converted to a cutout when it is transparent scatter), and every later material
972
+ * with the same content is released on arrival and draws with it instead.
973
+ */
974
+ #surfaceFor(source: Material): { readonly key: string; readonly material: Material } {
975
+ const key = this.#preserveAuthoredParts ? source.uuid : materialKey(source);
976
+ const shared = this.#surfaces.get(key);
977
+ if (shared !== undefined) {
978
+ shared.users += 1;
979
+ if (!shared.owned.includes(source) && this.releaseSource(source))
980
+ this.#host.setFailures(this.#host.failures() + 1);
981
+ return { key, material: shared.material };
982
+ }
983
+ const drawn = scatterMaterial(source, this.#transparentScatter);
984
+ this.#surfaces.set(key, { material: drawn.material, owned: drawn.owned, users: 1 });
985
+ return { key, material: drawn.material };
986
+ }
987
+
988
+ /** One user gone; the last one tears the shared surface down. Returns teardowns that threw. */
989
+ #releaseSurface(key: string): number {
990
+ const shared = this.#surfaces.get(key);
991
+ if (shared === undefined) return 0;
992
+ shared.users -= 1;
993
+ if (shared.users > 0) return 0;
994
+ this.#surfaces.delete(key);
995
+ let failed = 0;
996
+ // A caller-supplied loader's authored surfaces belong to the caller's cache, like its shapes.
997
+ // The cutout clones this world built are still the world's to release — `worldOwned` is the
998
+ // marker. See `#releaseSource`.
999
+ for (const material of shared.owned)
1000
+ if ((this.#ownsLoader || worldOwned.has(material)) && release(material)) failed += 1;
1001
+ return failed;
1002
+ }
1003
+
1004
+ release(id: string): void {
1005
+ const asset = this.#assets.get(id);
1006
+ if (asset === undefined) return;
1007
+ asset.refcount -= 1;
1008
+ if (asset.refcount > 0) return;
1009
+ this.#assets.delete(id);
1010
+ asset.disposed = true;
1011
+ // Before anything is released: a pending bake stages this asset's borrowed geometry, and a view
1012
+ // drawn after the teardown reads a disposed buffer. Then the terminal level's own surface, whose
1013
+ // geometry and material `#releaseParts` must skip; see `#releaseImpostor`.
1014
+ this.#host.cancelImpostor(asset);
1015
+ this.#host.releaseImpostor(asset);
1016
+ // The last cell drawing this asset is gone, so this is the one teardown its levels get. It is
1017
+ // also the one a lost device makes expensive, which is why every part goes through `release`:
1018
+ // at most once per resource, and a level that fell back shares the level below's parts, so one
1019
+ // shape is torn down once however many levels point at it. One refusal is counted per asset,
1020
+ // the way one refused `lod0` load was.
1021
+ const levels = asset.levels;
1022
+ const spilled = asset.spilled;
1023
+ asset.levels = [];
1024
+ asset.spilled = [];
1025
+ let failed = 0;
1026
+ failed += this.#host.drainShared(id);
1027
+ for (const parts of levels) failed += this.#releaseParts(parts);
1028
+ // The middle levels' own reduced foliage cards, taken out of DRAW but still owned here. The
1029
+ // released-parts set makes the ones a draw level also holds single-teardown, so a shared surface
1030
+ // is never dropped early.
1031
+ failed += this.#releaseParts(spilled);
1032
+ if (failed > 0) this.#host.setFailures(this.#host.failures() + 1);
1033
+ this.releaseModelPaths(asset.retainedPaths);
1034
+ }
1035
+
1036
+ /**
1037
+ * Note the exact `assets.model` cache paths an owner (an asset's levels, a cell's chunks) asks the
1038
+ * loader for, in the one world-wide `#modelPaths` map, so the last owner to let a path go can hand
1039
+ * it back. Both owners share the map, so an asset and a chunk that name the same bytes keep the
1040
+ * entry alive until neither holds it.
1041
+ */
1042
+ retainModelPaths(paths: readonly string[], into: string[]): void {
1043
+ for (const path of paths) {
1044
+ this.#modelPaths.set(path, (this.#modelPaths.get(path) ?? 0) + 1);
1045
+ into.push(path);
1046
+ }
1047
+ }
1048
+
1049
+ /**
1050
+ * Hand back the exact `assets.model` cache paths this owner requested, so the loader drops the
1051
+ * source scenes and their textures instead of pinning them for the world's whole life.
1052
+ *
1053
+ * A path another owner still names is not released: two definitions that fetch the same bytes but
1054
+ * carry different `lods`/`maxDistance` are distinct assets, and the one leaving the ring must not
1055
+ * tear out a cached source the other still draws with. Keyed on the requested logical path, so a
1056
+ * path this world never asked for is never touched.
1057
+ *
1058
+ * Only the loader this world created is released. An explicitly supplied `assets` loader is the
1059
+ * caller's: another game or world may hold the same cached model, so this world never drops a
1060
+ * cache entry it does not own — the caller's own `release` is where that lifetime ends.
1061
+ */
1062
+ releaseModelPaths(paths: string[]): void {
1063
+ for (const path of paths) {
1064
+ const holders = (this.#modelPaths.get(path) ?? 1) - 1;
1065
+ if (holders > 0) {
1066
+ this.#modelPaths.set(path, holders);
1067
+ continue;
1068
+ }
1069
+ this.#modelPaths.delete(path);
1070
+ if (this.#ownsLoader) this.#loader.release("model", path);
1071
+ }
1072
+ paths.length = 0;
1073
+ }
1074
+ }