@threenative/core 0.3.13 → 0.3.15

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 (50) hide show
  1. package/capabilities.json +299 -10
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-DIPIJICH.js → chunk-GEMQJBY4.js} +70 -18
  4. package/dist/{chunk-EFWZWLPY.js → chunk-QAMSM3Z5.js} +354 -12
  5. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  6. package/dist/{chunk-EEABDLUC.js → chunk-VBBYWGAT.js} +2 -2
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/index.d.ts +605 -7
  9. package/dist/index.js +1973 -609
  10. package/dist/playtest.js +3 -3
  11. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  12. package/dist/render-environment.d.ts +1 -1
  13. package/dist/ui-layer.js +2 -2
  14. package/dist/worker.js +2 -2
  15. package/dist/world.d.ts +13 -3
  16. package/dist/world.js +179 -36
  17. package/mcp/animation-server.mjs +1 -1
  18. package/mcp/engine-server.mjs +32 -6
  19. package/mcp/servers.mjs +3 -3
  20. package/package.json +5 -5
  21. package/scripts/ensure-mcp.mjs +6 -1
  22. package/src/clustered-batch.ts +146 -3
  23. package/src/clustered-mesh.ts +548 -20
  24. package/src/debug.ts +16 -0
  25. package/src/displaced-surface.ts +428 -0
  26. package/src/frame-budget.ts +16 -0
  27. package/src/generated/console-markers.ts +1 -0
  28. package/src/grass-field.ts +628 -0
  29. package/src/index.ts +112 -0
  30. package/src/render/material-key.ts +21 -1
  31. package/src/render/screen-probe-gather.ts +303 -0
  32. package/src/render/short-range-ao.ts +274 -0
  33. package/src/render/world-impostor-surface.ts +98 -3
  34. package/src/render-camera-cull.ts +9 -3
  35. package/src/renderer.ts +26 -4
  36. package/src/scatter-field.ts +496 -0
  37. package/src/startup-offscreen-bytes.ts +11 -5
  38. package/src/state.ts +16 -3
  39. package/src/static-transform.ts +75 -6
  40. package/src/tile-ring.ts +294 -0
  41. package/src/version.ts +1 -1
  42. package/src/warmup.ts +15 -2
  43. package/src/world-cell-batches.ts +4 -0
  44. package/src/world-cell-data.ts +7 -0
  45. package/src/world-cell-models.ts +36 -8
  46. package/src/world-cell-render-gpu-dress.ts +4 -2
  47. package/src/world-cell-render-util.ts +2 -2
  48. package/src/world-cells.ts +1 -1
  49. package/src/world-river-ribbon.ts +13 -22
  50. package/src/world-water-bodies.ts +113 -3
@@ -36,6 +36,13 @@ interface IFrozenRoot {
36
36
  readonly snapshot: Float64Array;
37
37
  /** Bumped every time the subtree is re-armed; the contract a consumer checks, not the flag. */
38
38
  version: number;
39
+ /**
40
+ * Set by {@link markEngineStatic}: the parent the root was frozen under. The engine owns the root's
41
+ * local transform, so the per-frame check reads only this parent's world matrix, once per parent.
42
+ */
43
+ parent?: Object3D | null;
44
+ /** An engine-owned root not yet checked in full since it froze. */
45
+ fresh?: boolean;
39
46
  }
40
47
 
41
48
  /**
@@ -55,7 +62,9 @@ function writeSnapshot(root: Object3D, into: Float64Array): void {
55
62
  const position: Vector3 = root.position;
56
63
  const quaternion: Quaternion = root.quaternion;
57
64
  const scale: Vector3 = root.scale;
58
- const matrix: Matrix4 = root.matrix;
65
+ // One read of each `elements`: on the owned engine it is an accessor that resolves a Wasm heap
66
+ // view per read, and this runs for every frozen root every frame (PRD-887 AC-3).
67
+ const matrix: Matrix4["elements"] = root.matrix.elements;
59
68
  into[0] = position.x;
60
69
  into[1] = position.y;
61
70
  into[2] = position.z;
@@ -66,8 +75,7 @@ function writeSnapshot(root: Object3D, into: Float64Array): void {
66
75
  into[7] = scale.x;
67
76
  into[8] = scale.y;
68
77
  into[9] = scale.z;
69
- for (let element = 0; element < 16; element += 1)
70
- into[10 + element] = matrix.elements[element] ?? 0;
78
+ for (let element = 0; element < 16; element += 1) into[10 + element] = matrix[element] ?? 0;
71
79
  // The frozen world matrix is the parent's times the root's own, so a root attached after it froze,
72
80
  // or one whose ancestor moved, is as stale as one the author moved. A streamed world freezes each
73
81
  // draw before it joins the world root, and a seated world (`world.position.y = -ground`) drew
@@ -167,6 +175,21 @@ function freeze(root: Object3D): number {
167
175
  * `invalidateStatic` does and the reason a generator can emit the call unconditionally.
168
176
  */
