@threenative/core 0.3.13 → 0.3.16

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 (60) hide show
  1. package/capabilities.json +1008 -83
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-EEABDLUC.js → chunk-5C4TCWI3.js} +2 -2
  4. package/dist/{chunk-DIPIJICH.js → chunk-FQURMC2F.js} +122 -18
  5. package/dist/{chunk-EFWZWLPY.js → chunk-OMGIYWW7.js} +400 -13
  6. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/hot.js +10 -2
  9. package/dist/index.d.ts +608 -16
  10. package/dist/index.js +2037 -633
  11. package/dist/{model-lod-DPTzeCcD.d.ts → model-lod-B921F6kQ.d.ts} +0 -10
  12. package/dist/playtest.js +3 -3
  13. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  14. package/dist/render-environment.d.ts +1 -1
  15. package/dist/ui-layer.js +2 -2
  16. package/dist/worker.js +2 -2
  17. package/dist/world.d.ts +14 -4
  18. package/dist/world.js +179 -36
  19. package/mcp/animation-server.mjs +1 -1
  20. package/mcp/engine-server.mjs +44 -17
  21. package/mcp/servers.mjs +4 -4
  22. package/package.json +6 -6
  23. package/patches/three@0.187.0-prd269-upgrade.patch +126 -2
  24. package/patches/three@0.187.0.patch +108 -21
  25. package/scripts/ensure-mcp.mjs +6 -1
  26. package/src/clustered-batch.ts +146 -3
  27. package/src/clustered-mesh.ts +548 -20
  28. package/src/debug.ts +16 -0
  29. package/src/displaced-surface.ts +428 -0
  30. package/src/engine-hooks.ts +29 -0
  31. package/src/frame-budget.ts +16 -0
  32. package/src/generated/console-markers.ts +1 -0
  33. package/src/grass-field.ts +628 -0
  34. package/src/grounding.ts +19 -10
  35. package/src/hot.ts +18 -2
  36. package/src/index.ts +112 -0
  37. package/src/instanced-batch-lod.ts +54 -0
  38. package/src/model-lod.ts +77 -1
  39. package/src/pose-measure.ts +27 -2
  40. package/src/render/material-key.ts +21 -1
  41. package/src/render/screen-probe-gather.ts +303 -0
  42. package/src/render/short-range-ao.ts +274 -0
  43. package/src/render/world-impostor-surface.ts +98 -3
  44. package/src/render-camera-cull.ts +9 -3
  45. package/src/renderer.ts +26 -4
  46. package/src/scatter-field.ts +497 -0
  47. package/src/startup-offscreen-bytes.ts +11 -5
  48. package/src/state.ts +16 -3
  49. package/src/static-transform.ts +109 -6
  50. package/src/tile-ring.ts +294 -0
  51. package/src/version.ts +1 -1
  52. package/src/warmup.ts +15 -2
  53. package/src/world-cell-batches.ts +4 -0
  54. package/src/world-cell-data.ts +7 -0
  55. package/src/world-cell-models.ts +36 -8
  56. package/src/world-cell-render-gpu-dress.ts +4 -2
  57. package/src/world-cell-render-util.ts +2 -2
  58. package/src/world-cells.ts +1 -1
  59. package/src/world-river-ribbon.ts +13 -22
  60. package/src/world-water-bodies.ts +113 -3
package/src/hot.ts CHANGED
@@ -131,6 +131,23 @@ function diagnostics<TState extends Record<string, unknown>, TPhysics>(
131
131
  physics: typeof physics?.numBodies === "function" ? physics.numBodies() : null,
132
132
  };
133
133
  }
