@mochiya/avatar-composition 0.1.1 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
+ // src/api.ts
2
+ import { MathUtils } from "three";
3
+
1
4
  // src/schema.ts
2
5
  import { z } from "zod";
3
6
  var EXTENSION_NAME = "MOCHIYA_avatar_composition";
4
- var SPEC_VERSION = "0.1";
7
+ var SPEC_VERSION = "0.2";
5
8
  var ASSET_KINDS = ["avatar", "attachment"];
6
9
  var CAPABILITIES = [
7
10
  "mergeArmature",
@@ -174,6 +177,8 @@ var CompositionError = class extends Error {
174
177
  code;
175
178
  };
176
179
  function parseManifest(input) {
180
+ if (typeof input === "object" && input !== null && !Array.isArray(input) && "specVersion" in input && input.specVersion === "0.1")
181
+ input = { ...input, specVersion: SPEC_VERSION };
177
182
  const result = manifestSchema.safeParse(input);
178
183
  if (!result.success)
179
184
  throw new CompositionError(
@@ -203,17 +208,7 @@ function menuItems(manifest) {
203
208
  }
204
209
 
205
210
  // src/asset.ts
206
- var MochiyaAvatarCompositionLoaderPlugin = class {
207
- constructor(parser) {
208
- this.parser = parser;
209
- }
210
- parser;
211
- name = EXTENSION_NAME;
212
- async afterRoot(gltf) {
213
- const value = this.parser.json.extensions?.[EXTENSION_NAME];
214
- if (value) gltf.userData.mochiyaAvatarComposition = parseManifest(value);
215
- }
216
- };
211
+ var imageOwners = /* @__PURE__ */ new WeakMap();
217
212
  var AvatarAsset = class {
218
213
  constructor(scene, options = {}) {
219
214
  this.scene = scene;
@@ -255,6 +250,7 @@ var AvatarAsset = class {
255
250
  ...resources.materials ?? [],
256
251
  ...resources.textures ?? []
257
252
  ]);
253
+ this.imageBitmaps = new Set(resources.imageBitmaps ?? []);
258
254
  if (options.nodes)
259
255
  for (const [index2, node] of options.nodes) this.nodes.set(index2, node);
260
256
  for (const [index2, node] of this.nodes) this.indices.set(node, index2);
@@ -267,9 +263,16 @@ var AvatarAsset = class {
267
263
  this.authoredActive.set(node, entry.active);
268
264
  node.visible = entry.active;
269
265
  }
266
+ for (const [node, active] of this.authoredActive) {
267
+ this.localActive.set(node, active);
268
+ this.evaluatedActive.set(node, active);
269
+ }
270
+ for (const image of this.imageBitmaps)
271
+ imageOwners.set(image, (imageOwners.get(image) ?? 0) + 1);
270
272
  }
271
273
  scene;
272
274
  resources;
275
+ imageBitmaps;
273
276
  disposed = false;
274
277
  meshes = [];
275
278
  bones = [];
@@ -279,7 +282,11 @@ var AvatarAsset = class {
279
282
  primitiveSlots = /* @__PURE__ */ new Map();
280
283
  materials;
281
284
  restWorld = /* @__PURE__ */ new Map();
285
+ activationOverrides = /* @__PURE__ */ new Map();
286
+ localActive = /* @__PURE__ */ new Map();
287
+ evaluatedActive = /* @__PURE__ */ new Map();
282
288
  authoredActive = /* @__PURE__ */ new Map();
289
+ sourceNames = /* @__PURE__ */ new Map();
283
290
  authoredParents = /* @__PURE__ */ new Map();
284
291
  rootRestWorld;
285
292
  manifest;
@@ -287,6 +294,7 @@ var AvatarAsset = class {
287
294
  nodeMeshes(node) {
288
295
  if (node.isMesh) return [node];
289
296
  return this.meshes.filter((mesh) => {
297
+ if (this.indices.has(mesh)) return false;
290
298
  for (let p = mesh.parent; p; p = p.parent) {
291
299
  if (p === node) return true;
292
300
  if (this.indices.has(p)) return false;
@@ -299,17 +307,26 @@ var AvatarAsset = class {
299
307
  return this.scene.matrixWorld.clone().multiply(this.rootRestWorld.clone().invert()).multiply(this.restWorld.get(node) ?? node.matrixWorld);
300
308
  }
301
309
  };
302
- async function prepareAvatarAsset(gltf) {
310
+ async function resolveAvatarDependencies(parser) {
311
+ const [nodes, materials] = await Promise.all([
312
+ parser.getDependencies("node"),
313
+ parser.getDependencies("material")
314
+ ]);
315
+ return { nodes, materials };
316
+ }
317
+ function prepareAvatarAsset(gltf, dependencies) {
303
318
  const parser = gltf.parser;
304
319
  const nodes = /* @__PURE__ */ new Map();
305
320
  const aliases = /* @__PURE__ */ new Map();
306
- const loaded = await parser.getDependencies("node");
321
+ const loaded = dependencies.nodes;
307
322
  loaded.forEach((node, index2) => {
308
323
  nodes.set(index2, node);
309
324
  aliases.set(node, [parser.json.nodes?.[index2]?.name ?? ""]);
310
325
  });
311
- const materials = await parser.getDependencies("material");
312
- const textures = new Set(await parser.getDependencies("texture"));
326
+ const materials = dependencies.materials;
327
+ const textures = /* @__PURE__ */ new Set();
328
+ for (const resource of parser.associations.keys())
329
+ if (resource.isTexture) textures.add(resource);
313
330
  const authoredObjects = /* @__PURE__ */ new Set([gltf.scene, ...nodes.values()]);
314
331
  const meshes = [];
315
332
  gltf.scene.traverse((node) => {
@@ -341,7 +358,10 @@ async function prepareAvatarAsset(gltf) {
341
358
  geometries: meshes.map((m) => m.geometry),
342
359
  skeletons: meshes.filter((m) => !!m.isSkinnedMesh).map((m) => m.skeleton),
343
360
  materials: ownedMaterials,
344
- textures
361
+ textures,
362
+ imageBitmaps: typeof ImageBitmap === "undefined" ? [] : [...textures].map((texture) => texture.image).filter(
363
+ (image) => image instanceof ImageBitmap
364
+ )
345
365
  }
346
366
  });
347
367
  for (const mesh of asset.meshes) {
@@ -349,17 +369,50 @@ async function prepareAvatarAsset(gltf) {
349
369
  if (association?.primitives !== void 0)
350
370
  asset.primitiveSlots.set(mesh, association.primitives);
351
371
  }
372
+ for (const [node, names] of aliases)
373
+ asset.sourceNames.set(node, names[0] || node.name);
352
374
  return asset;
353
375
  }
354
376
  function disposeAvatarAsset(asset) {
355
377
  if (asset.disposed) return;
356
378
  asset.disposed = true;
357
379
  asset.scene.removeFromParent();
358
- asset.vrm?.springBoneManager?.reset();
359
- asset.resources.forEach((resource) => resource.dispose());
380
+ const errors = [];
381
+ try {
382
+ asset.vrm?.springBoneManager?.reset();
383
+ } catch (error) {
384
+ errors.push(error);
385
+ }
386
+ asset.resources.forEach((resource) => {
387
+ try {
388
+ resource.dispose();
389
+ } catch (error) {
390
+ errors.push(error);
391
+ }
392
+ });
360
393
  asset.resources.clear();
394
+ for (const image of asset.imageBitmaps) {
395
+ const remaining = (imageOwners.get(image) ?? 1) - 1;
396
+ if (remaining > 0) imageOwners.set(image, remaining);
397
+ else {
398
+ imageOwners.delete(image);
399
+ try {
400
+ image.close();
401
+ } catch (error) {
402
+ errors.push(error);
403
+ }
404
+ }
405
+ }
406
+ asset.imageBitmaps.clear();
407
+ if (errors.length)
408
+ throw new AggregateError(errors, "Asset resource cleanup failed");
361
409
  }
362
410
 
411
+ // src/session.ts
412
+ import {
413
+ AnimationMixer
414
+ } from "three";
415
+
363
416
  // src/matching.ts
364
417
  function tokens(value) {
365
418
  return value.normalize("NFKC").replace(/([a-z\d])([A-Z])/g, "$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
@@ -556,15 +609,12 @@ var NameResolver = class {
556
609
  }
557
610
  };
558
611
 
559
- // src/session.ts
560
- import {
561
- AnimationMixer
562
- } from "three";
563
-
564
612
  // src/operations.ts
565
613
  function operations(component, sourceOrder) {
566
614
  const common2 = {
567
615
  componentId: component.id,
616
+ sourceNode: component.sourceNode,
617
+ automaticMenu: component.type === "menuItem",
568
618
  sourceOrder,
569
619
  condition: "condition" in component ? component.condition : void 0
570
620
  };
@@ -617,13 +667,18 @@ function operations(component, sourceOrder) {
617
667
  }
618
668
 
619
669
  // src/deletion.ts
620
- import { BufferAttribute } from "three";
670
+ import {
671
+ BufferAttribute,
672
+ BufferGeometry,
673
+ InterleavedBuffer,
674
+ InterleavedBufferAttribute
675
+ } from "three";
621
676
  var ShapeDeletion = class {
622
677
  states = /* @__PURE__ */ new Map();
623
678
  apply(requests, registered) {
624
- const live = new Set(registered.map((r) => r.mesh));
679
+ const live2 = new Set(registered.map((r) => r.mesh));
625
680
  for (const [mesh, state] of this.states)
626
- if (!live.has(mesh)) {
681
+ if (!live2.has(mesh)) {
627
682
  this.release(mesh, state);
628
683
  this.states.delete(mesh);
629
684
  }
@@ -703,7 +758,7 @@ var ShapeDeletion = class {
703
758
  continue;
704
759
  }
705
760
  const selection = [...new Set(keys)].sort().join(";");
706
- if (!state.copy) state.copy = source.clone();
761
+ if (!state.copy) state.copy = createIndexView(source);
707
762
  if (selection !== state.selection) {
708
763
  filterIndices(source, state.copy, masks);
709
764
  state.selection = selection;
@@ -730,6 +785,54 @@ var ShapeDeletion = class {
730
785
  this.states.clear();
731
786
  }
732
787
  };
788
+ function createIndexView(source) {
789
+ const view = new BufferGeometry();
790
+ const attributes = /* @__PURE__ */ new Map();
791
+ const interleaved = /* @__PURE__ */ new Map();
792
+ const share = (attribute) => {
793
+ const previous = attributes.get(attribute);
794
+ if (previous) return previous;
795
+ let result;
796
+ if ("data" in attribute) {
797
+ let data2 = interleaved.get(attribute.data);
798
+ if (!data2) {
799
+ data2 = new InterleavedBuffer(
800
+ attribute.data.array,
801
+ attribute.data.stride
802
+ );
803
+ data2.setUsage(attribute.data.usage);
804
+ interleaved.set(attribute.data, data2);
805
+ }
806
+ result = new InterleavedBufferAttribute(
807
+ data2,
808
+ attribute.itemSize,
809
+ attribute.offset,
810
+ attribute.normalized
811
+ );
812
+ } else {
813
+ result = new BufferAttribute(
814
+ attribute.array,
815
+ attribute.itemSize,
816
+ attribute.normalized
817
+ );
818
+ result.setUsage(attribute.usage);
819
+ result.gpuType = attribute.gpuType;
820
+ }
821
+ result.name = attribute.name;
822
+ attributes.set(attribute, result);
823
+ return result;
824
+ };
825
+ for (const [name, attribute] of Object.entries(source.attributes))
826
+ view.setAttribute(name, share(attribute));
827
+ for (const name of Object.keys(
828
+ source.morphAttributes
829
+ ))
830
+ view.morphAttributes[name] = source.morphAttributes[name]?.map(share);
831
+ view.morphTargetsRelative = source.morphTargetsRelative;
832
+ view.boundingBox = source.boundingBox?.clone() ?? null;
833
+ view.boundingSphere = source.boundingSphere?.clone() ?? null;
834
+ return view;
835
+ }
733
836
  function geometryStamp(g) {
734
837
  const attributes = [
735
838
  g.index,
@@ -1155,7 +1258,7 @@ var AvatarCompositionSession = class {
1155
1258
  item.warnings.push({
1156
1259
  code: "OVERLAPPING_WRITERS",
1157
1260
  operation: action.action.id,
1158
- message: `This action overlaps ${other.id}; layer order and instance ID determine the final value.`
1261
+ message: `This action overlaps ${other.id}; layer order and insertion order determine the final value.`
1159
1262
  });
1160
1263
  this.bindRig(item);
1161
1264
  item.status = item.requestedBones > 0 && item.matchedBones === 0 ? "unbound" : item.warnings.length ? "partial" : "attached";
@@ -1177,7 +1280,7 @@ var AvatarCompositionSession = class {
1177
1280
  }
1178
1281
  setItemState(id, patch) {
1179
1282
  this.requireLive();
1180
- const item = this.items.get(id);
1283
+ const item = id === "base" ? this.baseItem : this.items.get(id);
1181
1284
  if (!item)
1182
1285
  throw new CompositionError("MISSING_INSTANCE", `Unknown item ${id}`);
1183
1286
  this.restoreLayers();
@@ -1275,7 +1378,8 @@ var AvatarCompositionSession = class {
1275
1378
  afterVrmUpdate(delta) {
1276
1379
  this.requireLive();
1277
1380
  for (const item of this.items.values()) {
1278
- if (item.state.visible === false) continue;
1381
+ if (item.state.visible === false || item.asset.localActive.get(item.asset.scene) === false)
1382
+ continue;
1279
1383
  const vrm = item.asset.vrm;
1280
1384
  vrm?.expressionManager?.update();
1281
1385
  vrm?.nodeConstraintManager?.update();
@@ -1333,7 +1437,7 @@ var AvatarCompositionSession = class {
1333
1437
  return [
1334
1438
  this.baseItem,
1335
1439
  ...[...this.items.values()].sort(
1336
- (a, b) => (a.state.layerOrder ?? 0) - (b.state.layerOrder ?? 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
1440
+ (a, b) => (a.state.layerOrder ?? 0) - (b.state.layerOrder ?? 0)
1337
1441
  )
1338
1442
  ];
1339
1443
  }
@@ -1409,16 +1513,16 @@ var AvatarCompositionSession = class {
1409
1513
  logicalActive(item, node, asset) {
1410
1514
  if (asset === item.asset && item.state.visible === false) return false;
1411
1515
  for (let current = node; current && asset.authoredActive.has(current); current = asset.authoredParents.get(current) ?? null)
1412
- if (!current.visible) return false;
1516
+ if (!(asset.evaluatedActive.get(current) ?? true)) return false;
1413
1517
  return true;
1414
1518
  }
1415
1519
  condition(item, condition) {
1416
1520
  if (!condition) return () => true;
1417
1521
  if (condition.type === "control") {
1418
- const controls = menuItems(item.asset.manifest).filter(
1522
+ const controls2 = menuItems(item.asset.manifest).filter(
1419
1523
  (c) => (c.parameter ?? c.id) === condition.control
1420
1524
  );
1421
- const control = controls.find((c) => Number(c.defaultValue) !== 0) ?? controls[0];
1525
+ const control = controls2.find((c) => Number(c.defaultValue) !== 0) ?? controls2[0];
1422
1526
  if (!control)
1423
1527
  throw new CompositionError(
1424
1528
  "INVALID_CONTROL",
@@ -1468,21 +1572,49 @@ var AvatarCompositionSession = class {
1468
1572
  }
1469
1573
  };
1470
1574
  }
1471
- visibleBinding(node) {
1575
+ visibleBinding(node, owner) {
1576
+ const asset = owner ?? [this.baseItem, ...this.items.values()].find(
1577
+ (i) => i.asset.authoredActive.has(node)
1578
+ )?.asset;
1472
1579
  return {
1473
1580
  key: `${node.uuid}:active`,
1581
+ get: () => asset?.evaluatedActive.get(node) ?? node.visible,
1582
+ set: (value) => {
1583
+ if (asset)
1584
+ asset.evaluatedActive.set(
1585
+ node,
1586
+ Boolean(value) && asset.activationOverrides.get(node) !== false
1587
+ );
1588
+ else node.visible = Boolean(value);
1589
+ }
1590
+ };
1591
+ }
1592
+ renderBinding(node) {
1593
+ return {
1594
+ key: `${node.uuid}:render`,
1474
1595
  get: () => node.visible,
1475
- set: (v) => {
1476
- node.visible = Boolean(v);
1596
+ set: (value) => {
1597
+ node.visible = Boolean(value);
1477
1598
  }
1478
1599
  };
1479
1600
  }
1601
+ refresh() {
1602
+ this.requireLive();
1603
+ this.restoreLayers();
1604
+ this.evaluate();
1605
+ }
1480
1606
  compile(item, action) {
1481
1607
  const condition = this.condition(item, action.condition);
1482
1608
  if (!condition) return;
1483
1609
  const result = {
1484
1610
  action,
1485
- condition,
1611
+ condition: () => {
1612
+ if (item.state.visible === false || item.asset.localActive.get(item.asset.scene) === false)
1613
+ return false;
1614
+ const source = item.asset.nodes.get(action.sourceNode);
1615
+ const inverted = action.condition?.inverse && action.type !== "morph.sync";
1616
+ return (action.automaticMenu || inverted || !source || this.logicalActive(item, source, item.asset)) && condition();
1617
+ },
1486
1618
  execute: () => {
1487
1619
  },
1488
1620
  reads: [],
@@ -1490,6 +1622,10 @@ var AvatarCompositionSession = class {
1490
1622
  conditionReads: [],
1491
1623
  targets: []
1492
1624
  };
1625
+ if (!action.automaticMenu && !action.condition?.inverse) {
1626
+ for (let node = item.asset.nodes.get(action.sourceNode); node; node = item.asset.authoredParents.get(node) ?? void 0)
1627
+ result.conditionReads.push(this.visibleBinding(node, item.asset).key);
1628
+ }
1493
1629
  if (action.condition?.type === "nodeActive") {
1494
1630
  const selector = {
1495
1631
  asset: action.condition.asset ?? "self",
@@ -1570,7 +1706,10 @@ var AvatarCompositionSession = class {
1570
1706
  action.id
1571
1707
  );
1572
1708
  if (!target) return;
1573
- const binding = this.visibleBinding(target);
1709
+ const binding = this.visibleBinding(
1710
+ target,
1711
+ item.resolver.asset(action.target)
1712
+ );
1574
1713
  result.targets = [target.name];
1575
1714
  result.writes = [binding.key];
1576
1715
  result.execute = () => this.write(binding, action.value);
@@ -1673,16 +1812,19 @@ var AvatarCompositionSession = class {
1673
1812
  const items = this.orderedItems();
1674
1813
  if (phase !== "properties") {
1675
1814
  for (const item of items) {
1676
- if (item !== this.baseItem)
1677
- this.write(
1678
- this.visibleBinding(item.asset.scene),
1679
- item.state.visible !== false
1680
- );
1815
+ for (const [node, active] of item.asset.localActive)
1816
+ item.asset.evaluatedActive.set(node, active);
1817
+ if (item.state.visible === false)
1818
+ item.asset.evaluatedActive.set(item.asset.scene, false);
1681
1819
  for (const [index2, active] of Object.entries(
1682
1820
  item.state.nodeVisibility ?? {}
1683
1821
  )) {
1684
1822
  const node = item.asset.nodes.get(Number(index2));
1685
- if (node) this.write(this.visibleBinding(node), active);
1823
+ if (node) {
1824
+ item.asset.localActive.set(node, active);
1825
+ item.asset.activationOverrides.set(node, active);
1826
+ item.asset.evaluatedActive.set(node, active);
1827
+ }
1686
1828
  }
1687
1829
  }
1688
1830
  const pending = items.flatMap(
@@ -1702,9 +1844,11 @@ var AvatarCompositionSession = class {
1702
1844
  };
1703
1845
  pending.forEach(execute);
1704
1846
  for (const item of items)
1705
- for (const mesh of item.asset.meshes)
1706
- if (!this.logicalActive(item, mesh, item.asset))
1707
- this.write(this.visibleBinding(mesh), false);
1847
+ for (const node of item.asset.authoredActive.keys())
1848
+ this.write(
1849
+ this.renderBinding(node),
1850
+ this.logicalActive(item, node, item.asset) && (item === this.baseItem || this.base.localActive.get(this.base.scene) !== false)
1851
+ );
1708
1852
  for (const type of ["material.swap"])
1709
1853
  for (const item of items)
1710
1854
  for (const compiled of [...item.actions].sort(
@@ -1764,26 +1908,304 @@ var AvatarCompositionSession = class {
1764
1908
  }
1765
1909
  }
1766
1910
  };
1911
+
1912
+ // src/api.ts
1913
+ var data = /* @__PURE__ */ new WeakMap();
1914
+ var sessions = /* @__PURE__ */ new WeakMap();
1915
+ var controls = /* @__PURE__ */ new WeakMap();
1916
+ function live(asset) {
1917
+ if (asset.disposed)
1918
+ throw new CompositionError(
1919
+ "DISPOSED_ASSET",
1920
+ "This avatar asset has been disposed."
1921
+ );
1922
+ }
1923
+ var Item = class {
1924
+ constructor(asset, object, parent) {
1925
+ this.asset = asset;
1926
+ this.object = object;
1927
+ this.parent = parent;
1928
+ this.name = asset.manifest?.nodes.find(
1929
+ (node) => node.node === asset.indices.get(object)
1930
+ )?.aliases[0] || asset.sourceNames.get(object) || object.name;
1931
+ this.source = {
1932
+ node: asset.indices.get(object),
1933
+ path: parent ? [...parent.source.path, asset.sourceNames.get(object) || object.name] : []
1934
+ };
1935
+ this.three = { object3D: object, renderMeshes: asset.nodeMeshes(object) };
1936
+ }
1937
+ asset;
1938
+ object;
1939
+ parent;
1940
+ id = MathUtils.generateUUID();
1941
+ name;
1942
+ children = [];
1943
+ source;
1944
+ three;
1945
+ get activeSelf() {
1946
+ return this.asset.localActive.get(this.object) !== false;
1947
+ }
1948
+ get activeInHierarchy() {
1949
+ return this.asset.evaluatedActive.get(this.object) !== false && (this.parent?.activeInHierarchy ?? true);
1950
+ }
1951
+ setActive(active) {
1952
+ live(this.asset);
1953
+ this.asset.localActive.set(this.object, active);
1954
+ this.asset.activationOverrides.set(this.object, active);
1955
+ const owner = sessions.get(this.asset);
1956
+ if (owner) owner.session.refresh();
1957
+ else this.refreshDetached();
1958
+ }
1959
+ refreshDetached() {
1960
+ for (const [node, active] of this.asset.localActive)
1961
+ this.asset.evaluatedActive.set(node, active);
1962
+ for (const node of this.asset.authoredActive.keys()) {
1963
+ let visible = true;
1964
+ for (let p = node; p && this.asset.localActive.has(p); p = this.asset.authoredParents.get(p) ?? null)
1965
+ visible &&= this.asset.localActive.get(p) !== false;
1966
+ node.visible = visible;
1967
+ }
1968
+ }
1969
+ get controls() {
1970
+ const menus = menuItems(this.asset.manifest);
1971
+ return menus.filter((c) => this.asset.nodes.get(c.sourceNode) === this.object).map((c) => {
1972
+ const key = c.parameter ?? c.id;
1973
+ return {
1974
+ id: key,
1975
+ label: c.label,
1976
+ type: c.controlType,
1977
+ activeValue: c.value,
1978
+ value: controls.get(this.asset)?.[key] ?? menus.find(
1979
+ (m) => (m.parameter ?? m.id) === key && Number(m.defaultValue) !== 0
1980
+ )?.defaultValue ?? c.defaultValue
1981
+ };
1982
+ });
1983
+ }
1984
+ setControl(id, value) {
1985
+ live(this.asset);
1986
+ if (!this.controls.some((c) => c.id === id))
1987
+ throw new CompositionError(
1988
+ "INVALID_CONTROL",
1989
+ `Unknown item control: ${id}`
1990
+ );
1991
+ if (typeof value !== "boolean" && !Number.isFinite(value))
1992
+ throw new CompositionError(
1993
+ "INVALID_VALUE",
1994
+ "Control value must be finite."
1995
+ );
1996
+ const values = controls.get(this.asset) ?? {};
1997
+ values[id] = value;
1998
+ controls.set(this.asset, values);
1999
+ const owner = sessions.get(this.asset);
2000
+ owner?.session.setItemState(owner.key, { controls: { [id]: value } });
2001
+ }
2002
+ targets(id) {
2003
+ return this.three.renderMeshes.flatMap((mesh) => {
2004
+ const index2 = mesh.morphTargetDictionary?.[id];
2005
+ return index2 === void 0 || mesh.morphTargetInfluences?.[index2] === void 0 ? [] : [{ mesh, index: index2 }];
2006
+ });
2007
+ }
2008
+ get morphs() {
2009
+ const names = new Set(
2010
+ this.three.renderMeshes.flatMap(
2011
+ (m) => Object.keys(m.morphTargetDictionary ?? {})
2012
+ )
2013
+ );
2014
+ const session = sessions.get(this.asset)?.session;
2015
+ return [...names].map((name) => {
2016
+ const targets = this.targets(name), values = targets.map((t) => t.mesh.morphTargetInfluences[t.index]);
2017
+ return {
2018
+ id: name,
2019
+ name,
2020
+ value: values.every((v) => v === values[0]) ? values[0] : null,
2021
+ controlled: targets.some(
2022
+ (t) => session?.isMorphControlled(t.mesh, t.index)
2023
+ )
2024
+ };
2025
+ });
2026
+ }
2027
+ setMorph(id, value, options) {
2028
+ live(this.asset);
2029
+ if (!Number.isFinite(value))
2030
+ throw new CompositionError(
2031
+ "INVALID_VALUE",
2032
+ "Morph value must be finite."
2033
+ );
2034
+ const targets = this.targets(id), session = sessions.get(this.asset)?.session;
2035
+ if (!targets.length) return { applied: false, reason: "missing" };
2036
+ if (targets.some((t) => session?.isMorphControlled(t.mesh, t.index)))
2037
+ return { applied: false, reason: "controlled" };
2038
+ for (const { mesh, index: index2 } of targets) {
2039
+ if (session)
2040
+ session.setMorph(mesh, index2, value, { deferEvaluation: true });
2041
+ else mesh.morphTargetInfluences[index2] = value;
2042
+ }
2043
+ if (session && !options?.deferEvaluation) session.refresh();
2044
+ return { applied: true };
2045
+ }
2046
+ traverse(visitor) {
2047
+ visitor(this);
2048
+ this.children.forEach((child) => child.traverse(visitor));
2049
+ }
2050
+ };
2051
+ var Asset = class extends Item {
2052
+ constructor(asset) {
2053
+ super(asset, asset.scene, null);
2054
+ data.set(this, asset);
2055
+ const items = /* @__PURE__ */ new Map([[asset.scene, this]]);
2056
+ const create = (object) => {
2057
+ const existing = items.get(object);
2058
+ if (existing) return existing;
2059
+ let parent = asset.authoredParents.get(object);
2060
+ while (parent && parent !== asset.scene && !asset.indices.has(parent))
2061
+ parent = asset.authoredParents.get(parent);
2062
+ const owner = parent ? create(parent) : this;
2063
+ const item = new Item(asset, object, owner);
2064
+ items.set(object, item);
2065
+ owner.children.push(item);
2066
+ return item;
2067
+ };
2068
+ for (const object of asset.nodes.values()) create(object);
2069
+ }
2070
+ get scene() {
2071
+ return this.asset.scene;
2072
+ }
2073
+ get vrm() {
2074
+ return this.asset.vrm;
2075
+ }
2076
+ get manifest() {
2077
+ return this.asset.manifest;
2078
+ }
2079
+ get resources() {
2080
+ return this.asset.resources;
2081
+ }
2082
+ dispose() {
2083
+ if (sessions.has(this.asset))
2084
+ throw new CompositionError(
2085
+ "ASSET_IN_USE",
2086
+ "Remove this asset or dispose its composition before disposing the asset."
2087
+ );
2088
+ disposeAvatarAsset(this.asset);
2089
+ }
2090
+ };
2091
+ var AvatarCompositionLoaderPlugin = class {
2092
+ constructor(parser) {
2093
+ this.parser = parser;
2094
+ }
2095
+ parser;
2096
+ name = EXTENSION_NAME;
2097
+ async afterRoot(gltf) {
2098
+ const manifest = this.parser.json.extensions?.[EXTENSION_NAME];
2099
+ if (manifest !== void 0)
2100
+ gltf.userData.mochiyaAvatarComposition = parseManifest(manifest);
2101
+ const dependencies = await resolveAvatarDependencies(this.parser);
2102
+ let asset;
2103
+ Object.defineProperty(gltf.userData, "avatar", {
2104
+ enumerable: true,
2105
+ configurable: true,
2106
+ get: () => asset ??= new Asset(prepareAvatarAsset(gltf, dependencies))
2107
+ });
2108
+ }
2109
+ };
2110
+ var AvatarComposition = class {
2111
+ #session;
2112
+ #items = [];
2113
+ #disposed = false;
2114
+ base;
2115
+ constructor(base) {
2116
+ const asset = data.get(base);
2117
+ if (!asset)
2118
+ throw new CompositionError(
2119
+ "INVALID_ASSET",
2120
+ "Register AvatarCompositionLoaderPlugin and read userData.avatar after loading."
2121
+ );
2122
+ live(asset);
2123
+ this.base = base;
2124
+ this.#session = new AvatarCompositionSession({ base: asset });
2125
+ sessions.set(asset, { session: this.#session, key: "base" });
2126
+ this.#session.setItemState("base", { controls: controls.get(asset) });
2127
+ }
2128
+ get items() {
2129
+ return this.#items;
2130
+ }
2131
+ get issues() {
2132
+ return [
2133
+ ...this.#session.warnings,
2134
+ ...this.#session.attachments.flatMap((a) => a.warnings)
2135
+ ];
2136
+ }
2137
+ add(asset, options = {}) {
2138
+ const core = data.get(asset);
2139
+ if (!core)
2140
+ throw new CompositionError(
2141
+ "INVALID_ASSET",
2142
+ "Register AvatarCompositionLoaderPlugin and read userData.avatar after loading."
2143
+ );
2144
+ live(core);
2145
+ this.#session.attach(core, {
2146
+ id: asset.id,
2147
+ layerOrder: options.order,
2148
+ controls: controls.get(core)
2149
+ });
2150
+ sessions.set(core, { session: this.#session, key: asset.id });
2151
+ this.#items.push(asset);
2152
+ return asset;
2153
+ }
2154
+ remove(asset) {
2155
+ if (!this.#items.includes(asset)) return;
2156
+ this.#session.detach(asset.id);
2157
+ sessions.delete(data.get(asset));
2158
+ this.#items = this.#items.filter((a) => a !== asset);
2159
+ asset.refreshDetached();
2160
+ }
2161
+ setOrder(asset, order) {
2162
+ this.#session.setItemState(asset.id, { layerOrder: order });
2163
+ }
2164
+ inspect(asset) {
2165
+ if (asset === this.base)
2166
+ return {
2167
+ status: this.#session.warnings.length ? "partial" : "attached",
2168
+ warnings: this.#session.warnings,
2169
+ resolved: this.#session.resolved,
2170
+ matchedBones: 0,
2171
+ requestedBones: 0,
2172
+ appliedActions: this.#session.resolved.length
2173
+ };
2174
+ const result = this.#session.attachments.find((a) => a.id === asset.id);
2175
+ if (!result)
2176
+ throw new CompositionError(
2177
+ "MISSING_INSTANCE",
2178
+ "This asset is not in the composition."
2179
+ );
2180
+ return result;
2181
+ }
2182
+ setAnimation(clip, time = 0) {
2183
+ this.#session.setAnimation(clip, time);
2184
+ }
2185
+ get animationTime() {
2186
+ return this.#session.animationTime;
2187
+ }
2188
+ update(delta, paused = false) {
2189
+ this.#session.update(delta, paused);
2190
+ }
2191
+ dispose() {
2192
+ if (this.#disposed) return;
2193
+ this.#session.dispose();
2194
+ for (const asset of [this.base, ...this.#items]) {
2195
+ sessions.delete(data.get(asset));
2196
+ asset.refreshDetached();
2197
+ }
2198
+ this.#items = [];
2199
+ this.#disposed = true;
2200
+ }
2201
+ };
1767
2202
  export {
1768
2203
  ASSET_KINDS,
1769
- AvatarAsset,
1770
- AvatarCompositionSession,
2204
+ AvatarComposition,
2205
+ AvatarCompositionLoaderPlugin,
1771
2206
  CAPABILITIES,
1772
2207
  CompositionError,
1773
2208
  EXTENSION_NAME,
1774
- MochiyaAvatarCompositionLoaderPlugin,
1775
- NameResolver,
1776
2209
  SPEC_VERSION,
1777
- componentSchema,
1778
- conditionSchema,
1779
- curveSchema,
1780
- disposeAvatarAsset,
1781
- evaluateCurve,
1782
- keywordScore,
1783
- manifestSchema,
1784
- menuItems,
1785
- parseManifest,
1786
- prepareAvatarAsset,
1787
- selectorSchema,
1788
- tokens
2210
+ parseManifest
1789
2211
  };