169
177
  export function markStatic(root: Object3D): number {
178
+ return freezeRoot(root, false);
179
+ }
180
+
181
+ /**
182
+ * `markStatic` for a draw the engine creates and owns, such as a streamed world's instanced batches:
183
+ * nothing but the engine writes its local transform, and the engine re-arms it when it does. The
184
+ * per-frame check then reads its parent's world matrix once for every draw under that parent, rather
185
+ * than every draw's own transform: a cooked region froze 2,077 batches at its overview and paid the
186
+ * per-root check for each (PRD-887 AC-3). A draw moved under another parent still re-arms.
187
+ */
188
+ export function markEngineStatic(root: Object3D): number {
189
+ return freezeRoot(root, true);
190
+ }
191
+
192
+ function freezeRoot(root: Object3D, engine: boolean): number {
170
193
  const existing = frozen.get(root);
171
194
  // A second mark re-arms: thaw first, or `freeze`'s update skips the root's own world compose (the
172
195
  // first freeze turned it off) and the subtree keeps the world matrix of its first parent.
@@ -175,7 +198,12 @@ export function markStatic(root: Object3D): number {
175
198
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
176
199
  writeSnapshot(root, snapshot);
177
200
  const version = (existing?.version ?? 0) + 1;
178
- frozen.set(root, { objects, root, snapshot, version });
201
+ frozen.set(
202
+ root,
203
+ engine
204
+ ? { objects, root, snapshot, version, parent: root.parent, fresh: true }
205
+ : { objects, root, snapshot, version },
206
+ );
179
207
  return version;
180
208
  }
181
209
 
@@ -253,13 +281,53 @@ let rearmedSinceCensus = 0;
253
281
  */
254
282
  export function refreshStaticTransforms(): void {
255
283
  if (frozen.size === 0) return;
284
+ parentMovedThisFrame.clear();
256
285
  for (const entry of frozen.values()) {
257
- if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
258
- markStatic(entry.root);
286
+ const engine = entry.parent !== undefined;
287
+ if (engine) {
288
+ const parent = entry.root.parent;
289
+ // Read even for a fresh root, so the parent's matrix is on record before the next frame.
290
+ const moved = parentMoved(parent);
291
+ if (parent === entry.parent && entry.fresh !== true && !moved) continue;
292
+ entry.fresh = false;
293
+ // A draw frozen before it joined its parent, at the pose that parent still has, stays frozen
294
+ // and is watched under the parent it has now.
295
+ if (snapshotMatches(entry.root, entry.snapshot, scratch)) {
296
+ entry.parent = parent;
297
+ continue;
298
+ }
299
+ } else if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
300
+ freezeRoot(entry.root, engine);
259
301
  rearmedSinceCensus += 1;
260
302
  }
261
303
  }
262
304
 
305
+ /** Each watched parent's world matrix as the previous refresh read it. */
306
+ const parentSeen = new WeakMap<Object3D, Float64Array>();
307
+ /** This refresh's answer per parent, so a parent shared by a thousand draws is read once. */
308
+ const parentMovedThisFrame = new Map<Object3D, boolean>();
309
+
310
+ /** Whether `parent`'s world matrix changed since the previous refresh read it; null never moves. */
311
+ function parentMoved(parent: Object3D | null): boolean {
312
+ if (parent === null) return false;
313
+ const answered = parentMovedThisFrame.get(parent);
314
+ if (answered !== undefined) return answered;
315
+ const elements = parent.matrixWorld.elements;
316
+ let seen = parentSeen.get(parent);
317
+ let moved = seen === undefined;
318
+ if (seen === undefined) {
319
+ seen = new Float64Array(16);
320
+ parentSeen.set(parent, seen);
321
+ }
322
+ for (let element = 0; element < 16; element += 1) {
323
+ const value = elements[element] ?? 0;
324
+ if (seen[element] !== value) moved = true;
325
+ seen[element] = value;
326
+ }
327
+ parentMovedThisFrame.set(parent, moved);
328
+ return moved;
329
+ }
330
+
263
331
  /** The census, and the re-arm counter it resets. */
264
332
  export function staticTransformCensus(): IStaticTransformCensus {
265
333
  let objects = 0;
@@ -276,5 +344,6 @@ export function staticTransformCensus(): IStaticTransformCensus {
276
344
  /** Drops every registration. A game that tore down its scene must not keep its roots alive. */
277
345
  export function resetStaticTransforms(): void {
278
346
  frozen.clear();
347
+ parentMovedThisFrame.clear();
279
348
  rearmedSinceCensus = 0;
280
349
  }
@@ -0,0 +1,294 @@
1
+ /** A tile is built inside this many draw distances, so it exists before it is seen. */
2
+ export const CREATE_BAND = 1.3;
3
+ /** A tile is discarded only past this many draw distances, so a camera on the edge never thrashes. */
4
+ export const DISCARD_BAND = 1.4;
5
+
6
+ export interface ITileBounds {
7
+ readonly minX: number;
8
+ readonly minZ: number;
9
+ readonly maxX: number;
10
+ readonly maxZ: number;
11
+ }
12
+
13
+ /**
14
+ * What a `TileRing` needs from the field it streams: the live settings every frame reads, one tile
15
+ * builder, and the three things to do to a live tile. The field keeps the ground query, the look and
16
+ * the level-of-detail rule; the ring keeps the ring.
17
+ */
18
+ export interface ITileRingField<TTile> {
19
+ readonly chunkSize: number;
20
+ readonly drawDistance: number;
21
+ readonly buildBudgetMs: number;
22
+ /** Whether a column is inside the field's bounds; the ring asks before queueing it. */
23
+ inBounds(ix: number, iz: number): boolean;
24
+ /** Builds one tile. Resolve an empty tile by returning `null`; it is remembered, not rebuilt. */
25
+ build(ix: number, iz: number): TTile | null;
26
+ /** The tile is live and inside the draw distance: show it and pick its level of detail. */
27
+ show(tile: TTile, distance: number): void;
28
+ /** The tile is live but outside the draw distance, and not yet discarded. */
29
+ hide(tile: TTile): void;
30
+ dispose(tile: TTile): void;
31
+ }
32
+
33
+ export interface ITileRingStats {
34
+ /** Live tiles, built or remembered empty. */
35
+ tiles: number;
36
+ /** Tiles the last `update` showed. */
37
+ visible: number;
38
+ /** Tiles queued but not built at the end of the last `update`. */
39
+ pending: number;
40
+ /** Tiles built since the ring was made. */
41
+ built: number;
42
+ }
43
+
44
+ interface ITile<TTile> {
45
+ readonly ix: number;
46
+ readonly iz: number;
47
+ /** `null` when the builder found nothing to place: remembered so it is not rebuilt every frame. */
48
+ readonly tile: TTile | null;
49
+ seen: number;
50
+ }
51
+
52
+ /**
53
+ * Square tiles streamed round a moving follow point, nearest first, under a per-frame build budget.
54
+ *
55
+ * A tile is built inside 1.3 × the draw distance and discarded past 1.4 ×, Unreal Landscape grass's
56
+ * guard band (UE 5.8.3: Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp:88, :94), so a
57
+ * follow point on the edge never thrashes. One tile always builds, so the ring advances even under a
58
+ * budget smaller than one build; the rest wait nearest first. The field supplies what a tile is, how
59
+ * it looks at a distance and how it is freed, so grass blades and scattered props stream through the
60
+ * same loop.
61
+ *
62
+ * @constraint call `update(x, z)` once per rendered frame
63
+ * @constraint rotating or scaling the owning group is not supported; translating it is
64
+ */
65
+ export class TileRing<TTile> {
66
+ readonly stats: ITileRingStats = { built: 0, pending: 0, tiles: 0, visible: 0 };
67
+ readonly #field: ITileRingField<TTile>;
68
+ readonly #tiles = new Map<number, ITile<TTile>>();
69
+ readonly #queue: { d: number; ix: number; iz: number; k: number }[] = [];
70
+ #frame = 0;
71
+ #prewarm = false;
72
+
73
+ constructor(field: ITileRingField<TTile>) {
74
+ this.#field = field;
75
+ }
76
+
77
+ /** Every live tile, for a field that has to re-scatter or re-key its own build. */
78
+ tiles(): IterableIterator<ITile<TTile>> {
79
+ return this.#tiles.values();
80
+ }
81
+
82
+ /** Builds every tile in range on the next `update` regardless of budget: on load or after a teleport. */
83
+ prewarm(): void {
84
+ this.#prewarm = true;
85
+ }
86
+
87
+ /** Drops every live tile: the field's density or layout changed. */
88
+ clear(): void {
89
+ for (const entry of this.#tiles.values())
90
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
91
+ this.#tiles.clear();
92
+ }
93
+
94
+ /** Frees the tiles touching a rectangle, so only what changed re-scatters. */
95
+ disposeInside(rect: ITileBounds): void {
96
+ const S = this.#field.chunkSize;
97
+ for (const [k, entry] of this.#tiles) {
98
+ if (
99
+ entry.ix * S > rect.maxX ||
100
+ (entry.ix + 1) * S < rect.minX ||
101
+ entry.iz * S > rect.maxZ ||
102
+ (entry.iz + 1) * S < rect.minZ
103
+ )
104
+ continue;
105
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
106
+ this.#tiles.delete(k);
107
+ }
108
+ }
109
+
110
+ /** Streams, shows and frees the tiles round `(cx, cz)`. Call once per rendered frame. */
111
+ update(cx: number, cz: number): void {
112
+ const field = this.#field;
113
+ const R = field.drawDistance;
114
+ const frame = ++this.#frame;
115
+ this.stats.visible = 0;
116
+ this.#visit(cx, cz, R, frame);
117
+ this.#buildQueued(frame);
118
+ this.#prewarm = false;
119
+ this.#evict(cx, cz, R, frame);
120
+ this.stats.tiles = this.#tiles.size;
121
+ }
122
+
123
+ /** Marks the tiles inside the create band and queues the missing ones. */
124
+ #visit(cx: number, cz: number, R: number, frame: number): void {
125
+ const S = this.#field.chunkSize;
126
+ const reach = R * CREATE_BAND;
127
+ const queue = this.#queue;
128
+ queue.length = 0;
129
+ for (let iz = Math.floor((cz - reach) / S); iz <= Math.floor((cz + reach) / S); iz++) {
130
+ for (let ix = Math.floor((cx - reach) / S); ix <= Math.floor((cx + reach) / S); ix++) {
131
+ const d = tileDistance(ix, iz, cx, cz, S);
132
+ if (d >= reach || !this.#field.inBounds(ix, iz)) continue;
133
+ const k = tileKey(ix, iz);
134
+ const entry = this.#tiles.get(k);
135
+ if (!entry) {
136
+ queue.push({ d, ix, iz, k });
137
+ continue;
138
+ }
139
+ entry.seen = frame;
140
+ if (entry.tile !== null) this.#field.show(entry.tile, d);
141
+ }
142
+ }
143
+ }
144
+
145
+ /** Builds queued tiles nearest first; one always builds, the rest only inside the budget. */
146
+ #buildQueued(frame: number): void {
147
+ const queue = this.#queue;
148
+ queue.sort((a, c) => a.d - c.d);
149
+ const budget = this.#prewarm ? Number.POSITIVE_INFINITY : this.#field.buildBudgetMs;
150
+ const t0 = performance.now();
151
+ let built = 0;
152
+ for (const q of queue) {
153
+ if (built > 0 && performance.now() - t0 > budget) break;
154
+ const tile = this.#field.build(q.ix, q.iz);
155
+ this.#tiles.set(q.k, { ix: q.ix, iz: q.iz, seen: frame, tile });
156
+ if (tile !== null) this.#field.show(tile, q.d);
157
+ built++;
158
+ }
159
+ this.stats.built += built;
160
+ this.stats.pending = queue.length - built;
161
+ }
162
+
163
+ /** Hides tiles that left the view radius and frees those past the discard band. */
164
+ #evict(cx: number, cz: number, R: number, frame: number): void {
165
+ const S = this.#field.chunkSize;
166
+ for (const [k, entry] of this.#tiles) {
167
+ if (entry.seen === frame) continue;
168
+ if (tileDistance(entry.ix, entry.iz, cx, cz, S) > R * DISCARD_BAND) {
169
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
170
+ this.#tiles.delete(k);
171
+ } else if (entry.tile !== null) this.#field.hide(entry.tile);
172
+ }
173
+ }
174
+ }
175
+
176
+ /** The distance from a point to a tile's nearest corner, in the ground plane. */
177
+ export function tileDistance(ix: number, iz: number, cx: number, cz: number, S: number): number {
178
+ const dx = Math.max(ix * S - cx, 0, cx - (ix + 1) * S);
179
+ const dz = Math.max(iz * S - cz, 0, cz - (iz + 1) * S);
180
+ return Math.sqrt(dx * dx + dz * dz);
181
+ }
182
+
183
+ /** A tile column's key: unique for ix and iz in ±32767. */
184
+ export const tileKey = (ix: number, iz: number): number => (ix + 0x8000) * 0x10000 + (iz + 0x8000);
185
+
186
+ /** A seeded 32-bit integer hash of a column and a salt. */
187
+ export function hashInt(x: number, y: number, s: number): number {
188
+ let h =
189
+ Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(s | 0, 0x9e3779b1);
190
+ h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
191
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
192
+ return (h ^ (h >>> 16)) >>> 0;
193
+ }
194
+
195
+ /** The seeded generator both fields scatter their instances from. */
196
+ export function mulberry32(seed: number): () => number {
197
+ let a = seed >>> 0;
198
+ return () => {
199
+ a = (a + 0x6d2b79f5) | 0;
200
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
201
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
202
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
203
+ };
204
+ }
205
+
206
+ /**
207
+ * 0..total-1 in a seeded random order. Visiting a jittered grid in this order means any prefix
208
+ * covers the tile evenly, so distance thinning is a plain instance count.
209
+ */
210
+ export function shuffled(total: number, rng: () => number): Uint32Array {
211
+ const order = new Uint32Array(total);
212
+ for (let i = 0; i < total; i++) order[i] = i;
213
+ for (let i = total - 1; i > 0; i--) {
214
+ const j = (rng() * (i + 1)) | 0;
215
+ const tmp = order[i] as number;
216
+ order[i] = order[j] as number;
217
+ order[j] = tmp;
218
+ }
219
+ return order;
220
+ }
221
+
222
+ /** Height, d/dx and d/dz of the last `groundGrid` sample. */
223
+ export const sample = new Float64Array(3);
224
+
225
+ /**
226
+ * Ground height on a grid one ring wider than a tile, for gradients; `sample` reads it bilinearly.
227
+ * Heights come from the game's own `getHeight`, so a tilt on a prop follows the ground the game
228
+ * draws, not a second copy of it.
229
+ */
230
+ export function groundGrid(
231
+ getHeight: (x: number, z: number) => number,
232
+ ox: number,
233
+ oz: number,
234
+ S: number,
235
+ spacing: number,
236
+ ): { sample(lx: number, lz: number): void } {
237
+ const G = Math.max(1, Math.ceil(S / Math.max(spacing, 0.05)));
238
+ const gs = S / G;
239
+ const N = G + 3;
240
+ const hg = new Float32Array(N * N);
241
+ for (let j = 0; j < N; j++)
242
+ for (let i = 0; i < N; i++)
243
+ hg[j * N + i] = getHeight(ox + (i - 1) * gs, oz + (j - 1) * gs) || 0;
244
+ const gx = new Float32Array(N * N);
245
+ const gz = new Float32Array(N * N);
246
+ const inv2 = 1 / (2 * gs);
247
+ for (let j = 1; j < N - 1; j++)
248
+ for (let i = 1; i < N - 1; i++) {
249
+ const o = j * N + i;
250
+ gx[o] = ((hg[o + 1] as number) - (hg[o - 1] as number)) * inv2;
251
+ gz[o] = ((hg[o + N] as number) - (hg[o - N] as number)) * inv2;
252
+ }
253
+ return {
254
+ sample(lx, lz) {
255
+ const fx = lx / gs + 1;
256
+ const fz = lz / gs + 1;
257
+ const i0 = Math.min(fx | 0, G);
258
+ const j0 = Math.min(fz | 0, G);
259
+ const u = fx - i0;
260
+ const v = fz - j0;
261
+ const o = j0 * N + i0;
262
+ // Bilinear weights once, no closure per call: this runs for every candidate.
263
+ const w00 = (1 - u) * (1 - v);
264
+ const w10 = u * (1 - v);
265
+ const w01 = (1 - u) * v;
266
+ const w11 = u * v;
267
+ const o1 = o + 1;
268
+ const oN = o + N;
269
+ const oN1 = oN + 1;
270
+ sample[0] =
271
+ (hg[o] as number) * w00 +
272
+ (hg[o1] as number) * w10 +
273
+ (hg[oN] as number) * w01 +
274
+ (hg[oN1] as number) * w11;
275
+ sample[1] =
276
+ (gx[o] as number) * w00 +
277
+ (gx[o1] as number) * w10 +
278
+ (gx[oN] as number) * w01 +
279
+ (gx[oN1] as number) * w11;
280
+ sample[2] =
281
+ (gz[o] as number) * w00 +
282
+ (gz[o1] as number) * w10 +
283
+ (gz[oN] as number) * w01 +
284
+ (gz[oN1] as number) * w11;
285
+ },
286
+ };
287
+ }
288
+
289
+ export const clamp01 = (v: number): number => (v < 0 ? 0 : v > 1 ? 1 : v);
290
+
291
+ export function smoothstep(e0: number, e1: number, x: number): number {
292
+ const t = clamp01((x - e0) / Math.max(e1 - e0, 1e-6));
293
+ return t * t * (3 - 2 * t);
294
+ }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-version.mjs - do not edit. Source: package.json.
2
- export const CORE_VERSION = "0.3.13";
2
+ export const CORE_VERSION = "0.3.15";
package/src/warmup.ts CHANGED
@@ -286,6 +286,11 @@ interface INativeEnvironmentPreparer {
286
286
  ): Promise<boolean>;
287
287
  }
288
288
 
289
+ /** `drawPastFrameGate`'s refusal: the renderer never took the covered draw in its whole wait. */
290
+ function isFrameGateTimeout(error: unknown): boolean {
291
+ return error instanceof Error && error.message.startsWith("TN_WARMUP_FRAME_GATE");
292
+ }
293
+
289
294
  function nativeEnvironmentPreparer(raw: unknown): INativeEnvironmentPreparer | undefined {
290
295
  return typeof (raw as Partial<INativeEnvironmentPreparer> | null)?.prepareEnvironmentAsync ===
291
296
  "function"
@@ -1229,12 +1234,19 @@ export async function warmUpScene(
1229
1234
  // Skipped because the budget ran out first: lazy work, like any compile that never
1230
1235
  // started. Rejecting here failed a held startup whose compile merely ran long.
1231
1236
  if (passError === undefined && now() >= startedAt + budgetMs) return;
1237
+ // The frame gate declined the covered draw for its whole wait: the GPU was busy (a
1238
+ // software adapter holds each frame for seconds), which no pipeline caused. The pipelines
1239
+ // build lazily at the first frame that needs them; a rejection here failed the held launch.
1240
+ if (isFrameGateTimeout(passError)) return;
1232
1241
  throw passError ?? new Error("covered world warm render did not settle");
1233
1242
  }
1234
1243
  });