134
+ /**
135
+ * Name the class and the shape to store: an agent told only "plain objects" rewrites the wrong thing
136
+ * (hosted Studio, 2026-11-17: a Vector3 in state reloaded the page on every edit).
137
+ */
138
+ function notPlain(value: object, prototype: object, path: string): Error {
139
+ const named = (prototype as { constructor?: { name?: unknown } }).constructor?.name;
140
+ const name = typeof named === "string" && named.length > 0 ? named : "class instance";
141
+ // three keeps some fields private (`Quaternion._x`): the shape to store is the public name.
142
+ const keys = Object.keys(value).map((key) => key.replace(/^_/u, ""));
143
+ const shape =
144
+ keys.length > 0 && keys.length <= 6
145
+ ? `{ ${keys.join(", ")} } as a plain object`
146
+ : "its data as plain values";
147
+ return new Error(
148
+ `Hot reload state ${path} must contain only plain objects: it is a ${name}. Store ${shape} and rebuild the ${name} where the code needs it.`,
149
+ );
150
+ }
134
151
  function visitPortable(value: unknown, path: string, ancestors: Set<object>): void {
135
152
  if (value === null) return;
136
153
  if (typeof value === "string" || typeof value === "boolean") return;
@@ -149,8 +166,7 @@ function visitPortable(value: unknown, path: string, ancestors: Set<object>): vo
149
166
  return;
150
167
  }
151
168
  const prototype = Object.getPrototypeOf(value);
152
- if (prototype !== Object.prototype && prototype !== null)
153
- throw new Error(`Hot reload state ${path} must contain only plain objects.`);
169
+ if (prototype !== Object.prototype && prototype !== null) throw notPlain(value, prototype, path);
154
170
  ancestors.add(value);
155
171
  for (const key of Object.keys(value))
