@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
@@ -212,16 +212,6 @@ declare function baseGeometryOf(mesh: Mesh): BufferGeometry;
212
212
  * geometry.
213
213
  */
214
214
  declare function lodChainOf(geometry: BufferGeometry): ILodChain | undefined;
215
- /**
216
- * Takes every discrete-LOD mesh under `root` through this frame's selection.
217
- *
218
- * The engine calls this itself, once a frame, after matrices are synced and before the render.
219
- * Multi-view callers that need the finest level across passes use {@link selectLodLevel} directly;
220
- * this entry point selects for the one camera it is handed — which is the main view, and is at
221
- * least as fine as a shadow pass of lower resolution needs.
222
- *
223
- * @returns triangles the managed meshes will submit this frame.
224
- */
225
215
  declare function updateModelLods(root: {
226
216
  traverse(callback: (object: object) => void): void;
227
217
  }, camera: Camera, viewportHeight: number): number;
package/dist/playtest.js CHANGED
@@ -1,6 +1,6 @@
1
- import { PIPELINE_CENSUS_CAPABILITY, discardEngineCountsSinceLastFrame, readRenderChainObservation, CORE_VERSION } from './chunk-EEABDLUC.js';
2
- import { GEOMETRY_CAPTURE_CAPABILITY } from './chunk-EFWZWLPY.js';
3
- import './chunk-GYUZJQ7U.js';
1
+ import { PIPELINE_CENSUS_CAPABILITY, discardEngineCountsSinceLastFrame, readRenderChainObservation, CORE_VERSION } from './chunk-5C4TCWI3.js';
2
+ import { GEOMETRY_CAPTURE_CAPABILITY } from './chunk-OMGIYWW7.js';
3
+ import './chunk-VQRPEOKY.js';
4
4
  import { audioRuntimeSnapshot } from './chunk-U4YHUKKL.js';
5
5
  import './chunk-XDTZ4QMO.js';
6
6
  import './chunk-VP43GIWW.js';
@@ -1,4 +1,4 @@
1
- import { Box3, Material, DataTexture, Mesh, Object3D, Vector2, Camera, DirectionalLight, RenderTarget, Texture, Scene } from 'three';
1
+ import { Box3, Material, DataTexture, Object3D, Mesh, Vector2, Camera, DirectionalLight, RenderTarget, Texture, Scene } from 'three';
2
2
  import { pass } from 'three/tsl';
3
3
  import { Node, TextureNode, NodeBuilder, NodeFrame } from 'three/webgpu';
4
4
  import { R as RendererToneMapping } from './default-tone-mapping-GgKPTiBP.js';
@@ -865,4 +865,4 @@ declare const qualityTiers: {
865
865
  readonly shadow: typeof shadowPreset;
866
866
  };
867
867
 
868
- export { AutoExposureNode as A, type ChainStage as C, EPIC_SSGI as E, type FinalGatherMethod as F, type GIVisualizeMode as G, type IExposureSettings as I, type OutputRenderer as O, type QualityTier as Q, type ScreenSpaceAA as S, type TonemapMode as T, WorldEnvironment as W, GIVisualize as a, GI_VISUALIZE_MODES as b, type IGIVisualizeOptions as c, type IGiTier as d, type IReflectionRoute as e, type IShadowFilter as f, type IShadowTier as g, type ITracedHit as h, type ITracedRay as i, type ITracedReflectionsOptions as j, type IWorldEnvironmentOptions as k, type IWorldEnvironmentStageContext as l, type IWorldEnvironmentTarget as m, type SsgiQuality as n, TracedReflections as o, exposureSettings as p, installFilmicToneMapping as q, qualityPreset as r, qualityTiers as s };
868
+ export { AutoExposureNode as A, type ChainStage as C, EPIC_SSGI as E, type FinalGatherMethod as F, type GIVisualizeMode as G, type IExposureSettings as I, type OutputRenderer as O, type QualityTier as Q, type ScreenSpaceAA as S, TracedReflections as T, WorldEnvironment as W, GIVisualize as a, GI_VISUALIZE_MODES as b, type IGIVisualizeOptions as c, type IGiTier as d, type IReflectionRoute as e, type IShadowFilter as f, type IShadowTier as g, type ITracedHit as h, type ITracedRay as i, type ITracedReflectionsOptions as j, type IWorldEnvironmentOptions as k, type IWorldEnvironmentStageContext as l, type IWorldEnvironmentTarget as m, type SsgiQuality as n, type TonemapMode as o, exposureSettings as p, installFilmicToneMapping as q, qualityPreset as r, qualityTiers as s };
@@ -1,5 +1,5 @@
1
1
  import { Scene, Color, Texture } from 'three';
2
- import { Q as QualityTier } from './quality-BYqKGAwo.js';
2
+ import { Q as QualityTier } from './quality-BADStsTn.js';
3
3
  import 'three/tsl';
4
4
  import 'three/webgpu';
5
5
  import './default-tone-mapping-GgKPTiBP.js';
package/dist/ui-layer.js CHANGED
@@ -1,5 +1,5 @@
1
- export { onUiIntent, publishUiState, sendUiIntent, subscribeUiState } from './chunk-4SRAQFTU.js';
2
- import './chunk-GYUZJQ7U.js';
1
+ export { onUiIntent, publishUiState, sendUiIntent, subscribeUiState } from './chunk-2GPHICV6.js';
2
+ import './chunk-VQRPEOKY.js';
3
3
  import './chunk-VP43GIWW.js';
4
4
  import { HIT_REGIONS_MESSAGE } from './chunk-CFGTPFUH.js';
5
5
  export { GAME_STATE_MESSAGE, HIT_REGIONS_MESSAGE, UI_BRIDGE_GLOBALS, UI_DEV_METRICS_MESSAGE, UI_INTENT_MESSAGE, UI_READY_INTENT, UI_STARTUP_MESSAGE, connectUiBridge } from './chunk-CFGTPFUH.js';
package/dist/worker.js CHANGED
@@ -1,5 +1,5 @@
1
- import { markerLogRequested } from './chunk-SV4QVUTQ.js';
2
- import { debugRequested, countDebug } from './chunk-GYUZJQ7U.js';
1
+ import { markerLogRequested } from './chunk-QAQHYOWY.js';
2
+ import { debugRequested, countDebug } from './chunk-VQRPEOKY.js';
3
3
  import { hostWindow, hostDocument, hostResizeObserver } from './chunk-XDTZ4QMO.js';
4
4
  import './chunk-VP43GIWW.js';
5
5
  import { GAME_STATE_MESSAGE } from './chunk-CFGTPFUH.js';
package/dist/world.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Group, Vector3, BufferGeometry, Mesh, Object3D, LOD, Camera, Matrix4, Material, Box3, Texture, Data3DTexture } from 'three';
2
- import { I as IComputeDriven, a as IGPUReadbackSample, b as ILodView, c as IModelLodPolicy } from './model-lod-DPTzeCcD.js';
2
+ import { I as IComputeDriven, a as IGPUReadbackSample, b as ILodView, c as IModelLodPolicy } from './model-lod-B921F6kQ.js';
3
3
  import { I as IRendererLike } from './renderer-BtOSseYf.js';
4
4
  import { I as IAssetLoader } from './assets-CfMKnOsK.js';
5
5
  import { Node } from 'three/webgpu';
@@ -454,13 +454,16 @@ interface ILakeSurfaceOptions {
454
454
  }
455
455
  /**
456
456
  * A lake's water surface: a level disc out to `lakeReach`, the footprint `WaterBodies` floods, with a
457
- * `metres` attribute (water depth over the ground). Only cells with water at a corner get triangles,
458
- * so the surface does not hover over dry hillside and the shore follows the ground's contour. The
457
+ * `metres` attribute (water depth over the ground). Only cells with a corner the seed's water reaches
458
+ * get triangles, so the surface does not hover over dry hillside, a hollow past the basin's rim (a
459
+ * river valley beyond the dam) stays dry instead of standing under a sheet that stops where the reach
460
+ * does, and the shore follows the ground's contour. The
459
461
  * rings pack towards the middle, so an irregular basin costs vertices where the camera sees them.
460
462
  * Returns `undefined` when the basin holds no water at its level.
461
463
  *
462
464
  * @situation draw a lake's water surface from the baked level and seed
463
465
  * @situation a lake's drawn water and the swimmer's water disagree
466
+ * @situation lake water ends in a straight edge over a valley past the basin's rim
464
467
  * @constraint the lake row and field come from the game's bake; the game's material shades the geometry
465
468
  * @example const geometry = lakeSurfaceGeometry({ ...lake, margin: 1.12 }, field, { maxDepth: 1.6 });
466
469
  */