1235
1244
  };
1236
1245
 
1237
1246
  let gpuDrainSettled = true;
1247
+ // The last compile the deadline outran (still pending, not rejected). The expiry timer can fire a
1248
+ // fraction of a millisecond before `now()` reaches the deadline, so the clock alone misses it.
1249
+ let compileOutran = false;
1238
1250
  const compileWithinDeadline = async (
1239
1251
  deadline: number,
1240
1252
  work: Promise<void>,
@@ -1250,7 +1262,8 @@ export async function warmUpScene(
1250
1262
  };
1251
1263
  void work.then(track, track);
1252
1264
  const finished = await withinDeadline(deadline, work, yieldFrame, now);
1253
- if (!finished && !settled) pendingCompiles.push(work);
1265
+ compileOutran = !finished && !settled;
1266
+ if (compileOutran) pendingCompiles.push(work);
1254
1267
  return finished;
1255
1268
  };
1256
1269
  const finish = (report: IWarmUpReport): IWarmUpReport => {
@@ -1369,7 +1382,7 @@ export async function warmUpScene(
1369
1382
  elapsedMs: now() - startedAt,
1370
1383
  unsupported: false,
1371
1384
  abandoned: finished ? 0 : 1,
1372
- timedOut: !finished && (passError === undefined || now() >= deadline),
1385
+ timedOut: !finished && (passError === undefined || compileOutran || now() >= deadline),
1373
1386
  }),
