@threenative/metahuman 0.1.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.
@@ -0,0 +1,879 @@
1
+ import { Vector3, Quaternion, Group, Matrix4 } from 'three';
2
+ import { clone } from 'three/addons/utils/SkeletonUtils.js';
3
+
4
+ // src/metahuman.ts
5
+
6
+ // src/abi.ts
7
+ var JOINT_STRIDE = 10;
8
+
9
+ // src/errors.ts
10
+ var MetaHumanAssetError = class extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(`${code}: ${message}`);
14
+ this.name = "MetaHumanAssetError";
15
+ this.code = code;
16
+ }
17
+ };
18
+
19
+ // src/asset-contract.ts
20
+ var METAHUMAN_BINDINGS_SCHEMA_VERSION = 1;
21
+ var SHA256 = /^[0-9a-f]{64}$/u;
22
+ function fail(code, message) {
23
+ throw new MetaHumanAssetError(code, message);
24
+ }
25
+ function record(value, what) {
26
+ if (typeof value !== "object" || value === null || Array.isArray(value))
27
+ fail("TN_MH_SCHEMA", `${what} must be an object`);
28
+ return value;
29
+ }
30
+ function text(value, what) {
31
+ if (typeof value !== "string" || value.length === 0)
32
+ fail("TN_MH_SCHEMA", `${what} must be a non-empty string`);
33
+ return value;
34
+ }
35
+ function list(value, what) {
36
+ if (!Array.isArray(value)) fail("TN_MH_SCHEMA", `${what} must be an array`);
37
+ return value;
38
+ }
39
+ function index(value, what) {
40
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0)
41
+ fail("TN_MH_SCHEMA", `${what} must be a non-negative integer`);
42
+ return value;
43
+ }
44
+ function finite(value, what) {
45
+ if (typeof value !== "number" || !Number.isFinite(value))
46
+ fail("TN_MH_NON_FINITE", `${what} must be a finite number`);
47
+ return value;
48
+ }
49
+ function sha256(value, what) {
50
+ if (typeof value !== "string" || !SHA256.test(value))
51
+ fail("TN_MH_SCHEMA", `${what} must be a lowercase hex sha256`);
52
+ return value;
53
+ }
54
+ function oneOf(value, allowed, what) {
55
+ if (typeof value !== "string" || !allowed.includes(value))
56
+ fail("TN_MH_SCHEMA", `${what} must be one of ${allowed.join(", ")}`);
57
+ return value;
58
+ }
59
+ function assertAssetPath(path) {
60
+ if (typeof path !== "string" || path.length === 0)
61
+ fail("TN_MH_PATH_ESCAPE", "an asset path must be a non-empty string");
62
+ if (path.includes("\\")) fail("TN_MH_PATH_ESCAPE", `${path} uses a backslash separator`);
63
+ if (path.startsWith("/") || /^[a-zA-Z]:/u.test(path))
64
+ fail("TN_MH_PATH_ESCAPE", `${path} is absolute`);
65
+ if (path.split("/").some((segment) => segment === ".."))
66
+ fail("TN_MH_PATH_ESCAPE", `${path} walks out with ".."`);
67
+ return path;
68
+ }
69
+ function validateMetaHumanAssets(input) {
70
+ const { bindings, dnaSha256, glbSha256, rig, gltf } = input;
71
+ const root = record(bindings, "bindings");
72
+ if (root.schemaVersion !== METAHUMAN_BINDINGS_SCHEMA_VERSION)
73
+ fail("TN_MH_SCHEMA", `schemaVersion must be ${METAHUMAN_BINDINGS_SCHEMA_VERSION}`);
74
+ const specimen = record(root.specimen, "specimen");
75
+ const hashes = record(root.hashes, "hashes");
76
+ const coordinates = record(root.coordinates, "coordinates");
77
+ const dnaHash = sha256(hashes.dna, "hashes.dna");
78
+ const glbHash = sha256(hashes.glb, "hashes.glb");
79
+ if (dnaHash !== dnaSha256)
80
+ fail("TN_MH_HASH_MISMATCH", "the loaded DNA is not the one this bindings sidecar names");
81
+ if (glbSha256 !== void 0 && glbHash !== glbSha256)
82
+ fail("TN_MH_HASH_MISMATCH", "the loaded GLB is not the one this bindings sidecar names");
83
+ const nodeNames = /* @__PURE__ */ new Set();
84
+ for (const node of gltf.nodes) {
85
+ if (typeof node.name === "string") nodeNames.add(node.name);
86
+ }
87
+ const jointNames = new Set(rig.joints);
88
+ const channelNames = new Set(rig.blendShapes);
89
+ const guiNames = new Set(rig.gui);
90
+ const mapNames = new Set(rig.animatedMaps);
91
+ const joints = list(root.joints, "joints").map((entry) => {
92
+ const joint = record(entry, "a joint binding");
93
+ const dna = text(joint.dna, "joints[].dna");
94
+ const node = text(joint.node, "joints[].node");
95
+ if (!jointNames.has(dna)) fail("TN_MH_UNKNOWN_JOINT", `the DNA has no joint named ${dna}`);
96
+ if (!nodeNames.has(node)) fail("TN_MH_UNKNOWN_NODE", `the GLB has no node named ${node}`);
97
+ return { dna, node };
98
+ });
99
+ const morphs = list(root.morphs, "morphs").map((entry) => {
100
+ const morph = record(entry, "a morph binding");
101
+ const channel = text(morph.channel, "morphs[].channel");
102
+ if (!channelNames.has(channel))
103
+ fail("TN_MH_UNKNOWN_CHANNEL", `the DNA has no blend shape channel named ${channel}`);
104
+ const mesh = index(morph.mesh, "morphs[].mesh");
105
+ const meshEntry = gltf.meshes[mesh];
106
+ if (meshEntry === void 0) fail("TN_MH_INDEX_RANGE", `mesh ${mesh} is not in the GLB`);
107
+ const primitive = index(morph.primitive, "morphs[].primitive");
108
+ const meshPrimitive = meshEntry.primitives[primitive];
109
+ if (meshPrimitive === void 0)
110
+ fail("TN_MH_INDEX_RANGE", `mesh ${mesh} has no primitive ${primitive}`);
111
+ const target = index(morph.target, "morphs[].target");
112
+ if (target >= (meshPrimitive.targets?.length ?? 0))
113
+ fail(
114
+ "TN_MH_INDEX_RANGE",
115
+ `mesh ${mesh} primitive ${primitive} has ${meshPrimitive.targets?.length ?? 0} targets`
116
+ );
117
+ const targetNames = meshPrimitive.extras?.targetNames;
118
+ if (Array.isArray(targetNames) && targetNames[target] !== channel)
119
+ fail(
120
+ "TN_MH_UNKNOWN_CHANNEL",
121
+ `mesh ${mesh} primitive ${primitive} target ${target} is ${String(targetNames[target])}, not ${channel}`
122
+ );
123
+ return { channel, mesh, primitive, target };
124
+ });
125
+ const lods = list(root.lods, "lods").map((entry) => {
126
+ const lodEntry = record(entry, "a LOD binding");
127
+ const lod = index(lodEntry.lod, "lods[].lod");
128
+ if (lod >= rig.lodCount) fail("TN_MH_BAD_LOD", `lod ${lod} is not below ${rig.lodCount}`);
129
+ const meshes = list(lodEntry.meshes, "lods[].meshes").map((mesh, position) => {
130
+ const value = index(mesh, `lods[${lod}].meshes[${position}]`);
131
+ if (value >= gltf.meshes.length) fail("TN_MH_INDEX_RANGE", `mesh ${value} is not in the GLB`);
132
+ return value;
133
+ });
134
+ return { lod, meshes };
135
+ });
136
+ const aliases = /* @__PURE__ */ new Set();
137
+ const controls = list(root.controls, "controls").map((entry) => {
138
+ const control = record(entry, "a control binding");
139
+ const alias = text(control.alias, "controls[].alias");
140
+ if (aliases.has(alias)) fail("TN_MH_DUPLICATE_ALIAS", `${alias} is bound twice`);
141
+ aliases.add(alias);
142
+ const gui = text(control.gui, "controls[].gui");
143
+ if (!guiNames.has(gui))
144
+ fail("TN_MH_UNKNOWN_CONTROL", `the DNA has no GUI control named ${gui}`);
145
+ const min = finite(control.min, `${alias}.min`);
146
+ const max = finite(control.max, `${alias}.max`);
147
+ const value = finite(control.default, `${alias}.default`);
148
+ if (!(min < max)) fail("TN_MH_BAD_DOMAIN", `${alias} has min ${min} and max ${max}`);
149
+ if (value < min || value > max)
150
+ fail("TN_MH_BAD_DOMAIN", `${alias} defaults to ${value}, outside [${min}, ${max}]`);
151
+ return { alias, gui, min, max, default: value };
152
+ });
153
+ const animatedMaps = root.animatedMaps === void 0 ? void 0 : mapBindings(root.animatedMaps, mapNames);
154
+ return Object.freeze({
155
+ schemaVersion: METAHUMAN_BINDINGS_SCHEMA_VERSION,
156
+ specimen: Object.freeze({
157
+ id: text(specimen.id, "specimen.id"),
158
+ source: text(specimen.source, "specimen.source"),
159
+ license: text(specimen.license, "specimen.license")
160
+ }),
161
+ hashes: Object.freeze({ dna: dnaHash, glb: glbHash }),
162
+ coordinates: Object.freeze({
163
+ sourceUnits: oneOf(coordinates.sourceUnits, ["cm", "m"], "coordinates.sourceUnits"),
164
+ sourceUp: oneOf(coordinates.sourceUp, ["y", "z"], "coordinates.sourceUp"),
165
+ handedness: oneOf(
166
+ coordinates.handedness,
167
+ ["left", "right"],
168
+ "coordinates.handedness"
169
+ )
170
+ }),
171
+ joints,
172
+ morphs,
173
+ lods,
174
+ controls,
175
+ ...animatedMaps === void 0 ? {} : { animatedMaps }
176
+ });
177
+ }
178
+ function mapBindings(value, mapNames) {
179
+ return list(value, "animatedMaps").map((entry) => {
180
+ const map = record(entry, "an animated map binding");
181
+ const name = text(map.map, "animatedMaps[].map");
182
+ if (!mapNames.has(name)) fail("TN_MH_UNKNOWN_MAP", `the DNA has no animated map named ${name}`);
183
+ return { map: name };
184
+ });
185
+ }
186
+ var AXIS_MAPS = {
187
+ "y/right": [1, 0, 0, 0, 1, 0, 0, 0, 1],
188
+ "y/left": [1, 0, 0, 0, 1, 0, 0, 0, -1],
189
+ "z/right": [1, 0, 0, 0, 0, 1, 0, 1, 0],
190
+ "z/left": [1, 0, 0, 0, 0, 1, 0, -1, 0]
191
+ };
192
+ function axisMap(coordinates) {
193
+ const key = `${coordinates.sourceUp}/${coordinates.handedness}`;
194
+ const map = AXIS_MAPS[key];
195
+ if (map === void 0)
196
+ throw new Error(`TN_MH_COORDINATES: no axis map for ${key}, which the schema forbids`);
197
+ return new Matrix4().set(
198
+ map[0],
199
+ map[1],
200
+ map[2],
201
+ 0,
202
+ map[3],
203
+ map[4],
204
+ map[5],
205
+ 0,
206
+ map[6],
207
+ map[7],
208
+ map[8],
209
+ 0,
210
+ 0,
211
+ 0,
212
+ 0,
213
+ 1
214
+ );
215
+ }
216
+ function metaHumanBasis(coordinates) {
217
+ const axis = axisMap(coordinates);
218
+ const inverse = axis.clone().transpose();
219
+ const scale = coordinates.sourceUnits === "cm" ? 0.01 : 1;
220
+ const rotation = new Matrix4();
221
+ const conjugated = new Matrix4();
222
+ return {
223
+ scale,
224
+ vector(source, target) {
225
+ return target.copy(source).applyMatrix4(axis).multiplyScalar(scale);
226
+ },
227
+ quaternion(source, target) {
228
+ rotation.makeRotationFromQuaternion(source);
229
+ conjugated.multiplyMatrices(axis, rotation).multiply(inverse);
230
+ return target.setFromRotationMatrix(conjugated);
231
+ },
232
+ scaleTriple(source, target) {
233
+ return coordinates.sourceUp === "z" ? target.set(source.x, source.z, source.y) : target.copy(source);
234
+ }
235
+ };
236
+ }
237
+
238
+ // src/sha256.ts
239
+ async function sha256Hex(bytes) {
240
+ const subtle = globalThis.crypto?.subtle;
241
+ const digest = subtle ? new Uint8Array(await subtle.digest("SHA-256", Uint8Array.from(bytes))) : sha256Portable(bytes);
242
+ let hex = "";
243
+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
244
+ return hex;
245
+ }
246
+ var K = new Uint32Array([
247
+ 1116352408,
248
+ 1899447441,
249
+ 3049323471,
250
+ 3921009573,
251
+ 961987163,
252
+ 1508970993,
253
+ 2453635748,
254
+ 2870763221,
255
+ 3624381080,
256
+ 310598401,
257
+ 607225278,
258
+ 1426881987,
259
+ 1925078388,
260
+ 2162078206,
261
+ 2614888103,
262
+ 3248222580,
263
+ 3835390401,
264
+ 4022224774,
265
+ 264347078,
266
+ 604807628,
267
+ 770255983,
268
+ 1249150122,
269
+ 1555081692,
270
+ 1996064986,
271
+ 2554220882,
272
+ 2821834349,
273
+ 2952996808,
274
+ 3210313671,
275
+ 3336571891,
276
+ 3584528711,
277
+ 113926993,
278
+ 338241895,
279
+ 666307205,
280
+ 773529912,
281
+ 1294757372,
282
+ 1396182291,
283
+ 1695183700,
284
+ 1986661051,
285
+ 2177026350,
286
+ 2456956037,
287
+ 2730485921,
288
+ 2820302411,
289
+ 3259730800,
290
+ 3345764771,
291
+ 3516065817,
292
+ 3600352804,
293
+ 4094571909,
294
+ 275423344,
295
+ 430227734,
296
+ 506948616,
297
+ 659060556,
298
+ 883997877,
299
+ 958139571,
300
+ 1322822218,
301
+ 1537002063,
302
+ 1747873779,
303
+ 1955562222,
304
+ 2024104815,
305
+ 2227730452,
306
+ 2361852424,
307
+ 2428436474,
308
+ 2756734187,
309
+ 3204031479,
310
+ 3329325298
311
+ ]);
312
+ function sha256Portable(bytes) {
313
+ const blocks = Math.ceil((bytes.length + 9) / 64);
314
+ const padded = new Uint8Array(blocks * 64);
315
+ padded.set(bytes);
316
+ padded[bytes.length] = 128;
317
+ const view = new DataView(padded.buffer);
318
+ view.setUint32(padded.length - 8, Math.floor(bytes.length / 536870912));
319
+ view.setUint32(padded.length - 4, bytes.length * 8 >>> 0);
320
+ const h = new Uint32Array([
321
+ 1779033703,
322
+ 3144134277,
323
+ 1013904242,
324
+ 2773480762,
325
+ 1359893119,
326
+ 2600822924,
327
+ 528734635,
328
+ 1541459225
329
+ ]);
330
+ const w = new Uint32Array(64);
331
+ for (let offset = 0; offset < padded.length; offset += 64) {
332
+ for (let t = 0; t < 16; t += 1) w[t] = view.getUint32(offset + t * 4);
333
+ for (let t = 16; t < 64; t += 1) {
334
+ const a2 = w[t - 15];
335
+ const b2 = w[t - 2];
336
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
337
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
338
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 >>> 0;
339
+ }
340
+ let [a, b, c, d, e, f, g, hh] = Array.from(h);
341
+ for (let t = 0; t < 64; t += 1) {
342
+ const e0 = e;
343
+ const a0 = a;
344
+ const s1 = (e0 >>> 6 | e0 << 26) ^ (e0 >>> 11 | e0 << 21) ^ (e0 >>> 25 | e0 << 7);
345
+ const ch = e0 & f ^ ~e0 & g;
346
+ const t1 = hh + s1 + ch + K[t] + w[t] >>> 0;
347
+ const s0 = (a0 >>> 2 | a0 << 30) ^ (a0 >>> 13 | a0 << 19) ^ (a0 >>> 22 | a0 << 10);
348
+ const maj = a0 & b ^ a0 & c ^ b & c;
349
+ const t2 = s0 + maj >>> 0;
350
+ hh = g;
351
+ g = f;
352
+ f = e;
353
+ e = d + t1 >>> 0;
354
+ d = c;
355
+ c = b;
356
+ b = a;
357
+ a = t1 + t2 >>> 0;
358
+ }
359
+ h[0] = h[0] + a >>> 0;
360
+ h[1] = h[1] + b >>> 0;
361
+ h[2] = h[2] + c >>> 0;
362
+ h[3] = h[3] + d >>> 0;
363
+ h[4] = h[4] + e >>> 0;
364
+ h[5] = h[5] + f >>> 0;
365
+ h[6] = h[6] + g >>> 0;
366
+ h[7] = h[7] + hh >>> 0;
367
+ }
368
+ const out = new Uint8Array(32);
369
+ const outView = new DataView(out.buffer);
370
+ for (let index2 = 0; index2 < 8; index2 += 1) outView.setUint32(index2 * 4, h[index2]);
371
+ return out;
372
+ }
373
+
374
+ // src/metahuman.ts
375
+ function fail2(code, message) {
376
+ throw new MetaHumanAssetError(code, message);
377
+ }
378
+ async function readBytes(assets, path) {
379
+ const candidates = await assets.resolve(path);
380
+ const failures = [];
381
+ for (const url of candidates) {
382
+ try {
383
+ const response = await fetch(url);
384
+ if (!response.ok) {
385
+ failures.push(`${url} (status ${String(response.status)})`);
386
+ continue;
387
+ }
388
+ return new Uint8Array(await response.arrayBuffer());
389
+ } catch (error) {
390
+ failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
391
+ }
392
+ }
393
+ return fail2(
394
+ "TN_MH_WASM_LOAD",
395
+ `'${path}' is not served from any of ${String(candidates.length)} candidate url(s): ${failures.join("; ")}`
396
+ );
397
+ }
398
+ function isRecord(value) {
399
+ return typeof value === "object" && value !== null && !Array.isArray(value);
400
+ }
401
+ function gltfFactsOf(model) {
402
+ const json = model.parser?.json;
403
+ if (!isRecord(json) || !Array.isArray(json.nodes) || !Array.isArray(json.meshes))
404
+ fail2(
405
+ "TN_MH_SCHEMA",
406
+ "the model did not come from a glTF loader, so its bindings cannot be checked against it"
407
+ );
408
+ return { nodes: json.nodes, meshes: json.meshes };
409
+ }
410
+ function isMesh(node) {
411
+ return node?.isMesh === true;
412
+ }
413
+ function collect(root) {
414
+ const found = [];
415
+ const walk = (node) => {
416
+ found.push(node);
417
+ for (const child of node.children) walk(child);
418
+ };
419
+ walk(root);
420
+ return found;
421
+ }
422
+ function geometryByMeshIndex(model) {
423
+ const byIndex = /* @__PURE__ */ new Map();
424
+ for (const [object, mapping] of model.parser?.associations ?? []) {
425
+ if (!isMesh(object) || mapping.meshes === void 0) continue;
426
+ const primitives = byIndex.get(mapping.meshes) ?? [];
427
+ primitives[mapping.primitives ?? 0] = object.geometry;
428
+ byIndex.set(mapping.meshes, primitives);
429
+ }
430
+ return byIndex;
431
+ }
432
+ function meshesByGeometry(root) {
433
+ const byGeometry = /* @__PURE__ */ new Map();
434
+ for (const node of collect(root)) {
435
+ if (!isMesh(node)) continue;
436
+ const existing = byGeometry.get(node.geometry);
437
+ if (existing === void 0) byGeometry.set(node.geometry, [node]);
438
+ else existing.push(node);
439
+ }
440
+ return byGeometry;
441
+ }
442
+ function setInfluence(morph, weight) {
443
+ const influences = morph.mesh.morphTargetInfluences;
444
+ if (influences === void 0 || morph.index >= influences.length)
445
+ fail2("TN_MH_INDEX_RANGE", `${morph.mesh.name} has no morph target ${String(morph.index)}`);
446
+ influences[morph.index] = weight;
447
+ }
448
+ function lodOfMesh(bindings, mesh) {
449
+ return bindings.lods.find((entry) => entry.meshes.includes(mesh))?.lod ?? -1;
450
+ }
451
+ var MetaHuman = class {
452
+ root;
453
+ controls;
454
+ #evaluator;
455
+ #backend;
456
+ #openRigLogic;
457
+ #basis;
458
+ #joints;
459
+ #morphs;
460
+ #lodMeshes;
461
+ #meshes;
462
+ #animatedMapNames;
463
+ #gui;
464
+ #defaultGui;
465
+ #controlByAlias;
466
+ #mapWeights;
467
+ #lod;
468
+ #disposed = false;
469
+ /** Per-frame scratch, so a head with hundreds of joints allocates nothing per frame. */
470
+ #translation = new Vector3();
471
+ #rotation = new Quaternion();
472
+ #deltaRotation = new Quaternion();
473
+ #deltaScale = new Vector3();
474
+ constructor(input) {
475
+ const { bindings, evaluator } = input;
476
+ this.#evaluator = evaluator;
477
+ this.#backend = input.backend;
478
+ this.#openRigLogic = input.openRigLogic;
479
+ this.#basis = metaHumanBasis(bindings.coordinates);
480
+ this.root = new Group();
481
+ this.root.name = "metahuman";
482
+ this.root.add(clone(input.loader.scene));
483
+ const nodes = /* @__PURE__ */ new Map();
484
+ for (const node of collect(this.root)) if (node.name.length > 0) nodes.set(node.name, node);
485
+ const jointIndex = new Map(evaluator.names("joint").map((name, index2) => [name, index2]));
486
+ this.#joints = bindings.joints.map((entry) => {
487
+ const joint = jointIndex.get(entry.dna);
488
+ const node = nodes.get(entry.node);
489
+ if (joint === void 0 || node === void 0)
490
+ fail2("TN_MH_UNKNOWN_NODE", `${entry.dna} -> ${entry.node} is not in the loaded rig`);
491
+ return {
492
+ node,
493
+ joint,
494
+ restPosition: node.position.clone(),
495
+ restQuaternion: node.quaternion.clone(),
496
+ restScale: node.scale.clone()
497
+ };
498
+ });
499
+ const geometry = geometryByMeshIndex(input.loader);
500
+ const meshes = meshesByGeometry(this.root);
501
+ this.#meshes = [...meshes.values()].flat();
502
+ const meshOf = (mesh, primitive) => {
503
+ const where = `glTF mesh ${String(mesh)} primitive ${String(primitive)}`;
504
+ const source = geometry.get(mesh)?.[primitive];
505
+ if (source === void 0) fail2("TN_MH_INDEX_RANGE", `the model has no ${where}`);
506
+ const found = meshes.get(source)?.[0];
507
+ if (found === void 0) fail2("TN_MH_INDEX_RANGE", `the model has no mesh for ${where}`);
508
+ return found;
509
+ };
510
+ const channelIndex = new Map(evaluator.names("blendShape").map((name, index2) => [name, index2]));
511
+ this.#morphs = bindings.morphs.map((entry) => {
512
+ const mesh = meshOf(entry.mesh, entry.primitive);
513
+ const channel = channelIndex.get(entry.channel);
514
+ if (channel === void 0) fail2("TN_MH_UNKNOWN_CHANNEL", `the rig has no ${entry.channel}`);
515
+ const name = Object.keys(mesh.morphTargetDictionary ?? {})[entry.target];
516
+ if (name === void 0 || !name.endsWith(`__${entry.channel}`))
517
+ fail2(
518
+ "TN_MH_UNKNOWN_CHANNEL",
519
+ `glTF mesh ${String(entry.mesh)} target ${String(entry.target)} is ${String(name)}, not ${entry.channel}`
520
+ );
521
+ return { mesh, index: entry.target, channel, lod: lodOfMesh(bindings, entry.mesh) };
522
+ });
523
+ this.#lodMeshes = bindings.lods.map(
524
+ (entry) => entry.meshes.flatMap(
525
+ (mesh) => Array.from(
526
+ { length: geometry.get(mesh)?.length ?? 0 },
527
+ (_, primitive) => meshOf(mesh, primitive)
528
+ )
529
+ )
530
+ );
531
+ if (input.lod < 0 || input.lod >= this.#lodMeshes.length)
532
+ fail2("TN_MH_BAD_LOD", `${String(input.lod)} is not one of this specimen's LODs`);
533
+ if (input.lod !== 0) this.#evaluator.setLod(input.lod);
534
+ this.#lod = input.lod;
535
+ this.#showLod(input.lod);
536
+ this.controls = Object.freeze(
537
+ bindings.controls.map(
538
+ (entry) => Object.freeze({
539
+ alias: entry.alias,
540
+ gui: entry.gui,
541
+ min: entry.min,
542
+ max: entry.max,
543
+ default: entry.default
544
+ })
545
+ )
546
+ );
547
+ const gui = evaluator.names("gui");
548
+ this.#gui = new Float32Array(gui.length);
549
+ const byAlias = /* @__PURE__ */ new Map();
550
+ for (const control of this.controls) {
551
+ const index2 = gui.indexOf(control.gui);
552
+ if (index2 < 0) fail2("TN_MH_UNKNOWN_CONTROL", `the rig has no GUI control ${control.gui}`);
553
+ byAlias.set(control.alias, Object.freeze({ ...control, index: index2 }));
554
+ this.#gui[index2] = control.default;
555
+ }
556
+ this.#controlByAlias = byAlias;
557
+ this.#defaultGui = Float32Array.from(this.#gui);
558
+ this.#mapWeights = new Float32Array(evaluator.counts().animatedMaps);
559
+ this.#animatedMapNames = Object.freeze(
560
+ bindings.animatedMaps?.map((entry) => entry.map) ?? evaluator.names("animatedMap")
561
+ );
562
+ }
563
+ animatedMapNames() {
564
+ this.#live();
565
+ return this.#animatedMapNames;
566
+ }
567
+ animatedMaps() {
568
+ this.#live();
569
+ return Float32Array.from(this.#mapWeights);
570
+ }
571
+ setControls(values) {
572
+ this.#live();
573
+ if (!isRecord(values)) fail2("TN_MH_SCHEMA", "setControls takes a record of alias to number");
574
+ for (const [alias, value] of Object.entries(values)) {
575
+ const control = this.#controlByAlias.get(alias);
576
+ if (control === void 0)
577
+ fail2("TN_MH_UNKNOWN_CONTROL", `no control is declared as ${alias}`);
578
+ if (typeof value !== "number")
579
+ fail2("TN_MH_BAD_DOMAIN", `${alias} was given a ${typeof value}`);
580
+ if (!Number.isFinite(value)) fail2("TN_MH_NON_FINITE", `${alias} was given ${String(value)}`);
581
+ if (value < control.min || value > control.max)
582
+ fail2(
583
+ "TN_MH_BAD_DOMAIN",
584
+ `${alias} was given ${String(value)}, outside [${String(control.min)}, ${String(control.max)}]`
585
+ );
586
+ this.#gui[control.index] = value;
587
+ }
588
+ }
589
+ reset() {
590
+ this.#live();
591
+ this.#gui.set(this.#defaultGui);
592
+ }
593
+ setLod(lod) {
594
+ this.#live();
595
+ if (!Number.isInteger(lod) || lod < 0 || lod >= this.#lodMeshes.length)
596
+ fail2(
597
+ "TN_MH_BAD_LOD",
598
+ `${String(lod)} is not one of this specimen's ${String(this.#lodMeshes.length)} LODs`
599
+ );
600
+ if (lod === this.#lod) return;
601
+ for (const mesh of this.#lodMeshes[this.#lod]) mesh.visible = false;
602
+ this.#evaluator.setLod(lod);
603
+ this.#lod = lod;
604
+ for (const morph of this.#morphs) if (morph.lod !== lod) setInfluence(morph, 0);
605
+ this.#evaluate();
606
+ this.#showLod(lod);
607
+ }
608
+ update() {
609
+ this.#live();
610
+ this.#evaluate();
611
+ }
612
+ diagnostics() {
613
+ this.#live();
614
+ const counts = this.#evaluator.counts();
615
+ return Object.freeze({
616
+ backend: this.#backend,
617
+ openRigLogic: this.#openRigLogic,
618
+ lod: this.#lod,
619
+ joints: counts.joints,
620
+ blendShapes: counts.blendShapes,
621
+ animatedMaps: counts.animatedMaps,
622
+ controls: this.controls.length
623
+ });
624
+ }
625
+ dispose() {
626
+ if (this.#disposed) return;
627
+ this.#disposed = true;
628
+ this.#evaluator.dispose();
629
+ this.root.removeFromParent();
630
+ this.root.clear();
631
+ }
632
+ #live() {
633
+ if (this.#disposed) fail2("TN_MH_DISPOSED", "this MetaHuman handle is disposed");
634
+ }
635
+ #showLod(lod) {
636
+ const active = new Set(this.#lodMeshes[lod]);
637
+ for (const mesh of this.#meshes) mesh.visible = active.has(mesh);
638
+ }
639
+ /** Effective GUI vector in, joint and morph output out. The rig maps GUI to raw itself. */
640
+ #evaluate() {
641
+ const evaluator = this.#evaluator;
642
+ evaluator.setGuiControls(this.#gui);
643
+ evaluator.evaluate(true);
644
+ const joints = evaluator.jointOutputs();
645
+ for (const binding of this.#joints) {
646
+ const at = binding.joint * JOINT_STRIDE;
647
+ if (at + JOINT_STRIDE > joints.length)
648
+ fail2("TN_MH_LENGTH", `the rig returned ${joints.length} floats, too few for its joints`);
649
+ const { node, restPosition, restQuaternion, restScale } = binding;
650
+ this.#translation.set(
651
+ joints[at],
652
+ joints[at + 1],
653
+ joints[at + 2]
654
+ );
655
+ this.#rotation.set(
656
+ joints[at + 3],
657
+ joints[at + 4],
658
+ joints[at + 5],
659
+ joints[at + 6]
660
+ );
661
+ this.#deltaScale.set(
662
+ joints[at + 7],
663
+ joints[at + 8],
664
+ joints[at + 9]
665
+ );
666
+ this.#basis.vector(this.#translation, node.position).add(restPosition);
667
+ this.#basis.quaternion(this.#rotation, this.#deltaRotation);
668
+ node.quaternion.copy(restQuaternion).multiply(this.#deltaRotation);
669
+ this.#basis.scaleTriple(this.#deltaScale, node.scale).add(restScale);
670
+ }
671
+ const shapes = evaluator.blendShapeOutputs();
672
+ for (const morph of this.#morphs) {
673
+ const weight = shapes[morph.channel];
674
+ if (weight === void 0)
675
+ fail2("TN_MH_LENGTH", `the rig returned ${shapes.length} blend shape weights`);
676
+ if (morph.lod === this.#lod) setInfluence(morph, weight);
677
+ }
678
+ this.#mapWeights.set(evaluator.animatedMapOutputs());
679
+ }
680
+ };
681
+ async function createMetaHuman(backend, options) {
682
+ const { assets, model, dna, bindings: bindingsPath } = checkOptions(options);
683
+ const [dnaBytes, bindingsBytes] = await Promise.all([
684
+ readBytes(assets, dna),
685
+ readBytes(assets, bindingsPath)
686
+ ]);
687
+ let parsed;
688
+ try {
689
+ parsed = JSON.parse(new TextDecoder().decode(bindingsBytes));
690
+ } catch (error) {
691
+ return fail2(
692
+ "TN_MH_SCHEMA",
693
+ `'${bindingsPath}' is not JSON: ${error instanceof Error ? error.message : String(error)}`
694
+ );
695
+ }
696
+ const evaluator = await backend.create(dnaBytes);
697
+ try {
698
+ const loaded = await assets.model(model);
699
+ const gltf = gltfFactsOf(loaded);
700
+ const rig = {
701
+ gui: evaluator.names("gui"),
702
+ raw: evaluator.names("raw"),
703
+ joints: evaluator.names("joint"),
704
+ blendShapes: evaluator.names("blendShape"),
705
+ animatedMaps: evaluator.names("animatedMap"),
706
+ lodCount: evaluator.counts().lodCount
707
+ };
708
+ const bindings = validateMetaHumanAssets({
709
+ bindings: parsed,
710
+ dnaSha256: await sha256Hex(dnaBytes),
711
+ rig,
712
+ gltf
713
+ });
714
+ return new MetaHuman({
715
+ loader: loaded,
716
+ evaluator,
717
+ bindings,
718
+ backend: backend.name,
719
+ openRigLogic: await backend.openRigLogic(),
720
+ lod: options.lod ?? 0
721
+ });
722
+ } catch (error) {
723
+ evaluator.dispose();
724
+ throw error;
725
+ }
726
+ }
727
+ function checkOptions(options) {
728
+ if (!isRecord(options)) fail2("TN_MH_SCHEMA", "loadMetaHuman requires an options object");
729
+ for (const [name, value] of [
730
+ ["model", options.model],
731
+ ["dna", options.dna],
732
+ ["bindings", options.bindings]
733
+ ])
734
+ if (typeof value !== "string" || value.length === 0)
735
+ fail2("TN_MH_SCHEMA", `${name} must be a non-empty logical asset path`);
736
+ if (typeof options.assets?.model !== "function" || typeof options.assets?.resolve !== "function")
737
+ fail2("TN_MH_SCHEMA", "assets must be the game's asset loader (model and resolve)");
738
+ if (options.lod !== void 0 && !Number.isInteger(options.lod))
739
+ fail2("TN_MH_BAD_LOD", `lod ${String(options.lod)} is not an integer`);
740
+ return options;
741
+ }
742
+
743
+ // src/native/host.ts
744
+ function nativeGlobal() {
745
+ return globalThis.__THREENATIVE_NATIVE__;
746
+ }
747
+ function nativeMetaHumanHost() {
748
+ const host = installedNativeMetaHumanHost();
749
+ if (host === void 0)
750
+ throw new Error("TN_NATIVE_METAHUMAN_MISSING: runtime did not install the metahuman ABI");
751
+ return host;
752
+ }
753
+ function installedNativeMetaHumanHost() {
754
+ const host = nativeGlobal()?.metahuman;
755
+ if (host === void 0 || typeof host.version !== "string" || typeof host.create !== "function")
756
+ return void 0;
757
+ return host;
758
+ }
759
+
760
+ // src/native/native-evaluator.ts
761
+ var KIND_SELECTORS = {
762
+ gui: 0,
763
+ raw: 1,
764
+ joint: 2,
765
+ blendShape: 3,
766
+ animatedMap: 4,
767
+ lod: 5
768
+ };
769
+ var NativeRigEvaluator = class _NativeRigEvaluator {
770
+ #host;
771
+ #handle;
772
+ #disposed = false;
773
+ constructor(host, dna) {
774
+ this.#host = host;
775
+ this.#handle = host.create(dna);
776
+ }
777
+ /** Parse a DNA blob. The host copies the bytes, so the caller keeps its buffer. */
778
+ static create(dna, host = nativeMetaHumanHost()) {
779
+ if (dna instanceof Uint8Array ? dna.length === 0 : dna.byteLength === 0)
780
+ throw new MetaHumanAssetError("TN_MH_LENGTH", "dna must be a non-empty buffer");
781
+ return new _NativeRigEvaluator(host, dna);
782
+ }
783
+ /** The backend and pinned OpenRigLogic revision the host was built from. */
784
+ backend() {
785
+ return this.#live().version;
786
+ }
787
+ /**
788
+ * Live evaluator handles in the host process, across every instance of this class.
789
+ *
790
+ * The count a create/dispose cycle must return to, read from the ABI's own registry.
791
+ */
792
+ static liveHandleCount(host = nativeMetaHumanHost()) {
793
+ return host.liveCount();
794
+ }
795
+ #live() {
796
+ if (this.#disposed)
797
+ throw new MetaHumanAssetError("TN_MH_DISPOSED", "the evaluator is disposed");
798
+ return this.#host;
799
+ }
800
+ #count(kind) {
801
+ return this.#live().count(this.#handle, KIND_SELECTORS[kind]);
802
+ }
803
+ counts() {
804
+ return Object.freeze({
805
+ gui: this.#count("gui"),
806
+ raw: this.#count("raw"),
807
+ joints: this.#count("joint"),
808
+ blendShapes: this.#count("blendShape"),
809
+ animatedMaps: this.#count("animatedMap"),
810
+ lodCount: this.#count("lod")
811
+ });
812
+ }
813
+ names(kind) {
814
+ const host = this.#live();
815
+ const count = this.#count(kind);
816
+ const names = [];
817
+ for (let index2 = 0; index2 < count; index2 += 1)
818
+ names.push(host.name(this.#handle, KIND_SELECTORS[kind], index2));
819
+ return Object.freeze(names);
820
+ }
821
+ setLod(lod) {
822
+ if (!Number.isInteger(lod) || lod < 0 || lod >= this.#count("lod"))
823
+ throw new MetaHumanAssetError("TN_MH_INDEX_RANGE", `lod ${lod} is outside this rig`);
824
+ this.#live().setLod(this.#handle, lod);
825
+ }
826
+ setGuiControls(values) {
827
+ this.#setControls("gui", values);
828
+ }
829
+ setRawControls(values) {
830
+ this.#setControls("raw", values);
831
+ }
832
+ #setControls(kind, values) {
833
+ const host = this.#live();
834
+ const expected = this.#count(kind);
835
+ if (values.length !== expected)
836
+ throw new MetaHumanAssetError(
837
+ "TN_MH_LENGTH",
838
+ `${kind} controls need ${expected} values, got ${values.length}`
839
+ );
840
+ for (let index2 = 0; index2 < values.length; index2 += 1) {
841
+ if (!Number.isFinite(values[index2]))
842
+ throw new MetaHumanAssetError("TN_MH_NON_FINITE", `${kind} control ${index2} is not finite`);
843
+ }
844
+ if (kind === "gui") host.setGui(this.#handle, values);
845
+ else host.setRaw(this.#handle, values);
846
+ }
847
+ evaluate(useGui) {
848
+ this.#live().evaluate(this.#handle, useGui);
849
+ }
850
+ jointOutputs() {
851
+ return this.#live().jointOutputs(this.#handle);
852
+ }
853
+ blendShapeOutputs() {
854
+ return this.#live().blendShapeOutputs(this.#handle);
855
+ }
856
+ animatedMapOutputs() {
857
+ return this.#live().animatedMapOutputs(this.#handle);
858
+ }
859
+ neutralJoints() {
860
+ return this.#live().neutralJoints(this.#handle);
861
+ }
862
+ dispose() {
863
+ if (this.#disposed) return;
864
+ this.#disposed = true;
865
+ this.#host.destroy(this.#handle);
866
+ }
867
+ };
868
+
869
+ // src/native/index.ts
870
+ var loadMetaHuman = (options) => createMetaHuman(
871
+ {
872
+ name: "native",
873
+ create: (dna) => NativeRigEvaluator.create(dna),
874
+ openRigLogic: () => nativeMetaHumanHost().version
875
+ },
876
+ options
877
+ );
878
+
879
+ export { METAHUMAN_BINDINGS_SCHEMA_VERSION, MetaHumanAssetError, NativeRigEvaluator, assertAssetPath, loadMetaHuman, nativeMetaHumanHost, validateMetaHumanAssets };