156
172
  visitPortable((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors);
package/src/index.ts CHANGED
@@ -360,6 +360,60 @@ export type {
360
360
  ITracedRay,
361
361
  ITracedReflectionsOptions,
362
362
  } from "./render/traced-reflections.js";
363
+ /**
364
+ * Lumen's Screen Probe Gather: one probe per 16 x 16 pixels traces an 8 x 8 octahedron of rays, the probes are filtered
365
+ * into an irradiance octahedron each, and a pixel blends the four nearest probes it can see, instead of every pixel
366
+ * tracing its own rays. A ray that hits on screen returns the lit frame minus the cache along it; a ray that leaves the
367
+ * screen continues through the packed scene up to the radiance cache's cell and reads the cache where it ended, so the
368
+ * light that arrives from off screen is that direction's and not the pixel's mean.
369
+ * @situation bounce light that reads the room off screen instead of a flat ambient term
370
+ * @situation global illumination that costs a fraction of one ray per pixel
371
+ * @situation the light a corner sees from around the wall, which a per-pixel screen trace loses
372
+ * @situation lumen screen probe gather
373
+ * @situation lumen final gather
374
+ * @constraint the owned engine only: on engine: "threejs" the upstream node takes the camera as its fourth argument and has no probes, and gather() refuses
375
+ * @constraint the gather is a delta in E / pi: multiply it by the receiver's diffuse colour (mrt({ diffuseColor })) and add it after the scene pass, and give the scene pass no other indirect diffuse or the light is counted twice
376
+ * @constraint a viewport resize needs a new gather: the probe grid is fixed when it is built
377
+ * @constraint the grid is the cost: downsampleFactor 16 and an 8 x 8 octahedron are Unreal's Epic, 32 and 8 its High
378
+ * @constraint radiance answers in the frame's units (the cache read times the frame's gain), and a trace reads it only where the screen has nothing
379
+ * @override downsampleFactor, tracingOctahedronResolution, cacheCellSize, timedPass and the strength of the composite are game-owned choices
380
+ * @example
381
+ * const gather = new ScreenProbeGather({ camera, viewport, radiance, trace });
382
+ * const gi = gather.gather(convertToTexture(input), depth(), normalView());
383
+ * const bounce = gather.getGINode().rgb.mul(diffuseColor.rgb);
384
+ */
385
+ export { ScreenProbeGather } from "./render/screen-probe-gather.js";
386
+ export type {
387
+ IScreenProbeCamera,
388
+ IScreenProbeGatherOptions,
389
+ IScreenProbeGatherReport,
390
+ ScreenProbePass,
391
+ } from "./render/screen-probe-gather.js";
392
+ /**
393
+ * Unreal's Short Range AO: a horizon search of 2 sweeps around the view normal, 3 samples each at the squared fraction
394
+ * of a 32 px screen reach, at full resolution, with a bent normal at Epic. It is the occlusion that runs *with* dynamic
395
+ * global illumination — the contact detail Lumen keeps after the screen probe gather has already answered the wide
396
+ * occlusion — so a gathered frame is not darkened twice by two wide treatments. The result is one texture: `rgb` the
397
+ * bent normal in view space, `a` the share of the hemisphere left open, which multiplies indirect light only.
398
+ * @situation contact shadow at the foot of an object while dynamic GI runs
399
+ * @situation dark line where a wall meets the floor, without a second wide AO over the gathered light
400
+ * @situation lumen short range ao
401
+ * @constraint it replaces GTAO when dynamic GI runs; a tier without GI keeps ambientOcclusion
402
+ * @constraint the occlusion multiplies indirect light only: direct light and emission keep their own occlusion
403
+ * @constraint multi-bounce and its albedo cap belong to the game's composite; Unreal caps the albedo at 0.5
404
+ * @constraint an authored stage that carries its name must anchor itself (`before: "ssgi"`), because the chain's built-in order names no shortRangeAO
405
+ * @override horizonSearchSliceCount, horizonSearchStepCount, reachPx, bentNormal and intensity are game-owned choices
406
+ * @example
407
+ * const shortRange = new ShortRangeAO({ camera, viewport: renderer.drawingBufferSize });
408
+ * const contact = shortRange.occlusion(depth(), normalView());
409
+ * const indirect = input.rgb.mul(contact.a);
410
+ */
411
+ export { ShortRangeAO } from "./render/short-range-ao.js";
412
+ export type {
413
+ IShortRangeAOCamera,
414
+ IShortRangeAOOptions,
415
+ IShortRangeAOReport,
416
+ } from "./render/short-range-ao.js";
363
417
  /**
364
418
  * Collapse many copies of one game-authored shape into a single draw, without counting them first.
365
419
  *
@@ -456,6 +510,15 @@ export type { IMergeByMaterialOptions } from "./merge-parts.js";
456
510
  * if (debugFlag("freeCam")) camera.flyMode = true;
457
511
  */
458
512
  export { debugFlag } from "./debug.js";
513
+ /**
514
+ * Read the text a debug switch was given by the launch, on the same rule as `debugFlag`.
515
+ * @situation read a debug override whose value is not a boolean
516
+ * @situation override a quality tier or a mode for one run without changing the code
517
+ * @constraint the same name rule as `debugFlag`: `?quality=` on the web, `TN_DEBUG_QUALITY` on a native launch
518
+ * @example import { debugValue } from "@threenative/core";
519
+ * const tier = debugValue("quality");
520
+ */
521
+ export { debugValue } from "./debug.js";
459
522
  /**
460
523
  * Publish one game object under `__THREENATIVE__.debug` for a capture script or the console.
461
524
  * @situation expose a game object to a capture script or the console in dev builds
@@ -1477,6 +1540,55 @@ export type {
1477
1540
  */
1478
1541
  export { GPUReadback } from "./gpu-readback.js";
1479
1542
  export type { IGPUReadbackOptions, IGPUReadbackSample } from "./gpu-readback.js";
1543
+ /**
1544
+ * Stream instanced grass in chunks around the camera; the game owns the blade and its TSL material.
1545
+ * @situation grass that sways and parts around the player
1546
+ * @situation a meadow, lawn or grassy field over terrain that streams around the camera
1547
+ * @situation ground cover grass blades with distance thinning and LOD that does not pop
1548
+ * @situation grass flattened or pushed aside where the player, a creature or a vehicle walks
1549
+ * @situation grow grass on a terrain biome's grass rows with grassFieldFromBiome
1550
+ * @constraint call `update(camera)` once per rendered frame from `ctx.beforeRender`; chunks build nearest first inside `buildBudgetMs`
1551
+ * @constraint the material reads `GRASS_FIELD_ATTRIBUTES` and the field's `nodes` uniforms, so its thinning matches the CPU trim
1552
+ * @constraint a chunk is built inside 1.3 × the draw distance and discarded past 1.4 ×, so a camera on the edge rebuilds nothing
1553
+ * @override densityScale and cullDistanceScale scale every density and distance at once; prewarm() builds all in range on the next update
1554
+ * @example // the look lives in the kit's src/render/grass.ts
1555
+ * const grass = new GrassField3D({ blade: grassBlade(), material: grassMaterial, getHeight: height });
1556
+ * ctx.add(grass);
1557
+ * ctx.beforeRender(() => { grass.pushers[0]?.set(hero.x, hero.y, hero.z, 1.2); grass.update(ctx.camera); });
1558
+ */
1559
+ export { GRASS_FIELD_ATTRIBUTES, GrassField3D } from "./grass-field.js";
1560
+ export type {
1561
+ IGrassField3DOptions,
1562
+ IGrassFieldBlade,
1563
+ IGrassFieldBounds,
1564
+ IGrassFieldNodes,
1565
+ IGrassFieldStats,
1566
+ } from "./grass-field.js";
1567
+
1568
+ /**
1569
+ * Stream instanced copies of any baked mesh around a follow point, with distance thinning and levels
1570
+ * of detail, from the game's own placement rule.
1571
+ * @situation scatter fallen logs, twigs, leaf litter, stones and ferns over a forest floor
1572
+ * @situation stream instanced props of any baked mesh round the player without one draw per prop
1573
+ * @situation place rocks, debris or plants on a heightfield with distance thinning and level of detail
1574
+ * @constraint call `update(follow)` once per rendered frame
1575
+ * @constraint `place` runs once per candidate per tile build: return false for paths and clearings
1576
+ * @constraint rotating or scaling the field is not supported; translating it is
1577
+ * @requires npm i -D @threenative/procedural-environment for the bake these instances come from
1578
+ * @example
1579
+ * const floor = new ScatterField3D({ parts: [{ lods, material }], getHeight, density: 0.05, place });
1580
+ * ctx.add(floor);
1581
+ * ctx.beforeRender(() => floor.update(hero.position));
1582
+ */
1583
+ export { ScatterField3D } from "./scatter-field.js";
1584
+ export type {
1585
+ IScatterField3DOptions,
1586
+ IScatterFieldBounds,
1587
+ IScatterFieldStats,
1588
+ IScatterPart,
1589
+ IScatterPlacement,
1590
+ IScatterPoint,
1591
+ } from "./scatter-field.js";
1480
1592
  /**
1481
1593
  * Dispatch a game-owned particle surface and process function through a pooled system.
1482
1594
  * @situation emit sparks, smoke, or other transient effects
@@ -11,6 +11,7 @@ import {
11
11
  DISCRETE_LOD_DEFAULT_HYSTERESIS,
12
12
  type IModelLodController,
13
13
  biasedLodDistance,
14
+ lodBias,
14
15
  lodChainOf,
15
16
  registerModelLodController,
16
17
  selectLodFor,
@@ -155,6 +156,24 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
155
156
  const sphere = new Sphere();
156
157
  let children: InstancedMesh[] = [];
157
158
  let triangles = 0;
159
+ // PRD-898 J3: on the owned engine the per-instance sort below is one call a frame
160
+ // (`lod::selectInstancedLods`), handed the partitions once, instead of three crossings per instance.
161
+ const engine = instancedLodHooks(mesh);
162
+ let attached = false;
163
+ function attachEngine(hooks: IInstancedLodHooks): void {
164
+ const authored = options.lods !== undefined;
165
+ hooks.attach.call(
166
+ mesh,
167
+ children,
168
+ Array.from(partitionOf),
169
+ authored ? distances : [],
170
+ [local.center.x, local.center.y, local.center.z, local.radius],
171
+ authored ? null : [...(chain?.errors ?? [])],
172
+ budget,
173
+ hysteresis,
174
+ );
175
+ attached = true;
176
+ }
158
177
  function ensureChildren(): void {
159
178
  if (children.length > 0) return;
160
179
  children = groups.flatMap((indices, partition) =>
@@ -186,6 +205,11 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
186
205
  },
187
206
  update(camera: Camera, viewportHeight: number): void {
188
207
  ensureChildren();
208
+ if (engine !== undefined) {
209
+ if (!attached) attachEngine(engine);
210
+ triangles = engine.update.call(mesh, camera, viewportHeight, lodBias());
211
+ return;
212
+ }
189
213
  triangles = 0;
190
214
  mesh.updateWorldMatrix(true, false);
191
215
  camera.getWorldPosition(cameraPosition);
@@ -258,6 +282,7 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
258
282
  child.dispose();
259
283
  }
260
284
  children = [];
285
+ attached = false;
261
286
  mesh.geometry = base;
262
287
  triangles = 0;
263
288
  },
@@ -276,3 +301,32 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
276
301
  ensureChildren();
277
302
  mesh.addEventListener("dispose", () => controller.release());
278
303
  }
304
+
305
+ interface IInstancedLodHooks {
306
+ readonly attach: (
307
+ children: readonly InstancedMesh[],
308
+ partitionOf: readonly number[],
309
+ distances: readonly number[],
310
+ local: readonly number[],
311
+ chainErrors: readonly number[] | null,
312
+ budget: number,
313
+ hysteresis: number,
314
+ ) => void;
315
+ readonly update: (camera: Camera, viewportHeight: number, bias: number) => number;
316
+ }
317
+
318
+ /** The owned engine's instanced LOD calls (abi/bindings_scene.cpp), or undefined on plain three.js. */
319
+ function instancedLodHooks(mesh: InstancedMesh): IInstancedLodHooks | undefined {
320
+ const carrier = mesh as InstancedMesh & {
321
+ readonly __tnInstancedLodAttach?: unknown;
322
+ readonly __tnInstancedLodUpdate?: unknown;
323
+ };
324
+ const attach = carrier.__tnInstancedLodAttach;
325
+ const update = carrier.__tnInstancedLodUpdate;
326
+ return typeof attach === "function" && typeof update === "function"
327
+ ? {
328
+ attach: attach as IInstancedLodHooks["attach"],
329
+ update: update as IInstancedLodHooks["update"],
330
+ }
331
+ : undefined;
332
+ }
package/src/model-lod.ts CHANGED
@@ -404,6 +404,35 @@ class ModelLod {
404
404
  return this.#chain.base;
405
405
  }
406
406
 
407
+ /** PRD-898 J2: whether the engine's batched selection can run this one (the join authority cannot). */
408
+ get batchable(): boolean {
409
+ return this.#rung === undefined || !this.#authority;
410
+ }
411
+
412
+ #attached = false;
413
+
414
+ /** The mesh for `__tnModelLodSelect`, its chain handed to the engine on first use. */
415
+ engineMesh(): Mesh {
416
+ if (!this.#attached) {
417
+ const { center, radius } = this.#chain.sphere;
418
+ (this.#mesh as Mesh & IModelLodEngineMesh).__tnModelLodAttach(
419
+ [...this.#chain.errors],
420
+ [center.x, center.y, center.z, radius],
421
+ this.#policy.maxPixelError,
422
+ this.#policy.hysteresis,
423
+ this.#current,
424
+ );
425
+ this.#attached = true;
426
+ }
427
+ return this.#mesh;
428
+ }
429
+
430
+ /** The level the engine's batched selection chose. */
431
+ applyLevel(index: number): void {
432
+ this.#current = index;
433
+ this.#mesh.geometry = this.#chain.levels[index] as BufferGeometry;
434
+ }
435
+
407
436
  get triangles(): number {
408
437
  // With a joined rung active, the authored primitives draw nothing and the proxy draws the
409
438
  // collapse: the authority reports the rung's triangles, every hidden sibling reports zero.
@@ -501,6 +530,23 @@ class ModelLod {
501
530
  }
502
531
  }
503
532
 
533
+ /** The owned engine's ModelLod calls (abi/bindings_scene.cpp), absent on plain three.js. */
534
+ interface IModelLodEngineMesh {
535
+ __tnModelLodAttach(
536
+ errors: readonly number[],
537
+ local: readonly number[],
538
+ maxPixelError: number,
539
+ hysteresis: number,
540
+ current: number,
541
+ ): void;
542
+ }
543
+
544
+ type ModelLodSelect = (viewportHeight: number, bias: number) => readonly number[];
545
+
546
+ interface IModelLodEngineSet {
547
+ __tnModelLodMeshes(meshes: readonly Mesh[]): void;
548
+ }
549
+
504
550
  /** Resolved runtime policy the loader stamps onto a controller, from the manifest. */
505
551
  export interface IModelLodPolicy {
506
552
  readonly hysteresis: number;
@@ -1416,6 +1462,29 @@ function trackRoot(root: IGraphNode): ITrackedRoot {
1416
1462
  *
1417
1463
  * @returns triangles the managed meshes will submit this frame.
1418
1464
  */
1465
+ /** The batched set the engine holds (`__tnModelLodMeshes`), resent only when it changes. */
1466
+ let engineBatch: readonly ModelLod[] = [];
1467
+
1468
+ /** One engine call selects every batched ModelLod; only the changed levels come back. */
1469
+ function selectBatched(
1470
+ select: ModelLodSelect,
1471
+ camera: Camera,
1472
+ batched: readonly ModelLod[],
1473
+ viewportHeight: number,
1474
+ ): void {
1475
+ if (
1476
+ batched.length !== engineBatch.length ||
1477
+ batched.some((entry, i) => entry !== engineBatch[i])
1478
+ ) {
1479
+ const meshes = batched.map((entry) => entry.engineMesh());
1480
+ (camera as Camera & IModelLodEngineSet).__tnModelLodMeshes(meshes);
1481
+ engineBatch = batched;
1482
+ }
1483
+ const changed = select.call(camera, viewportHeight, lodBias());
1484
+ for (let i = 0; i < changed.length; i += 2)
1485
+ (batched[changed[i] as number] as ModelLod).applyLevel(changed[i + 1] as number);
1486
+ }
1487
+
1419
1488
  export function updateModelLods(
1420
1489
  root: { traverse(callback: (object: object) => void): void },
1421
1490
  camera: Camera,
@@ -1436,6 +1505,10 @@ export function updateModelLods(
1436
1505
  return triangles;
1437
1506
  }
1438
1507
  const tracking = trackRoot(root);
1508
+ // PRD-898 J2: on the owned engine every plain selection is one call, and only changed levels return.
1509
+ const hook = (camera as Camera & { __tnModelLodSelect?: unknown }).__tnModelLodSelect;
1510
+ const select = typeof hook === "function" ? (hook as ModelLodSelect) : undefined;
1511
+ const batched: ModelLod[] = [];
1439
1512
  for (const mesh of tracking.items) {
1440
1513
  const entry = controllerFor(mesh);
1441
1514
  if (entry === undefined) {
@@ -1443,8 +1516,11 @@ export function updateModelLods(
1443
1516
  if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1444
1517
  continue;
1445
1518
  }
1446
- entry.update(camera, viewportHeight);
1519
+ if (select !== undefined && entry instanceof ModelLod && entry.batchable) batched.push(entry);
1520
+ else entry.update(camera, viewportHeight);
1447
1521
  }
1522
+ if (select !== undefined && batched.length > 0)
1523
+ selectBatched(select, camera, batched, viewportHeight);
1448
1524
  let triangles = 0;
1449
1525
  for (const mesh of tracking.items) triangles += controllers.get(mesh)?.triangles ?? 0;
1450
1526
  return triangles;
@@ -1,5 +1,6 @@
1
1
  import { AttachedBindMode, Box3, type Object3D, Quaternion, Vector3 } from "three";
2
2
  import type { Mesh, SkinnedMesh } from "three";
3
+ import { sphereBoundsHook } from "./engine-hooks.js";
3
4
 
4
5
  /**
5
6
  * Brings every attached-mode skinned mesh under `root` to the bind state the renderer would give it.
@@ -414,11 +415,35 @@ function getEnvelope(
414
415
  * read one world-matrix translation per contributing bone and allocate nothing. The returned
415
416
  * object is cached for the root and updated in place; copy it if it must outlive the next call.
416
417
  */
418
+ /** PRD-898 J4: which envelope's spheres the engine holds for each root. */
419
+ const engineEnvelope = new WeakMap<Object3D, IPosedBoundsEnvelope>();
420
+
417
421
  export function posedBounds(root: Object3D, meshes?: readonly Object3D[]): IThreePoseBounds {
418
422
  const envelope = getEnvelope(root, meshes);
419
- root.updateWorldMatrix(true, true);
420
- rawBounds(envelope, envelope.raw);
421
423
  const raw = envelope.raw;
424
+ // PRD-898 J4: on the owned engine the matrix pass and every sphere read are one call.
425
+ const engine = sphereBoundsHook(root);
426
+ if (engine === undefined) {
427
+ root.updateWorldMatrix(true, true);
428
+ rawBounds(envelope, raw);
429
+ } else {
430
+ // The engine keeps one sphere set per root: hand this envelope's over when it is not the one held.
431
+ if (engineEnvelope.get(root) !== envelope) {
432
+ engine.attach.call(
433
+ root,
434
+ [...envelope.bones.map((s) => s.bone), ...envelope.statics.map((s) => s.object)],
435
+ [...envelope.bones.map((s) => s.radius), ...envelope.statics.map((s) => s.radius)],
436
+ );
437
+ engineEnvelope.set(root, envelope);
438
+ }
439
+ const box = engine.bounds.call(root);
440
+ raw.minX = box[0] ?? Number.POSITIVE_INFINITY;
441
+ raw.minY = box[1] ?? Number.POSITIVE_INFINITY;
442
+ raw.minZ = box[2] ?? Number.POSITIVE_INFINITY;
443
+ raw.maxX = box[3] ?? Number.NEGATIVE_INFINITY;
444
+ raw.maxY = box[4] ?? Number.NEGATIVE_INFINITY;
445
+ raw.maxZ = box[5] ?? Number.NEGATIVE_INFINITY;
446
+ }
422
447
  const min = envelope.result.min;
423
448
  const max = envelope.result.max;
424
449
  const size = envelope.result.size;
@@ -16,11 +16,31 @@ const TEXTURE_SLOTS = [
16
16
  "alphaMap",
17
17
  ] as const;
18
18
 
19
+ /** Ids for unnamed textures whose source carries no `uuid` (the owned engine's), one per texture. */
20
+ const unnamedIds = new WeakMap<Texture, number>();
21
+ let nextUnnamedId = 0;
22
+
23
+ /** The texture's own source identity: three's source `uuid`, else a per-texture id from this module. */
24
+ function sourceId(texture: Texture): string {
25
+ const uuid = (texture.source as { uuid?: string } | undefined)?.uuid;
26
+ if (uuid !== undefined) return uuid;
27
+ let id = unnamedIds.get(texture);
28
+ if (id === undefined) {
29
+ id = nextUnnamedId++;
30
+ unnamedIds.set(texture, id);
31
+ }
32
+ return `#${String(id)}`;
33
+ }
34
+
19
35
  function textureKey(texture: Texture | null | undefined): string {
20
36
  if (texture === null || texture === undefined) return "-";
21
37
  const image = texture.image as { width?: number; height?: number } | undefined;
22
38
  const mips = (texture as { mipmaps?: readonly { data?: { byteLength?: number } }[] }).mipmaps;
23
- return `${texture.name}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture.flipY ? 1 : 0}`;
39
+ // A name is what lets two loads of one image match. Without one, nothing here tells two images of
40
+ // one size apart (generated leaf atlases are all 1024², unnamed, with no mip bytes), so the
41
+ // texture's own source is its identity: it never shares, and never draws another's pixels.
42
+ const id = texture.name !== "" ? texture.name : `source:${sourceId(texture)}`;
43
+ return `${id}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture.flipY ? 1 : 0}`;
24
44
  }
25
45
 
26
46
  /**