1374
1387
  );
1375
1388
  }
@@ -8,6 +8,7 @@ import {
8
8
  Sphere,
9
9
  Vector3,
10
10
  } from "three";
11
+ import { GEOMETRY_ASSET_KEY } from "./geometry-capture.js";
11
12
  import type { InstancedBatch } from "./instanced-batch.js";
12
13
  import { pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
13
14
  import { type IRecordWriter, batchRecords } from "./world-cell-records.js";
@@ -274,6 +275,9 @@ export class SharedBatch implements IRecordWriter {
274
275
  view.boundingSphere = source.boundingSphere;
275
276
  view.setDrawRange(source.drawRange.start, source.drawRange.count);
276
277
  view.userData.tnPublishedLodRangeView = true;
278
+ // The view is drawn in the source's place, so it keeps the loader's provenance stamp.
279
+ const stamp = source.userData[GEOMETRY_ASSET_KEY];
280
+ if (stamp !== undefined) view.userData[GEOMETRY_ASSET_KEY] = stamp;
277
281
  const ranges = new InstancedBufferAttribute(
278
282
  new Float32Array(capacity * LOD_RANGE_STRIDE),
279
283
  LOD_RANGE_STRIDE,
@@ -210,6 +210,13 @@ export interface IWorldCellsLoadOptions {
210
210
  * loader works. The url is the authored one, so a compiled package wants `assets` instead.
211
211
  */
212
212
  readonly loadModel?: (url: string) => Promise<Object3D>;
213
+ /**
214
+ * The game's surface for one loaded part, given the authored material and the part's geometry: a
215
+ * swaying tree returns its own node material reading the baked wind attribute. Return the material
216
+ * passed in to keep it. The game memoises per source material, so every level and placement of an
217
+ * asset shares one surface; this world releases it with the asset's own.
218
+ */
219
+ readonly partMaterial?: (material: Material, geometry: BufferGeometry) => Material;
213
220
  /**
214
221
  * Model loads in flight at once, assets and chunks together. Defaults to `loadAll`'s
215
222
  * `concurrency`, six.
@@ -155,7 +155,10 @@ function scatterMaterial(
155
155
  */
156
156
  function renderableParts(
157
157
  model: Object3D,
158
- surfaceFor: (material: Material) => { readonly key: string; readonly material: Material },
158
+ surfaceFor: (
159
+ material: Material,
160
+ geometry: BufferGeometry,
161
+ ) => { readonly key: string; readonly material: Material },
159
162
  ): readonly IAssetPart[] {
160
163
  model.updateMatrixWorld(true);
161
164
  const rootInverse = new Matrix4().copy(model.matrixWorld).invert();
@@ -165,7 +168,7 @@ function renderableParts(
165
168
  if (object instanceof SkinnedMesh || !(object instanceof Mesh)) return;
166
169
  const material = Array.isArray(object.material) ? object.material[0] : object.material;
167
170
  if (object.geometry === undefined || material === undefined) return;
168
- const surface = surfaceFor(material);
171
+ const surface = surfaceFor(material, object.geometry);
169
172
  parts.push({
170
173
  geometry: object.geometry,
171
174
  local: local.multiplyMatrices(rootInverse, object.matrixWorld).clone(),
@@ -588,8 +591,9 @@ export class CellModels {
588
591
  readonly #autoLodMaxPixelError: number;
589
592
 
590
593
  readonly #transparentScatter: "cutout" | "blend";
594
+ readonly #partMaterial: IWorldCellsLoadOptions["partMaterial"];
591
595
  constructor(
592
- init: Pick<IWorldCellsLoadOptions, "assets" | "loadModel" | "concurrency"> & {
596
+ init: Pick<IWorldCellsLoadOptions, "assets" | "loadModel" | "concurrency" | "partMaterial"> & {
593
597
  readonly ownsAssets?: boolean;
594
598
  },
595
599
  settings: ICellModelsSettings,
@@ -607,6 +611,7 @@ export class CellModels {
607
611
  this.#loader = init.assets ?? createAssetLoader();
608
612
  this.#ownsLoader = init.ownsAssets ?? init.assets === undefined;
609
613
  this.#loadModel = init.loadModel;
614
+ this.#partMaterial = init.partMaterial;
610
615
  this.#limiter = new ModelLoadLimiter(
611
616
  positiveInteger(init.concurrency ?? WORLD_LOAD_CONCURRENCY, "concurrency"),
612
617
  );
@@ -757,7 +762,16 @@ export class CellModels {
757
762
  /** One loaded model's drawable parts, or `undefined` when it carries nothing to draw. */
758
763
  #partsOf(model: Object3D | undefined): readonly IAssetPart[] | undefined {
759
764
  if (model === undefined) return undefined;
760
- const parts = renderableParts(model, (material) => this.#surfaceFor(material));
765
+ let parts: readonly IAssetPart[];
766
+ try {
767
+ parts = renderableParts(model, (material, geometry) => this.#surfaceFor(material, geometry));
768
+ } catch (error) {
769
+ // A game `partMaterial` that threw or answered with no material: the model is refused, named.
770
+ this.#host.setFailures(this.#host.failures() + 1);
771
+ this.#host.reportCellFailure("asset", model.name || "model", [], error);
772
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
773
+ return undefined;
774
+ }
761
775
  if (parts.length === 0) {
762
776
  // Same as a refused load: counted, released, and the next acquire retries.
763
777
  this.#host.setFailures(this.#host.failures() + 1);
@@ -971,8 +985,21 @@ export class CellModels {
971
985
  * canonical one (converted to a cutout when it is transparent scatter), and every later material
972
986
  * with the same content is released on arrival and draws with it instead.
973
987
  */
974
- #surfaceFor(source: Material): { readonly key: string; readonly material: Material } {
975
- const key = this.#preserveAuthoredParts ? source.uuid : materialKey(source);
988
+ #surfaceFor(
989
+ source: Material,
990
+ geometry: BufferGeometry,
991
+ ): { readonly key: string; readonly material: Material } {
992
+ // The game's own surface for this part (a swaying tree): keyed by its identity, because its
993
+ // content can match an authored material that does not sway.
994
+ const game = this.#partMaterial?.(source, geometry);
995
+ if (game !== undefined && (game as Partial<Material> | null)?.isMaterial !== true)
996
+ throw new Error("WorldCells partMaterial must return a Material.");
997
+ const hooked = game !== undefined && game !== source;
998
+ const key = hooked
999
+ ? `part:${game.uuid}`
1000
+ : this.#preserveAuthoredParts
1001
+ ? source.uuid
1002
+ : materialKey(source);
976
1003
  const shared = this.#surfaces.get(key);
977
1004
  if (shared !== undefined) {
978
1005
  shared.users += 1;
@@ -980,8 +1007,9 @@ export class CellModels {
980
1007
  this.#host.setFailures(this.#host.failures() + 1);
981
1008
  return { key, material: shared.material };
982
1009
  }
983
- const drawn = scatterMaterial(source, this.#transparentScatter);
984
- this.#surfaces.set(key, { material: drawn.material, owned: drawn.owned, users: 1 });
1010
+ const drawn = scatterMaterial(hooked ? game : source, this.#transparentScatter);
1011
+ const owned = hooked ? [source, ...drawn.owned] : drawn.owned;
1012
+ this.#surfaces.set(key, { material: drawn.material, owned, users: 1 });
985
1013
  return { key, material: drawn.material };
986
1014
  }
987
1015
 
@@ -17,10 +17,11 @@ import {
17
17
  import {
18
18
  type ITemporalLod,
19
19
  advanceTemporalLod,
20
+ syncLodCollapse,
20
21
  worldLodMaterial,
21
22
  } from "./render/world-impostor-surface.js";
22
23
  import type { IRendererLike } from "./renderer.js";
23
- import { markStatic } from "./static-transform.js";
24
+ import { markEngineStatic } from "./static-transform.js";
24
25
  import type { ICasterScaleMesh, SharedBatch } from "./world-cell-batches.js";
25
26
  import { levelTriangles } from "./world-cell-chunks.js";
26
27
  import type { IAssetPart, IBatchShape, ICellBatch, IKeyDescriptor } from "./world-cell-data.js";
@@ -244,6 +245,7 @@ export class CellGpuDress {
244
245
  updateLodEye(x: number, y: number, z: number): void {
245
246
  this.#lodEye.value.set(x, y, z);
246
247
  this.#lodClock.value = (performance.now() - this.#lodClockOrigin) / 1000;
248
+ syncLodCollapse();
247
249
  if (this.#host.lodTransition() !== "temporal") return;
248
250
  advanceTemporalLod(this.#temporalLod, this.#lodEye.value, this.#lodClock.value);
249
251
  this.#lodAlpha.value = this.#temporalLod.alpha;
@@ -302,7 +304,7 @@ export class CellGpuDress {
302
304
  // rebound one and the three roles. Static here is only safe because every write announces
303
305
  // itself: `instanceMatrix.needsUpdate` bumps the attribute's version, which is what a settled
304
306
  // draw watches to know it still has to scan.
305
- markStatic(mesh);
307
+ markEngineStatic(mesh);
306
308
  if (role !== "main") {
307
309
  mesh.layers.set(
308
310
  role === "cluster"
@@ -2,7 +2,7 @@ import { BufferGeometry, InstancedMesh, type Material, type Mesh, type Object3D
2
2
  import {
3
3
  composeSilencedByFreeze,
4
4
  isStatic,
5
- markStatic,
5
+ markEngineStatic,
6
6
  worldSilencedByFreeze,
7
7
  } from "./static-transform.js";
8
8
  import type { SharedBatch } from "./world-cell-batches.js";
@@ -210,7 +210,7 @@ export function freshMeshFor(
210
210
  next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
211
211
  // A dressed batch is frozen, and the freeze is keyed by the object: a replacement that did not
212
212
  // re-arm it would compose its own world matrix every walk forever.
213
- if (isStatic(old)) markStatic(next);
213
+ if (isStatic(old)) markEngineStatic(next);
214
214
  return next;
215
215
  }
216
216
 
@@ -194,7 +194,7 @@ async function fetchOk(url: string): Promise<Response> {
194
194
  * @constraint SkinnedMesh parts are skipped; an instanced copy would draw one rest pose
195
195
  * @constraint a baked chain's switch distances are measured against `autoLod` (default 4 px of error over 60° and 1080 raster rows), because an instanced draw cannot select a level per instance; an asset with nonempty authored `lods` never consults it; explicit empty lists enroll only unchanged static geometry/material parts
196
196
  * @constraint eligible static sources can use cooked HLOD (chunk-only alongside GPU scatter, whole-cell on CPU) after compilation and an observed main-context backend submission; projected-error hysteresis requires actual source triangle reduction and no extra material draws, unsupported or shared source stays resident, and collision/shadow paths retain source representations; stats().hlod counts lifecycle and charged resources, not GPU timing or physical allocation
197
- * @override `hlod: false` keeps source rendering; ring, budgets, terrain tile size/resolution, terrain stream and collider radius, `transparentScatter`, `clusterSize` and `shadows.invalidate`, load `concurrency`, `rebuildsPerUpdate`, `admissionBudgetMs` and the package's per-asset maxDistance; `impostorFar: "always"` keeps the far aggregate the near ring's guaranteed radius made unnecessary
197
+ * @override `hlod: false` keeps source rendering; `partMaterial` gives a part the game's own surface (a swaying tree); ring, budgets, terrain tile size/resolution, terrain stream and collider radius, `transparentScatter`, `clusterSize` and `shadows.invalidate`, load `concurrency`, `rebuildsPerUpdate`, `admissionBudgetMs` and the package's per-asset maxDistance; `impostorFar: "always"` keeps the far aggregate the near ring's guaranteed radius made unnecessary
198
198
  * @constraint `prewarmed` resolves once every prewarmed shared batch has been drawn; a game with a loading screen waits on it, and `stats().pendingPrewarm` is the same gate as a number
199
199
  * @constraint every `asset:level:part` is one InstancedMesh for the main pass, plus one caster InstancedMesh per world-grid square of `clusterSize` on the shadow caster layer, so the main pass draws one mesh per key and a shadow level submits only the squares it covers
200
200
  * @constraint two definitions the asset loader resolves to one model — the same cooked `glb`, the same `lods` at the same distances, the same `maxDistance` and bounds — are one asset under the lexicographically smallest id: one model load, one set of `asset:level:part` keys, one prewarm and one refcount, released when the last cell holding any member of the group leaves the ring; `TN_WORLD_ASSET_ALIAS` reports how many of the package's assets are really distinct