@@ -1939,6 +1942,13 @@ interface IWorldCellsLoadOptions {
1939
1942
  * loader works. The url is the authored one, so a compiled package wants `assets` instead.
1940
1943
  */
1941
1944
  readonly loadModel?: (url: string) => Promise<Object3D>;
1945
+ /**
1946
+ * The game's surface for one loaded part, given the authored material and the part's geometry: a
1947
+ * swaying tree returns its own node material reading the baked wind attribute. Return the material
1948
+ * passed in to keep it. The game memoises per source material, so every level and placement of an
1949
+ * asset shares one surface; this world releases it with the asset's own.
1950
+ */
1951
+ readonly partMaterial?: (material: Material, geometry: BufferGeometry) => Material;
1942
1952
  /**
1943
1953
  * Model loads in flight at once, assets and chunks together. Defaults to `loadAll`'s
1944
1954
  * `concurrency`, six.
@@ -2444,7 +2454,7 @@ declare function instanceRandom(): Node<"float">;
2444
2454
  * @constraint SkinnedMesh parts are skipped; an instanced copy would draw one rest pose
2445
2455
  * @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
2446
2456
  * @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
2447
- * @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
2457
+ * @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
2448
2458
  * @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
2449
2459
  * @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
2450
2460
  * @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
package/dist/world.js CHANGED
@@ -1,7 +1,7 @@
1
- import { SPANS, createAssetLoader, addInSlices, yieldToHost, batchRecords, drainMeshPool, spanRecorder, spanNow, addSpan, fetchAsset, placedBox, InstancedBatch, INSTANCED_LOD_MAX_PIXEL_ERROR, dropPooledFor, DRAW_ARGS_BYTES, parkMesh, warmUpSceneWithCompletion, loadAll, warmUpScene, markStatic, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, pooledCapacity, pooledMesh, displacesVertices, DEFAULT_TARGET_FPS, STORAGE_PLAIN, argsWords, NO_LOCAL, SLOT_NONE, LOCAL_WORDS, storageAttribute, SOURCE_FLOOR, PLACEMENT_ROWS, DRAW_ARGS_WORDS, growBuffer, addRange, PLACEMENT_WORDS, VEC4_WORDS, composeSilencedByFreeze, worldSilencedByFreeze, isStatic, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, mergeByMaterial, VALIDATE_EVERY, TALLY_EVERY, nodes } from './chunk-DIPIJICH.js';
1
+ import { SPANS, createAssetLoader, addInSlices, yieldToHost, batchRecords, drainMeshPool, spanRecorder, spanNow, addSpan, fetchAsset, placedBox, InstancedBatch, INSTANCED_LOD_MAX_PIXEL_ERROR, dropPooledFor, DRAW_ARGS_BYTES, parkMesh, warmUpSceneWithCompletion, loadAll, warmUpScene, markStatic, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, pooledCapacity, pooledMesh, displacesVertices, DEFAULT_TARGET_FPS, STORAGE_PLAIN, argsWords, NO_LOCAL, SLOT_NONE, LOCAL_WORDS, storageAttribute, SOURCE_FLOOR, PLACEMENT_ROWS, DRAW_ARGS_WORDS, growBuffer, addRange, PLACEMENT_WORDS, VEC4_WORDS, composeSilencedByFreeze, worldSilencedByFreeze, isStatic, markEngineStatic, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, mergeByMaterial, VALIDATE_EVERY, TALLY_EVERY, nodes } from './chunk-FQURMC2F.js';
2
2
  import { GPUReadback } from './chunk-QWJEMUUT.js';
3
- import { baseGeometryOf, worldSphere, selectLodFor, projectedLodError, selectLodLevel, setLodBias, markEngineRenderHook, biasedLodDistance, isLodJoinProxy, setModelLodLayers, LOD_NEAR_PLANE, isEngineRenderHook, lodChainOf, DISCRETE_LOD_DEFAULT_HYSTERESIS } from './chunk-EFWZWLPY.js';
4
- import { readLaunchFlag, readLaunchValues, readLaunchValue } from './chunk-GYUZJQ7U.js';
3
+ import { baseGeometryOf, worldSphere, selectLodFor, projectedLodError, selectLodLevel, setLodBias, markEngineRenderHook, biasedLodDistance, isLodJoinProxy, setModelLodLayers, LOD_NEAR_PLANE, GEOMETRY_ASSET_KEY, isEngineRenderHook, lodChainOf, DISCRETE_LOD_DEFAULT_HYSTERESIS } from './chunk-OMGIYWW7.js';
4
+ import { readLaunchFlag, readLaunchValues, readLaunchValue } from './chunk-VQRPEOKY.js';
5
5
  import './chunk-XDTZ4QMO.js';
6
6
  import './chunk-VP43GIWW.js';
7
7
  import { createTerrainJobRunner, edgeWorldPoint } from './chunk-KIRUKTBQ.js';
@@ -1297,6 +1297,63 @@ function waterlineRadius(field, centre, level) {
1297
1297
  }
1298
1298
  return furthest;
1299
1299
  }
1300
+ function lakeDisc(field, lake, rings = 44, spokes = 88, packing = 1.7) {
1301
+ const reach = lakeReach(field, lake);
1302
+ if (!(reach > 0)) return void 0;
1303
+ const [cx = 0, cz = 0] = lake.at;
1304
+ const minX = field.origin.x - field.width / 2;
1305
+ const minZ = field.origin.z - field.depth / 2;
1306
+ const count3 = (rings - 1) * spokes + 1;
1307
+ const positions = new Float32Array(count3 * 2);
1308
+ const raw = new Float32Array(count3);
1309
+ for (let index = 0; index < count3; index += 1) {
1310
+ const ring = index === 0 ? 0 : Math.floor((index - 1) / spokes) + 1;
1311
+ const angle = (index - 1) % spokes / spokes * Math.PI * 2;
1312
+ const radius = index === 0 ? 0 : reach * (ring / (rings - 1)) ** packing;
1313
+ const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
1314
+ const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
1315
+ positions[index * 2] = x;
1316
+ positions[index * 2 + 1] = z;
1317
+ raw[index] = Math.max(0, lake.level - field.heightAt(x, z));
1318
+ }
1319
+ const depths = new Float32Array(count3);
1320
+ const stack = [0];
1321
+ depths[0] = raw[0];
1322
+ const visit = (index) => {
1323
+ if (raw[index] > 0 && depths[index] === 0) {
1324
+ depths[index] = raw[index];
1325
+ stack.push(index);
1326
+ }
1327
+ };
1328
+ while (stack.length > 0) {
1329
+ const index = stack.pop();
1330
+ if (index === 0) {
1331
+ for (let spoke2 = 0; spoke2 < spokes; spoke2 += 1) visit(1 + spoke2);
1332
+ continue;
1333
+ }
1334
+ const ring = Math.floor((index - 1) / spokes) + 1;
1335
+ const spoke = (index - 1) % spokes;
1336
+ const at = (r, s) => r === 0 ? 0 : 1 + (r - 1) * spokes + s;
1337
+ visit(at(ring, (spoke + 1) % spokes));
1338
+ visit(at(ring, (spoke + spokes - 1) % spokes));
1339
+ visit(at(ring - 1, spoke));
1340
+ if (ring + 1 < rings) visit(at(ring + 1, spoke));
1341
+ }
1342
+ return { x: cx, z: cz, reach, rings, spokes, packing, positions, depths };
1343
+ }
1344
+ function discReaches(disc, x, z) {
1345
+ const dx = x - disc.x;
1346
+ const dz = z - disc.z;
1347
+ const t = (Math.hypot(dx, dz) / disc.reach) ** (1 / disc.packing) * (disc.rings - 1);
1348
+ const ring = Math.min(disc.rings - 2, Math.floor(t));
1349
+ const turn = (Math.atan2(dz, dx) / (Math.PI * 2) + 1) % 1;
1350
+ const spoke = Math.floor(turn * disc.spokes) % disc.spokes;
1351
+ const at = (r, s) => r === 0 ? 0 : 1 + (r - 1) * disc.spokes + s;
1352
+ const next = (spoke + 1) % disc.spokes;
1353
+ return [at(ring, spoke), at(ring, next), at(ring + 1, spoke), at(ring + 1, next)].some(
1354
+ (index) => disc.depths[index] > 0
1355
+ );
1356
+ }
1300
1357
  function lakeReach(field, lake) {
1301
1358
  return Math.min(waterlineRadius(field, lake.at, lake.level) * lake.margin, lake.radius);
1302
1359
  }
@@ -1375,7 +1432,7 @@ var WaterBodies = class {
1375
1432
  let level = river === void 0 ? Number.NEGATIVE_INFINITY : river.ha + (river.hb - river.ha) * along;
1376
1433
  let kind = river === void 0 ? void 0 : "river";
1377
1434
  for (const pool of this.#pools)
1378
- if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level) {
1435
+ if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level && !isolated(pool, x, z)) {
1379
1436
  level = pool.level;
1380
1437
  river = void 0;
1381
1438
  kind = "lake";
@@ -1389,6 +1446,18 @@ var WaterBodies = class {
1389
1446
  return kind === void 0 ? void 0 : { kind, level, river };
1390
1447
  }
1391
1448
  };
1449
+ function isolated(pool, x, z) {
1450
+ const disc = pool.disc;
1451
+ if (disc === void 0 || discReaches(disc, x, z)) return false;
1452
+ const field = pool.field;
1453
+ const minX = field.origin.x - field.width / 2;
1454
+ const minZ = field.origin.z - field.depth / 2;
1455
+ const ground = field.heightAt(
1456
+ Math.max(minX, Math.min(minX + field.width, x)),
1457
+ Math.max(minZ, Math.min(minZ + field.depth, z))
1458
+ );
1459
+ return ground < pool.level;
1460
+ }
1392
1461
  function buildReaches(ribbon2, into) {
1393
1462
  const width = positive2(ribbon2.width, "ribbon width");
1394
1463
  const flow = finite3(ribbon2.flow, "ribbon flow");
@@ -1423,8 +1492,9 @@ function poolOf(field, lake) {
1423
1492
  const [x = 0, z = 0] = lake.at;
1424
1493
  finite3(x, "lake x");
1425
1494
  finite3(z, "lake z");
1426
- const radius = lakeReach(field, lake);
1427
- return { level: lake.level, radius2: radius * radius, x, z };
1495
+ const disc = lakeDisc(field, lake);
1496
+ const radius = disc?.reach ?? 0;
1497
+ return { level: lake.level, radius2: radius * radius, x, z, disc, field };
1428
1498
  }
1429
1499
  function indexReaches(reaches, cellSize) {
1430
1500
  const cells = /* @__PURE__ */ new Map();
@@ -1578,28 +1648,16 @@ function lakeSurfaceGeometry(lake, field, options = {}) {
1578
1648
  );
1579
1649
  if (!(packing > 0) || !(maxDepth > 0))
1580
1650
  throw new Error("TN_LAKE_SURFACE_INVALID: packing and maxDepth must be positive.");
1581
- const reach = lakeReach(field, lake);
1582
- if (!(reach > 0)) return void 0;
1583
- const [cx = 0, cz = 0] = lake.at;
1584
- const minX = field.origin.x - field.width / 2;
1585
- const minZ = field.origin.z - field.depth / 2;
1586
- const count3 = (rings - 1) * spokes + 1;
1651
+ const disc = lakeDisc(field, lake, rings, spokes, packing);
1652
+ if (disc === void 0) return void 0;
1653
+ const count3 = disc.depths.length;
1587
1654
  const positions = new Float32Array(count3 * 3);
1588
1655
  const depths = new Float32Array(count3);
1589
- const place = (index, radius, spoke) => {
1590
- const angle = spoke / spokes * Math.PI * 2;
1591
- const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
1592
- const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
1593
- positions[index * 3] = x;
1656
+ for (let index = 0; index < count3; index += 1) {
1657
+ positions[index * 3] = disc.positions[index * 2];
1594
1658
  positions[index * 3 + 1] = lake.level;
1595
- positions[index * 3 + 2] = z;
1596
- depths[index] = Math.min(maxDepth, Math.max(0, lake.level - field.heightAt(x, z)));
1597
- };
1598
- place(0, 0, 0);
1599
- for (let ring = 1; ring < rings; ring += 1) {
1600
- const radius = reach * (ring / (rings - 1)) ** packing;
1601
- for (let spoke = 0; spoke < spokes; spoke += 1)
1602
- place(1 + (ring - 1) * spokes + spoke, radius, spoke);
1659
+ positions[index * 3 + 2] = disc.positions[index * 2 + 1];
1660
+ depths[index] = Math.min(maxDepth, disc.depths[index]);
1603
1661
  }
1604
1662
  const depth = (index) => depths[index] ?? 0;
1605
1663
  const indices = [];
@@ -6627,11 +6685,24 @@ var TEXTURE_SLOTS = [
6627
6685
  "emissiveMap",
6628
6686
  "alphaMap"
6629
6687
  ];
6688
+ var unnamedIds = /* @__PURE__ */ new WeakMap();
6689
+ var nextUnnamedId = 0;
6690
+ function sourceId(texture3) {
6691
+ const uuid = texture3.source?.uuid;
6692
+ if (uuid !== void 0) return uuid;
6693
+ let id = unnamedIds.get(texture3);
6694
+ if (id === void 0) {
6695
+ id = nextUnnamedId++;
6696
+ unnamedIds.set(texture3, id);
6697
+ }
6698
+ return `#${String(id)}`;
6699
+ }
6630
6700
  function textureKey(texture3) {
6631
6701
  if (texture3 === null || texture3 === void 0) return "-";
6632
6702
  const image = texture3.image;
6633
6703
  const mips = texture3.mipmaps;
6634
- return `${texture3.name}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture3.flipY ? 1 : 0}`;
6704
+ const id = texture3.name !== "" ? texture3.name : `source:${sourceId(texture3)}`;
6705
+ return `${id}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture3.flipY ? 1 : 0}`;
6635
6706
  }
6636
6707
  function materialKey(material) {
6637
6708
  const fields = material;
@@ -8623,14 +8694,57 @@ function advanceTemporalLod(state, eye, now, lag = LOD_TEMPORAL_LAG) {
8623
8694
  const window = state.toTime - state.fromTime;
8624
8695
  state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
8625
8696
  }
8697
+ function lodFadedPast(distances, level, width) {
8698
+ const gate = level + 1;
8699
+ const at = distances[gate];
8700
+ if (at === void 0) return void 0;
8701
+ let span2 = Math.min(at * width, (at - distances[gate - 1]) * width);
8702
+ const next = distances[gate + 1];
8703
+ if (next !== void 0) span2 = Math.min(span2, (next - at) * width);
8704
+ return at + 0.75 * span2;
8705
+ }
8706
+ var lodCollapseArmed;
8707
+ var makeLodCollapseSwitch = () => uniform(1).setGroup(renderGroup);
8708
+ var lodCollapseSwitch;
8709
+ function lodCollapseNode() {
8710
+ lodCollapseArmed ??= readLaunchFlag({
8711
+ environment: "TN_LOD_COLLAPSE",
8712
+ query: "lodCollapse",
8713
+ global: "__tnLodCollapse"
8714
+ });
8715
+ if (!lodCollapseArmed) return void 0;
8716
+ lodCollapseSwitch ??= makeLodCollapseSwitch();
8717
+ return lodCollapseSwitch;
8718
+ }
8719
+ function syncLodCollapse() {
8720
+ if (lodCollapseSwitch === void 0) return;
8721
+ const live = Reflect.get(globalThis, "__tnLodCollapse");
8722
+ if (typeof live === "boolean") lodCollapseSwitch.value = live ? 1 : 0;
8723
+ }
8724
+ function collapseFadedVertices(material, on, gate) {
8725
+ let faded = on.greaterThan(0.5);
8726
+ for (const distance of gate.distances) faded = faded.and(distance.greaterThanEqual(gate.past));
8727
+ if (gate.publishedRanges) {
8728
+ const range = attribute("tnPublishedLodRange", "vec4");
8729
+ faded = faded.and(range.y.greaterThan(gate.lod));
8730
+ if (gate.clock !== void 0)
8731
+ faded = faded.and(
8732
+ range.z.lessThan(0).or(gate.clock.sub(range.w).div(LOD_TEMPORAL_LAG).greaterThanEqual(1)).or(range.z.sub(gate.lod).abs().greaterThanEqual(0.5))
8733
+ );
8734
+ }
8735
+ const position = material.positionNode ?? positionGeometry;
8736
+ material.positionNode = select(faded, vec3(0, 0, 0), position);
8737
+ }
8626
8738
  function worldLodMaterial(source, local, distances, level, width, eye, distanceBias, spatial, publishedRanges = false, clock, temporal, shadowFloor = 0) {
8627
8739
  const material = cloneLitMaterial(source);
8628
8740
  const inverse = uniform(local.clone().invert());
8629
8741
  const root = Fn(
8630
8742
  (_inputs, builder) => userInstanceMatrix(builder).mul(inverse).mul(vec4(0, 0, 0, 1)).xyz
8631
8743
  )();
8632
- const origin = varying(floor(root.mul(16).add(0.5)).div(16));
8633
- const distanceTo = (at) => (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
8744
+ const quantised = floor(root.mul(16).add(0.5)).div(16);
8745
+ const origin = varying(quantised);
8746
+ const distanceFrom = (point, at) => (spatial ? length(point.sub(at)) : length(point.xz.sub(at.xz))).mul(distanceBias);
8747
+ const distanceTo = (at) => distanceFrom(origin, at);
8634
8748
  const distance = distanceTo(eye);
8635
8749
  const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
8636
8750
  const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
@@ -8670,6 +8784,17 @@ function worldLodMaterial(source, local, distances, level, width, eye, distanceB
8670
8784
  }
8671
8785
  material.maskNode = material.maskNode ? material.maskNode.and(colour) : colour;
8672
8786
  material.maskShadowNode = material.maskShadowNode ? material.maskShadowNode.and(shadow) : shadow;
8787
+ const collapseOn = lodCollapseNode();
8788
+ if (collapseOn !== void 0)
8789
+ collapseFadedVertices(material, collapseOn, {
8790
+ past: uniform((lodFadedPast(distances, level, width) ?? 1e30) * 1.001),
8791
+ distances: (temporal === void 0 ? [eye] : [eye, temporal.from, temporal.to]).map(
8792
+ (at) => distanceFrom(quantised, at)
8793
+ ),
8794
+ lod,
8795
+ publishedRanges,
8796
+ clock
8797
+ });
8673
8798
  if (publishedRanges) material.userData.tnPublishedLodRange = true;
8674
8799
  return material;
8675
8800
  }
@@ -9699,7 +9824,7 @@ function renderableParts(model, surfaceFor) {
9699
9824
  if (object instanceof SkinnedMesh || !(object instanceof Mesh)) return;
9700
9825
  const material = Array.isArray(object.material) ? object.material[0] : object.material;
9701
9826
  if (object.geometry === void 0 || material === void 0) return;
9702
- const surface = surfaceFor(material);
9827
+ const surface = surfaceFor(material, object.geometry);
9703
9828
  parts.push({
9704
9829
  geometry: object.geometry,
9705
9830
  local: local.multiplyMatrices(rootInverse, object.matrixWorld).clone(),
@@ -9893,6 +10018,7 @@ var CellModels = class _CellModels {
9893
10018
  /** The screen-space error budget a synthesized level is switched at; see `autoLod`. */
9894
10019
  #autoLodMaxPixelError;
9895
10020
  #transparentScatter;
10021
+ #partMaterial;
9896
10022
  constructor(init, settings, host) {
9897
10023
  this.#host = host;
9898
10024
  this.#lodHysteresis = settings.lodHysteresis;
@@ -9906,6 +10032,7 @@ var CellModels = class _CellModels {
9906
10032
  this.#loader = init.assets ?? createAssetLoader();
9907
10033
  this.#ownsLoader = init.ownsAssets ?? init.assets === void 0;
9908
10034
  this.#loadModel = init.loadModel;
10035
+ this.#partMaterial = init.partMaterial;
9909
10036
  this.#limiter = new ModelLoadLimiter(
9910
10037
  positiveInteger(init.concurrency ?? WORLD_LOAD_CONCURRENCY, "concurrency")
9911
10038
  );
@@ -10029,7 +10156,15 @@ var CellModels = class _CellModels {
10029
10156
  /** One loaded model's drawable parts, or `undefined` when it carries nothing to draw. */
10030
10157
  #partsOf(model) {
10031
10158
  if (model === void 0) return void 0;
10032
- const parts = renderableParts(model, (material) => this.#surfaceFor(material));
10159
+ let parts;
10160
+ try {
10161
+ parts = renderableParts(model, (material, geometry) => this.#surfaceFor(material, geometry));
10162
+ } catch (error) {
10163
+ this.#host.setFailures(this.#host.failures() + 1);
10164
+ this.#host.reportCellFailure("asset", model.name || "model", [], error);
10165
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
10166
+ return void 0;
10167
+ }
10033
10168
  if (parts.length === 0) {
10034
10169
  this.#host.setFailures(this.#host.failures() + 1);
10035
10170
  this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
@@ -10206,8 +10341,12 @@ var CellModels = class _CellModels {
10206
10341
  * canonical one (converted to a cutout when it is transparent scatter), and every later material
10207
10342
  * with the same content is released on arrival and draws with it instead.
10208
10343
  */
10209
- #surfaceFor(source) {
10210
- const key = this.#preserveAuthoredParts ? source.uuid : materialKey(source);
10344
+ #surfaceFor(source, geometry) {
10345
+ const game = this.#partMaterial?.(source, geometry);
10346
+ if (game !== void 0 && game?.isMaterial !== true)
10347
+ throw new Error("WorldCells partMaterial must return a Material.");
10348
+ const hooked = game !== void 0 && game !== source;
10349
+ const key = hooked ? `part:${game.uuid}` : this.#preserveAuthoredParts ? source.uuid : materialKey(source);
10211
10350
  const shared2 = this.#surfaces.get(key);
10212
10351
  if (shared2 !== void 0) {
10213
10352
  shared2.users += 1;
@@ -10215,8 +10354,9 @@ var CellModels = class _CellModels {
10215
10354
  this.#host.setFailures(this.#host.failures() + 1);
10216
10355
  return { key, material: shared2.material };
10217
10356
  }
10218
- const drawn = scatterMaterial(source, this.#transparentScatter);
10219
- this.#surfaces.set(key, { material: drawn.material, owned: drawn.owned, users: 1 });
10357
+ const drawn = scatterMaterial(hooked ? game : source, this.#transparentScatter);
10358
+ const owned = hooked ? [source, ...drawn.owned] : drawn.owned;
10359
+ this.#surfaces.set(key, { material: drawn.material, owned, users: 1 });
10220
10360
  return { key, material: drawn.material };
10221
10361
  }
10222
10362
  /** One user gone; the last one tears the shared surface down. Returns teardowns that threw. */
@@ -10609,7 +10749,7 @@ function freshMeshFor(old, geometry, count3) {
10609
10749
  next.matrixWorld.copy(old.matrixWorld);
10610
10750
  next.matrixAutoUpdate = old.matrixAutoUpdate || composeSilencedByFreeze(old);
10611
10751
  next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
10612
- if (isStatic(old)) markStatic(next);
10752
+ if (isStatic(old)) markEngineStatic(next);
10613
10753
  return next;
10614
10754
  }
10615
10755
  function followCluster(follow, minX, minZ, cellSize, cellsPerCluster) {
@@ -13427,6 +13567,7 @@ var CellGpuDress = class {
13427
13567
  updateLodEye(x, y, z) {
13428
13568
  this.#lodEye.value.set(x, y, z);
13429
13569
  this.#lodClock.value = (performance.now() - this.#lodClockOrigin) / 1e3;
13570
+ syncLodCollapse();
13430
13571
  if (this.#host.lodTransition() !== "temporal") return;
13431
13572
  advanceTemporalLod(this.#temporalLod, this.#lodEye.value, this.#lodClock.value);
13432
13573
  this.#lodAlpha.value = this.#temporalLod.alpha;
@@ -13469,7 +13610,7 @@ var CellGpuDress = class {
13469
13610
  dressMesh(shared2, receiveShadow) {
13470
13611
  const mesh = shared2.mesh;
13471
13612
  const role = shared2.role;
13472
- markStatic(mesh);
13613
+ markEngineStatic(mesh);
13473
13614
  if (role !== "main") {
13474
13615
  mesh.layers.set(
13475
13616
  role === "cluster" ? VIRTUAL_SHADOW_CASTER_LAYER : role === "key" ? VIRTUAL_SHADOW_KEY_LAYER : shared2.smallCaster ? VIRTUAL_SHADOW_SMALL_CASTER_LAYER : VIRTUAL_SHADOW_WIDE_CASTER_LAYER
@@ -13953,6 +14094,8 @@ var SharedBatch = class {
13953
14094
  view.boundingSphere = source.boundingSphere;
13954
14095
  view.setDrawRange(source.drawRange.start, source.drawRange.count);
13955
14096
  view.userData.tnPublishedLodRangeView = true;
14097
+ const stamp = source.userData[GEOMETRY_ASSET_KEY];
14098
+ if (stamp !== void 0) view.userData[GEOMETRY_ASSET_KEY] = stamp;
13956
14099
  const ranges = new InstancedBufferAttribute(
13957
14100
  new Float32Array(capacity * LOD_RANGE_STRIDE),
13958
14101
  LOD_RANGE_STRIDE
@@ -252,7 +252,7 @@ void main() {
252
252
  }`,$e={meshphysical_vert:yk,meshphysical_frag:Sk},ae={common:{diffuse:{value:new ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ce}},envmap:{envMap:{value:null},envMapRotation:{value:new Ce},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ce}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ce}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ce},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ce},normalScale:{value:new mn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ce},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ce}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ce}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ce}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:[]},probesMin:{value:[]},probesMax:{value:[]},probesResolution:{value:[]}},points:{diffuse:{value:new ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0},uvTransform:{value:new Ce}},sprite:{diffuse:{value:new ft(16777215)},opacity:{value:1},center:{value:new mn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}}},VE={basic:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.fog])},lambert:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},envMapIntensity:{value:1}}])},phong:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},specular:{value:new ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}])},standard:{uniforms:Nt([ae.common,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.roughnessmap,ae.metalnessmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}])},toon:{uniforms:Nt([ae.common,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.gradientmap,ae.fog,ae.lights,{emissive:{value:new ft(0)}}])},matcap:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,{matcap:{value:null}}])},points:{uniforms:Nt([ae.points,ae.fog])},dashed:{uniforms:Nt([ae.common,ae.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}])},depth:{uniforms:Nt([ae.common,ae.displacementmap])},normal:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,{opacity:{value:1}}])},sprite:{uniforms:Nt([ae.sprite,ae.fog])},background:{uniforms:{uvTransform:{value:new Ce}}},backgroundCube:{uniforms:{backgroundRotation:{value:new Ce}}},distance:{uniforms:Nt([ae.common,ae.displacementmap,{referencePosition:{value:new qe},nearDistance:{value:1},farDistance:{value:1e3}}])},shadow:{uniforms:Nt([ae.lights,ae.fog,{color:{value:new ft(0)},opacity:{value:1}}])}};VE.physical={uniforms:Nt([VE.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ce},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ce},clearcoatNormalScale:{value:new mn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ce},diffuseRoughness:{value:0},diffuseRoughnessMap:{value:null},diffuseRoughnessMapTransform:{value:new Ce},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ce},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ce},sheen:{value:0},sheenColor:{value:new ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ce},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ce},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ce},transmissionSamplerSize:{value:new mn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ce},attenuationDistance:{value:0},attenuationColor:{value:new ft(0)},specularColor:{value:new ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ce},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ce},anisotropyVector:{value:new mn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ce}}]),vertexShader:$e.meshphysical_vert,fragmentShader:$e.meshphysical_frag};var Ik=new Ce;Ik.set(-1,0,0,0,1,0,0,0,1);var Ck=new Ce;Ck.set(-1,0,0,0,1,0,0,0,1);var Pk=t=>{let e=t.toLowerCase();if(e==="left")return t==="LEFT"?"RIGHT":"Right";if(e==="right")return t==="RIGHT"?"LEFT":"Left"};function jE(t){let e=t.replace(/left|right/giu,i=>Pk(i)??i);if(e!==t)return e;let r=t.replace(/(^|[._\s-])([lrLR])(?=$|[._\s-]|\d)/gu,(i,n,s)=>`${n}${s==="L"?"R":s==="R"?"L":s==="l"?"r":"l"}`);return r===t?void 0:r}function GE(t,e){let r=[],i=[];return t.forEach((n,s)=>{let o=e(n);o!==void 0&&(r.push(s),i.push(o));}),{source:r,times:i}}function HE(t,e){let r=new qe(t[0]??0,t[1]??0,t[2]??0).applyQuaternion(new Pt(e[0]??0,e[1]??0,e[2]??0,e[3]??1).invert());return [r.x,r.y,r.z]}var Nk=()=>new Jt().registerExtensions(Qt);function gn(t,e,r){let{times:i,values:n}=t,s=i.length,o=t.interpolation==="CUBICSPLINE",a=o?e*3:e,c=(_,y)=>n[_*a+(o?e:0)+y]??0,l=i[0]??0,u=i[s-1]??l,d=_=>Array.from({length:e},(y,R)=>c(_,R));if(s===0)return new Array(e).fill(0);if(r<=l)return d(0);if(r>=u)return d(s-1);let f=1;for(;f<s&&(i[f]??0)<r;)f+=1;let p=f-1,g=i[p]??0,m=i[f]??g,S=d(p);if(t.interpolation==="STEP"||m-g<=1e-9)return S;let h=(r-g)/(m-g),v=d(f);return S.map((_,y)=>_+((v[y]??0)-_)*h)}function Ok(t,e,r){let i=e.get(t.getName()),n=[...t.getTranslation()],s=[...t.getRotation()],o=[...t.getScale()],a=i?.get("translation");a!==void 0&&n.splice(0,3,...gn(a,3,r));let c=i?.get("rotation");c!==void 0&&s.splice(0,4,...gn(c,4,r));let l=i?.get("scale");return l!==void 0&&o.splice(0,3,...gn(l,3,r)),{matrix:new nn().compose(new qe(n[0]??0,n[1]??0,n[2]??0),new Pt(s[0]??0,s[1]??0,s[2]??0,s[3]??1),new qe(o[0]??1,o[1]??1,o[2]??1)),translation:n}}function qE(t,e){let r=0;for(let i of e.get(t.getName())?.values()??[])r=Math.max(r,i.times.at(-1)??0);for(let i of t.listChildren())r=Math.max(r,qE(i,e));return r}async function jh(t,e,r=30){return v0(await Nk().read(t),e,r)}function v0(t,e,r=30){let i=t.getRoot().listAnimations().find(p=>p.getName()===e);if(i===void 0){let p=t.getRoot().listAnimations().map(g=>g.getName());throw new Error(`The GLB has no clip '${e}'. It carries: ${p.length===0?"none":p.join(", ")}.`)}let n=new Map;for(let p of i.listChannels()){let g=p.getTargetNode(),m=p.getSampler(),S=p.getTargetPath();if(g===null||m===null||S===null)continue;let h=m.getInput()?.getArray(),v=m.getOutput()?.getArray();if(h==null||v===null||v===void 0)continue;let _=n.get(g.getName())??new Map;_.set(S,{interpolation:m.getInterpolation(),times:h,values:v}),n.set(g.getName(),_);}let s=t.getRoot().listScenes().flatMap(p=>p.listChildren()),o=s.reduce((p,g)=>Math.max(p,qE(g,n)),0),a=t.getRoot().listSkins().flatMap(p=>p.listJoints()).map(p=>p.getName()),c=new Set(a.length>0?a:t.getRoot().listNodes().map(p=>p.getName()).filter(p=>p.length>0)),l=[...c],u={},d=Math.max(1,Math.round(o*r)),f=[];for(let p=0;p<=d;p+=1){let g=Math.min(o,p/r),m={},S={},h={},v=(_,y,R)=>{let T=y.clone().multiply(Ok(_,n,g).matrix),b=_.getName();if(c.has(b)){let E=new qe().setFromMatrixPosition(T),M=new Pt().setFromRotationMatrix(T),N=new Pt().setFromRotationMatrix(y);m[b]=[E.x,E.y,E.z],S[b]=[M.x,M.y,M.z,M.w],h[b]=[N.x,N.y,N.z,N.w],R!==void 0&&c.has(R)&&(u[b]=R);}for(let E of _.listChildren())v(E,T,b);};for(let _ of s)v(_,new nn);f.push({parents:h,positions:m,rotations:S,time:g});}return {bones:l,duration:o,fps:r,frames:f,parentsOf:u}}var zk=()=>new Jt().registerExtensions(Qt),Gh=t=>t==="rotation"?4:3;function xi(t){let e=t.getSampler(),r=e?.getInput()?.getArray(),i=e?.getOutput()?.getArray();if(!(e===null||r===null||r===void 0||i===null||i===void 0))return {interpolation:e.getInterpolation(),times:r,values:i}}function Fa(t,e,r,i,n){let s=e.getSampler();if(s===null)return;let o=t.getRoot().listBuffers()[0]??t.createBuffer(),a=t.createAccessor(`${e.getTargetNode()?.getName()}.time`).setType("SCALAR").setArray(new Float32Array(r)).setBuffer(o),c=t.createAccessor(`${e.getTargetNode()?.getName()}.${e.getTargetPath()}`).setType(n===4?"VEC4":"VEC3").setArray(new Float32Array(i)).setBuffer(o);s.setInput(a).setOutput(c).setInterpolation("LINEAR");}function WE(t,e,r,i){for(let n of e.listChannels()){let s=xi(n);if(s===void 0)continue;let o=n.getTargetPath()??"translation",a=Gh(o),c=s.interpolation==="CUBICSPLINE",l=c?a*3:a,{source:u,times:d}=GE([...s.times],r);if(d.length===0)throw new Error(`'${e.getName()}' keeps no keyframes in that window; the edit would leave an empty clip.`);let f=[];for(let p of u)for(let g=0;g<l;g+=1)f.push(s.values[p*l+g]??0);if(i!==void 0){let p=gn(s,a,0),g=i,m=d.findIndex(v=>v>g),S=m===-1?d.length:m;d.splice(S,0,g);let h=c?Array.from({length:3*a},(v,_)=>_>=a&&_<a*2?p[_-a]??0:0):p;f.splice(S*l,0,...h);}Fa(t,n,d,f,a),c?n.getSampler()?.setInterpolation("CUBICSPLINE"):s.interpolation==="STEP"&&n.getSampler()?.setInterpolation("STEP");}}function $k(t){let e=0;for(let r of t.listChannels())e=Math.max(e,xi(r)?.times.at(-1)??0);return e}function Dk(t,e,r,i){for(let n of e.listChannels()){let s=xi(n);if(s===void 0)continue;let o=Gh(n.getTargetPath()??"translation"),a=s.interpolation==="CUBICSPLINE",c=a?o*3:o,u=[...gn(s,o,r),...a?new Array(o).fill(0):[]],d=[...gn(s,o,i),...a?new Array(o).fill(0):[]],f=[0],p=[...u];for(let g=0;g<s.times.length;g+=1){let m=s.times[g]??0;if(!(m<=r||m>=i)){f.push(m-r);for(let S=0;S<c;S+=1)p.push(s.values[g*c+S]??0);}}f.push(i-r),p.push(...d),Fa(t,n,f,p,o),a&&n.getSampler()?.setInterpolation("CUBICSPLINE");}}function Lk(t,e,r){let i=e.listChannels(),n=0;for(let a of i){let c=xi(a);c!==void 0&&(n=Math.max(n,c.times.at(-1)??0));}let s=Math.max(1,Math.round(n*r)),o=Array.from({length:s+1},(a,c)=>Math.min(n,c/r));for(let a of i){let c=xi(a);if(c===void 0)continue;let l=Gh(a.getTargetPath()??"translation"),u=o.flatMap(d=>gn(c,l,d));Fa(t,a,o,u,l);}}function kk(t,e){let r=new Map(t.getRoot().listNodes().map(i=>[i.getName(),i]));for(let i of e.listChannels()){let n=i.getTargetNode(),s=xi(i);if(n===null||s===void 0)continue;let o=i.getTargetPath()??"translation",a=Gh(o),c=[];for(let d=0;d+a<=s.values.length;d+=a){let f=Array.from({length:a},(p,g)=>s.values[d+g]??0);o==="translation"&&(f[0]=-(f[0]??0)),o==="rotation"&&(f[1]=-(f[1]??0),f[2]=-(f[2]??0)),c.push(...f);}Fa(t,i,[...s.times],c,a);let l=jE(n.getName()),u=l===void 0?void 0:r.get(l);u!==void 0&&i.setTargetNode(u);}}function Uk(t,e,r){let i=v0(t,e.getName()),n=r.feet.length>0?r.feet:i.bones.filter(s=>/foot/iu.test(s));if(n.length===0)throw new Error("No foot bones to lock: name them with 'feet'.");for(let s of n){let o=i.frames.map(g=>g.positions[s]?.[1]??0),a=Math.min(...o),c=e.listChannels().find(g=>g.getTargetNode()?.getName()===s&&g.getTargetPath()==="translation");if(c===void 0)continue;let l=xi(c);if(l===void 0)continue;let u=[],d=[],f,p=false;i.frames.forEach((g,m)=>{let S=g.positions[s];if(S===void 0)return;(S[1]??0)<=a+r.contact?(f??=S,p=true):(p=false,f=void 0);let v=p&&f!==void 0?[(f[0]??0)-(S[0]??0),0,(f[2]??0)-(S[2]??0)]:[0,0,0],_=HE(v,g.parents[s]??[0,0,0,1]);u.push(g.time),d.push((gn(l,3,g.time)[0]??0)+_[0],(gn(l,3,g.time)[1]??0)+_[1],(gn(l,3,g.time)[2]??0)+_[2]);}),Fa(t,c,u,d,3);}}function Fk(t,e,r){switch(r.kind){case "trim":{if(r.end<=r.start)throw new Error("trim needs an end after its start.");let i=$k(e);if(r.start>=i||r.end>i+1e-6)throw new Error(`trim asks for ${r.start}\u2013${r.end}s but '${e.getName()}' is ${i}s long.`);Dk(t,e,r.start,r.end);return}case "retime":if(!(r.speed>0))throw new Error("retime needs a speed above zero.");WE(t,e,i=>i/r.speed);return;case "loop-point":WE(t,e,i=>i<=r.time?i:void 0,r.time);return;case "resample":if(!(r.fps>0))throw new Error("resample needs an fps above zero.");Lk(t,e,r.fps);return;case "mirror":kk(t,e);return;case "foot-lock":Uk(t,e,r);return}}function KE(t,e,r){let i=t.getRoot().listAnimations().filter(n=>n.getName()===e);if(i.length===0)throw new Error(`The GLB has no clip '${e}' to edit.`);for(let n of r)for(let s of i)Fk(t,s,n);}async function ZE(t){return zk().read(t)}function Bk(t){let e=new Map;for(let r of t)r.op==="modify"&&e.set(r.clip,[...e.get(r.clip)??[],r.edit]);return e}async function XE(t,e){let r=await ZE(t.host),i=t.ops.some(o=>o.op==="attach")?await Iy(r,t):void 0,n=Bk(t.ops);for(let[o,a]of n)KE(r,o,a);return await new Jt().registerExtensions(Qt).write(e,r),{clips:i?.clips??[],edits:[...n.values()].reduce((o,a)=>o+a.length,0),file:e,modified:[...n.keys()]}}var ks=Object.freeze({contact:.03,jitter:.05,penetration:.01,seam:5,skate:.02,stretch:.02}),y0=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[1]??0)-(e[1]??0),(t[2]??0)-(e[2]??0)),Vk=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[2]??0)-(e[2]??0));function jk(t,e){let r=n=>Math.hypot(n[0]??0,n[1]??0,n[2]??0,n[3]??1)||1,i=((t[0]??0)*(e[0]??0)+(t[1]??0)*(e[1]??0)+(t[2]??0)*(e[2]??0)+(t[3]??1)*(e[3]??1))/(r(t)*r(e));return 2*Math.acos(Math.min(1,Math.abs(i)))*180/Math.PI}function S0(t,e=2){let r=[],i,n;for(let s of t)(i===void 0||n===void 0||s-n>e)&&(i!==void 0&&n!==void 0&&r.push({from:i,to:n}),i=s),n=s;return i!==void 0&&n!==void 0&&r.push({from:i,to:n}),r}function Gk(t,e,r,i){let n=[];for(let s of e){let o=t.frames.map(p=>p.positions[s]?.[1]??0),a=Math.min(...o),c=t.frames.map((p,g)=>({index:g,frame:p})).filter(({frame:p})=>(p.positions[s]?.[1]??0)<=a+i),l,u,d=()=>{u!==void 0&&(u.worst>r&&n.push({bone:s,detail:`the planted foot slid ${(u.worst*1e3).toFixed(0)} mm between frames ${u.first} and ${u.last}`,fromFrame:u.first,fromTime:t.frames[u.first]?.time??0,kind:"foot-skate",limit:r,measured:u.worst,toFrame:u.last,toTime:t.frames[u.last]?.time??0}),u=void 0,l=void 0);},f;for(let{index:p,frame:g}of c){f!==void 0&&p-f>1&&d(),l??=g;let m=Vk(g.positions[s]??[0,0,0],l.positions[s]??[0,0,0]);u??={first:p,last:p,worst:0},u.last=p,u.worst=Math.max(u.worst,m),f=p;}d();}return n}function Hk(t,e,r){let i=[];for(let n of e){let s=t.frames.map((o,a)=>({index:a,y:o.positions[n]?.[1]})).filter(({y:o})=>o!==void 0&&o<-r);for(let o of S0(s.map(({index:a})=>a))){let a=s.filter(({index:c})=>c>=o.from&&c<=o.to).reduce((c,{y:l})=>Math.min(c,l??0),0);i.push({bone:n,detail:`reaches ${(Math.abs(a)*1e3).toFixed(0)} mm below the floor`,fromFrame:o.from,fromTime:t.frames[o.from]?.time??0,kind:"ground-penetration",limit:r,measured:Math.abs(a),toFrame:o.to,toTime:t.frames[o.to]?.time??0});}}return i}function qk(t,e){let r=t.frames[0],i=t.frames.at(-1);if(r===void 0||i===void 0||t.frames.length<3)return [];let n,s=0;for(let o of t.bones){let a=r.rotations[o],c=i.rotations[o];if(a===void 0||c===void 0)continue;let l=jk(a,c);l<=e||(s+=1,(n===void 0||l>n.angle)&&(n={angle:l,bone:o}));}return n===void 0?[]:[{bone:n.bone,detail:`the clip ends ${n.angle.toFixed(1)}\xB0 from where it started${s>1?`, and ${s-1} more bones with it`:""}`,fromFrame:0,fromTime:r.time,kind:"loop-seam",limit:e,measured:n.angle,toFrame:t.frames.length-1,toTime:i.time}]}function Wk(t,e,r){let i=[];for(let n of e){let s=t.frames.map(l=>l.positions[n]),o=[],a=new Map,c=0;for(let l=1;l<s.length-1;l+=1){let u=s[l-1],d=s[l],f=s[l+1];if(u===void 0||d===void 0||f===void 0)continue;let p=y0([2*(d[0]??0)-(u[0]??0),2*(d[1]??0)-(u[1]??0),2*(d[2]??0)-(u[2]??0)],[f[0]??0,f[1]??0,f[2]??0]);p>r&&(o.push(l),a.set(l,Math.max(a.get(l)??0,p)),c=Math.max(c,p));}for(let l of S0(o.map(u=>u)))i.push({bone:n,detail:`a frame-direction spike of ${((a.get(l.from)??c)*1e3).toFixed(0)} mm`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"jitter",limit:r,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}function Kk(t,e){let r=t.frames[0];if(r===void 0)return [];let i=[];for(let[n,s]of Object.entries(t.parentsOf)){let o=y0(r.positions[n]??[0,0,0],r.positions[s]??[0,0,0]);if(o<=1e-6)continue;let a=t.frames.map((l,u)=>({index:u,ratio:Math.abs(y0(l.positions[n]??[0,0,0],l.positions[s]??[0,0,0])/o-1)})).filter(({ratio:l})=>l>e);if(a.length===0)continue;let c=a.reduce((l,{ratio:u})=>Math.max(l,u),0);for(let l of S0(a.map(({index:u})=>u)))i.push({bone:n,detail:`distance to its parent '${s}' changes by ${(c*100).toFixed(1)}%`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"bone-stretch",limit:e,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}var Zk=new Set(["left-foot","right-foot"]);async function JE(t,e,r={}){let i=r.scale??1,n={contact:(r.thresholds?.contact??ks.contact)/i,jitter:(r.thresholds?.jitter??ks.jitter)/i,penetration:(r.thresholds?.penetration??ks.penetration)/i,seam:r.thresholds?.seam??ks.seam,skate:(r.thresholds?.skate??ks.skate)/i,stretch:r.thresholds?.stretch??ks.stretch},s=await jh(t,e,r.fps??30),o=Sh(s.bones).filter(c=>Zk.has(c.id)).map(c=>c.node),a=[...Gk(s,o,n.skate,n.contact),...Hk(s,s.bones,n.penetration),...qk(s,n.seam),...Wk(s,s.bones,n.jitter),...Kk(s,n.stretch)];return {bones:s.bones.length,clip:e,defects:a,duration:s.duration,file:t,fps:s.fps,frames:s.frames.length,passed:a.length===0,scale:i,thresholds:n}}var Jk=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let i=0;i<8;i+=1)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0;}return t})();function Yk(t){let e=4294967295;for(let r of t)e=(Jk[(e^r)&255]??0)^e>>>8;return (e^4294967295)>>>0}function x0(t,e){let r=Buffer.alloc(4);r.writeUInt32BE(e.length,0);let i=Buffer.concat([Buffer.from(t,"ascii"),Buffer.from(e)]),n=Buffer.alloc(4);return n.writeUInt32BE(Yk(i),0),Buffer.concat([r,i,n])}function YE(t,e,r){let i=Buffer.alloc(13);i.writeUInt32BE(t,0),i.writeUInt32BE(e,4),i[8]=8,i[9]=6,i[10]=0,i[11]=0,i[12]=0;let n=t*4,s=Buffer.alloc((n+1)*e);for(let o=0;o<e;o+=1)s[o*(n+1)]=0,Buffer.from(r.buffer,r.byteOffset+o*n,n).copy(s,o*(n+1)+1);return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),x0("IHDR",i),x0("IDAT",deflateSync(s,{level:9})),x0("IEND",new Uint8Array)])}var b0=[9,13,11],tU=[183,243,74],nU=[39,48,44];function ew(t,e,r,i){let[n,s]=e,[o,a]=r,c=Math.max(1,Math.ceil(Math.max(Math.abs(o-n),Math.abs(a-s))));for(let l=0;l<=c;l+=1){let u=Math.round(n+(o-n)*l/c),d=Math.round(s+(a-s)*l/c);if(u<0||d<0||u>=t.width||d>=t.height)continue;let f=t.width*d+u<<2;t.data[f]=i[0]??0,t.data[f+1]=i[1]??0,t.data[f+2]=i[2]??0,t.data[f+3]=255;}}async function tw(t){let e=await jh(t.file,t.clip,t.fps??30),r=Math.max(1,t.columns??6),i=Math.max(48,t.height??160),n=Math.min(r,e.frames.length),s=Math.max(1,Math.floor((e.frames.length-1)/Math.max(1,n-1))),o=Array.from({length:n},(_,y)=>Math.min(e.frames.length-1,y*s)),a={data:new Uint8Array(i*n*i*4),height:i,width:i*n};for(let _=0;_<a.width*a.height;_+=1){let y=_<<2;a.data[y]=b0[0],a.data[y+1]=b0[1],a.data[y+2]=b0[2],a.data[y+3]=255;}let c=o.flatMap(_=>e.bones.map(y=>e.frames[_]?.positions[y]).filter(y=>y!==void 0)),l=c.map(_=>_[0]),u=c.map(_=>_[1]),d=Math.min(...l,0),f=Math.max(...l,1),p=Math.min(...u,0),g=Math.max(...u,1),m=Math.max(1e-6,Math.max(f-d,g-p)),S=i*.12,h=(_,y,R)=>[Math.round(R*i+S+(_-d)/m*(i-S*2)),Math.round(i-S-(y-p)/m*(i-S*2))];o.forEach((_,y)=>{let R=e.frames[_];if(R!==void 0){ew(a,h(d,p,y),h(f,p,y),nU);for(let T of e.bones){let b=R.positions[T];b!==void 0&&ew(a,h(b[0],0,y),h(b[0],b[1],y),tU);}}});let v=YE(a.width,a.height,a.data);return await mkdir(Gr.dirname(Gr.resolve(t.output)),{recursive:true}),await writeFile(t.output,v),{bytes:v.length,columns:n,frames:e.frames.length}}var rU=String.raw`
253
253
  :root{color-scheme:dark;font-family:"IBM Plex Mono","Azeret Mono",ui-monospace,monospace;background:#080b0a;color:#dce4de;--line:#27302c;--line2:#38433e;--panel:#111613;--panel2:#171d1a;--acid:#b7f34a;--cyan:#68d9d0;--muted:#77837c;--red:#ff705d}*{box-sizing:border-box}body{margin:0;overflow:hidden;background:#080b0a}button{cursor:pointer}.lab{height:100vh;display:grid;grid-template-rows:50px 1fr 26px}.bar{display:flex;align-items:center;gap:14px;padding:0 14px;border-bottom:1px solid var(--line);background:#0d120f}.brand{font:800 13px sans-serif;letter-spacing:.18em}.brand b{display:inline-grid;place-items:center;width:24px;height:24px;margin-right:9px;background:var(--acid);color:#101808}.bar small,.status{color:var(--muted)}.grow{flex:1}.bar button{border:1px solid #789e3f;border-radius:2px;background:var(--acid);color:#111908;padding:8px 14px;font:800 10px inherit}.body{min-height:0;display:grid;grid-template-columns:230px minmax(0,1fr) 285px}.side{overflow:auto;background:var(--panel)}.left{border-right:1px solid var(--line)}.right{border-left:1px solid var(--line)}.section{padding:13px;border-bottom:1px solid var(--line)}h2{margin:0 0 10px;color:var(--muted);font-size:9px;letter-spacing:.16em;text-transform:uppercase}label{display:grid;gap:5px;margin-bottom:10px;color:#91a097;font-size:9px;text-transform:uppercase}select,input{width:100%;border:1px solid var(--line);border-radius:2px;background:#090d0b;color:#dce4de;padding:8px;font:10px inherit;outline:none}select:focus,input:focus{border-color:var(--acid)}input:disabled{opacity:.38}.workspace{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(280px,1fr) 224px;background:#090d0b}.viewport{position:relative;min-width:0;min-height:0}.viewport canvas{display:block;width:100%;height:100%}.title{position:absolute;top:18px;left:18px;pointer-events:none;font:800 23px sans-serif}.title small{display:block;margin-top:6px;color:var(--acid);font:9px ui-monospace;letter-spacing:.14em}.tools{position:absolute;bottom:16px;left:50%;display:flex;transform:translateX(-50%);border:1px solid var(--line2);background:#090d0be8}.tools button,.preset button{border:0;background:none;color:var(--muted);padding:9px 15px;font:9px inherit;text-transform:uppercase}.tools button.on{background:#263328;color:var(--acid)}.tools button:disabled{opacity:.28;cursor:not-allowed}.release-note{position:absolute;top:18px;right:18px;padding:7px 10px;border:1px solid #8b493d;background:#2b1713d9;color:#ff9b86;font-size:9px;letter-spacing:.13em}.landmarks{display:grid;gap:5px}.landmark{display:grid;grid-template-columns:8px 1fr auto;gap:8px;align-items:center;width:100%;padding:8px;border:1px solid transparent;border-radius:2px;background:#0c110f;color:var(--muted);font:10px inherit;text-align:left}.landmark.on{border-color:#668c34;color:#dce4de}.landmark i{width:6px;height:6px;border-radius:50%;background:#71b9ff}.landmark.detected i{background:var(--acid)}.landmark small{font-size:8px;color:#69756f}.axis{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}.axis label{margin:0}.preset{display:grid;grid-template-columns:repeat(4,1fr);margin-top:8px}.preset button{padding:7px 2px;border:1px solid var(--line)}.wide,.editor-bar button,.segmented button{border:1px solid var(--line2);border-radius:2px;background:#1a211d;color:#dce4de;padding:8px;font:10px inherit}.wide{width:100%}.secondary{color:var(--muted)!important;background:#0d1210!important}.segmented{display:grid;grid-template-columns:1fr 1fr;gap:3px}.segmented button.on{border-color:var(--acid);color:var(--acid);background:#243021}.segmented button.danger.on{border-color:var(--red);color:#ff9b86;background:#321a16}.hint{margin:8px 0 0;color:var(--muted);font-size:9px;line-height:1.5}.status{display:flex;justify-content:space-between;align-items:center;padding:0 12px;border-top:1px solid var(--line);font-size:9px}.status b{color:var(--acid)}.error{position:absolute;top:18px;right:18px;max-width:360px;padding:10px;border:1px solid #81452f;background:#321a12;color:#ffb08a;font-size:10px}.saved{color:var(--acid);font-size:9px}.dope-editor{min-width:0;border-top:1px solid #46504b;background:#101512;box-shadow:0 -12px 30px #0008}.editor-bar{height:44px;display:flex;align-items:center;gap:7px;padding:6px 9px;border-bottom:1px solid var(--line2);background:#171c19}.editor-bar select{width:180px;padding:7px}.editor-bar button{white-space:nowrap;padding:7px 10px}.editor-bar button:disabled{opacity:.3;cursor:not-allowed}.editor-bar .transport{width:34px;border-color:#738d47;color:var(--acid);font-size:13px}.timecode{min-width:90px;color:#e1e7e3;font-size:11px;letter-spacing:.08em}.timecode i{color:var(--muted);font-style:normal}.compact{display:flex}.sheet{position:relative;height:179px;display:grid;grid-template-columns:132px 1fr;grid-template-rows:27px repeat(4,38px);overflow:hidden;background:repeating-linear-gradient(90deg,transparent 0,transparent calc(10% - 1px),#252d29 calc(10% - 1px),#252d29 10%)}.ruler-label{grid-column:1;grid-row:1}.ruler{position:relative;grid-column:2;grid-row:1;border-bottom:1px solid var(--line2);background:#0c100e}.ruler span{position:absolute;bottom:5px;transform:translateX(-50%);color:#68736d;font-size:8px}.lane-row{display:contents}.lane-label{z-index:3;display:flex;align-items:center;gap:8px;padding-left:13px;border-right:1px solid var(--line2);border-bottom:1px solid #222a26;background:#151a17;color:#87938c;font-size:9px;letter-spacing:.1em}.lane-label i{width:6px;height:6px;border:1px solid var(--cyan);transform:rotate(45deg)}.lane-track{position:relative;border-bottom:1px solid #222a26;background:#0d120f66}.key-diamond{position:absolute;z-index:4;top:14px;width:10px;height:10px;padding:0;transform:translate(-50%,-50%) rotate(45deg);border:1px solid #e2ffae;background:var(--acid);box-shadow:0 0 0 2px #0a0e0c}.attachment-lane .lane-label{grid-column:1;grid-row:5}.event-clip{align-self:center;grid-column:2;grid-row:5;height:23px;margin:0 8px;padding:6px 10px;border-left:3px solid var(--cyan);background:#17312d;color:#8ce7df;font-size:9px;letter-spacing:.08em}.event-clip.released{border-left-color:var(--red);background:#321a16;color:#ff9b86}.playhead{position:absolute;z-index:6;top:0;bottom:0;width:1px;background:#f3f7f4;pointer-events:none}.playhead b{position:absolute;top:0;left:-4px;width:9px;height:9px;background:#f3f7f4;clip-path:polygon(0 0,100% 0,50% 100%)}.scrubber{position:absolute;z-index:7;top:0;right:0;bottom:0;left:132px;width:calc(100% - 132px);height:100%;margin:0;padding:0;opacity:0;cursor:ew-resize}.ruler{grid-column:2;grid-row:1}.lane-row:nth-of-type(1) .lane-label,.lane-row:nth-of-type(1) .lane-track{grid-row:2}.lane-row:nth-of-type(2) .lane-label,.lane-row:nth-of-type(2) .lane-track{grid-row:3}.lane-row:nth-of-type(3) .lane-label,.lane-row:nth-of-type(3) .lane-track{grid-row:4}.lane-row .lane-label{grid-column:1}.lane-row .lane-track{grid-column:2}@media(max-width:980px){.body{grid-template-columns:210px 1fr}.right{display:none}.workspace{grid-template-rows:minmax(260px,1fr) 224px}.compact{display:none}}
254
254
  `;function nw(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll('"',"&quot;")}function rw(t){return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Pose Lab \u2014 ${nw(t)}</title><style>${rU}</style></head><body><div id="root" data-project="${nw(t)}"></div><script type="module" src="/app.js"></script></body></html>`}var aU=new URL("./client/app.js",import.meta.url),cU=256e3;function iw(t,e){if(e.length===0||Gr.isAbsolute(e)||e.split(/[\\/]/u).some(n=>n.length===0||n.startsWith(".")))return;let r=Gr.resolve(t),i=Gr.resolve(r,e);return i.startsWith(`${r}${Gr.sep}`)?i:void 0}async function lU(t){let e=[],r=new Set([".git","build","dist","node_modules"]),i=async(n,s,o)=>{if(o>6||e.length>=2e3)return;let a=await readdir(n,{withFileTypes:true}).catch(()=>[]);for(let c of a){if(c.name.startsWith(".")||r.has(c.name))continue;let l=s.length===0?c.name:`${s}/${c.name}`;c.isDirectory()?await i(Gr.join(n,c.name),l,o+1):c.name.toLowerCase().endsWith(".glb")&&e.push(l);}};return await i(t,"",0),e.sort((n,s)=>n.localeCompare(s))}async function uU(t){let e=[],r=0;for await(let i of t){let n=Buffer.from(i);if(r+=n.length,r>cU)throw new Error("Request exceeds 256 KB.");e.push(n);}return JSON.parse(Buffer.concat(e).toString("utf8"))}function Hh(t,e,r,i){t.writeHead(e,{"cache-control":"no-store","content-type":i,"x-content-type-options":"nosniff"}),t.end(r);}function Rn(t,e,r){Hh(t,e,JSON.stringify(r),"application/json; charset=utf-8");}async function ow(t={}){let e=Gr.resolve(t.project??process.cwd()),r=t.port??4192;await readdir(e).catch(()=>{throw new Error(`Project directory does not exist: ${e}`)});let i=createServer(async(s,o)=>{try{let a=new URL(s.url??"/","http://pose-lab");if(s.method==="GET"&&(a.pathname==="/"||a.pathname==="/pose"))return Hh(o,200,rw(Gr.basename(e)),"text/html; charset=utf-8");if(s.method==="GET"&&a.pathname==="/app.js")return Hh(o,200,await readFile(aU),"text/javascript; charset=utf-8");if(s.method==="GET"&&a.pathname==="/favicon.ico")return o.writeHead(204),o.end();if(s.method==="GET"&&a.pathname==="/api/models")return Rn(o,200,{models:await lU(e)});if(s.method==="GET"&&a.pathname==="/api/model"){let c=a.searchParams.get("path")??"",l=c.endsWith(".glb")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"GLB not found."});let u=await readFile(l).catch(()=>{});return u===void 0?Rn(o,404,{error:"GLB not found."}):Hh(o,200,u,"model/gltf-binary")}if(a.pathname==="/api/recipe"){let c=a.searchParams.get("path")??"",l=c.endsWith(".json")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"Recipe not found."});if(s.method==="GET"){let u=await readFile(l,"utf8").catch(()=>{});return u===void 0?Rn(o,404,{error:"Recipe not found."}):Rn(o,200,{recipe:JSON.parse(u),path:c})}if(s.method==="PUT"){let u=await uU(s);return typeof u.recipe!="object"||u.recipe===null?Rn(o,400,{error:"Body must contain a recipe object."}):(await mkdir(Gr.dirname(l),{recursive:!0}),await writeFile(l,`${JSON.stringify(u.recipe,null,2)}
255
- `,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.10"});return t.registerTool("animation_inspect",{annotations:Ba(true),description:"Inspect a local rigged GLB: bones, skeleton landmarks, clips with durations, root-motion travel and in-place detection, meshes, skins and extensions. Reads one local file and writes nothing.",inputSchema:mU,outputSchema:cw,title:"Inspect a rig and its clips"},async e=>{try{let r=cw.parse(await Py(e.file));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_attach",{annotations:Ba(false),description:"Attach a prop GLB to a bone, with per-clip keyed offsets, and bake it into an ordinary GLB beside the source. Writes the v4 op log (<model>.anim.json) next to the source GLB and the baked GLB; a version 3 pose recipe loads as the same ops and still bakes.",inputSchema:lw,outputSchema:uw,title:"Attach a prop to a bone and bake it"},async e=>{try{let r=uw.parse(await SU(lw.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_verify",{annotations:Ba(true),description:"Measure one clip for the defects a still frame cannot show: a planted foot that slides (2 cm), ground penetration (1 cm), a loop seam (5\xB0), a one-frame jitter spike, and bones whose length changes. Every defect names the bone and the frame range it spans. Thresholds are in metres; pass `scale` for a model that is not (Mixamo and Quaternius are centimetres: 0.01).",inputSchema:dw,outputSchema:hw,title:"Verify a clip's motion"},async e=>{try{let r=dw.parse(e),i=hw.parse({...await JE(r.file,r.clip,{fps:r.fps,scale:r.scale}),filmstrip:await yU(r)});return {content:En(i),structuredContent:i}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_modify",{annotations:Ba(false),description:"Edit one clip \u2014 trim, retime, move the loop point, resample, mirror, lock planted feet \u2014 writing each edit into the op log and rendering the result from the source GLB. Rendering twice from one log gives the same bytes, so the log is the change and the GLB is derived.",inputSchema:fw,outputSchema:pw,title:"Edit a clip and render it from the log"},async e=>{try{let r=fw.parse(e),i=r.log??wy(r.file),s=await lE(i).catch(async()=>({host:r.file,ops:[],version:4}));for(let c of r.edits)s=Ey(s,{clip:r.clip,edit:c,op:"modify"});await My(i,s);let o=await XE(s,r.output??vw(r.file)),a=pw.parse({...o,log:Gr.resolve(i)});return {content:En(a),structuredContent:a}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_open_view",{annotations:Ba(false),description:"Start the animation calibrator page on 127.0.0.1 and return its URL. A human drags the prop into place there; the same operations an agent calls are what the page records.",inputSchema:R0,outputSchema:mw,title:"Open the animation calibrator"},async e=>{try{let r=mw.parse(await yw(R0.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t}function bU(){nR(()=>xU());}function TU(){let t=process.argv[1];if(t===void 0)return false;try{return realpathSync(t)===realpathSync(fileURLToPath(import.meta.url))}catch{return false}}TU()&&(process.argv[2]==="--view"?yw(R0.parse({project:process.cwd()})).then(({url:t})=>process.stdout.write(`Animation view: ${t}
255
+ `,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.13"});return t.registerTool("animation_inspect",{annotations:Ba(true),description:"Inspect a local rigged GLB: bones, skeleton landmarks, clips with durations, root-motion travel and in-place detection, meshes, skins and extensions. Reads one local file and writes nothing.",inputSchema:mU,outputSchema:cw,title:"Inspect a rig and its clips"},async e=>{try{let r=cw.parse(await Py(e.file));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_attach",{annotations:Ba(false),description:"Attach a prop GLB to a bone, with per-clip keyed offsets, and bake it into an ordinary GLB beside the source. Writes the v4 op log (<model>.anim.json) next to the source GLB and the baked GLB; a version 3 pose recipe loads as the same ops and still bakes.",inputSchema:lw,outputSchema:uw,title:"Attach a prop to a bone and bake it"},async e=>{try{let r=uw.parse(await SU(lw.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_verify",{annotations:Ba(true),description:"Measure one clip for the defects a still frame cannot show: a planted foot that slides (2 cm), ground penetration (1 cm), a loop seam (5\xB0), a one-frame jitter spike, and bones whose length changes. Every defect names the bone and the frame range it spans. Thresholds are in metres; pass `scale` for a model that is not (Mixamo and Quaternius are centimetres: 0.01).",inputSchema:dw,outputSchema:hw,title:"Verify a clip's motion"},async e=>{try{let r=dw.parse(e),i=hw.parse({...await JE(r.file,r.clip,{fps:r.fps,scale:r.scale}),filmstrip:await yU(r)});return {content:En(i),structuredContent:i}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_modify",{annotations:Ba(false),description:"Edit one clip \u2014 trim, retime, move the loop point, resample, mirror, lock planted feet \u2014 writing each edit into the op log and rendering the result from the source GLB. Rendering twice from one log gives the same bytes, so the log is the change and the GLB is derived.",inputSchema:fw,outputSchema:pw,title:"Edit a clip and render it from the log"},async e=>{try{let r=fw.parse(e),i=r.log??wy(r.file),s=await lE(i).catch(async()=>({host:r.file,ops:[],version:4}));for(let c of r.edits)s=Ey(s,{clip:r.clip,edit:c,op:"modify"});await My(i,s);let o=await XE(s,r.output??vw(r.file)),a=pw.parse({...o,log:Gr.resolve(i)});return {content:En(a),structuredContent:a}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_open_view",{annotations:Ba(false),description:"Start the animation calibrator page on 127.0.0.1 and return its URL. A human drags the prop into place there; the same operations an agent calls are what the page records.",inputSchema:R0,outputSchema:mw,title:"Open the animation calibrator"},async e=>{try{let r=mw.parse(await yw(R0.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t}function bU(){nR(()=>xU());}function TU(){let t=process.argv[1];if(t===void 0)return false;try{return realpathSync(t)===realpathSync(fileURLToPath(import.meta.url))}catch{return false}}TU()&&(process.argv[2]==="--view"?yw(R0.parse({project:process.cwd()})).then(({url:t})=>process.stdout.write(`Animation view: ${t}
256
256
  `),t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
257
257
  `),process.exitCode=1;}):bU());/*! Bundled license information:
258
258