@margoengine/rigging 0.0.0-stage → 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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +969 -3
  4. package/dist/autorig.d.ts +50 -0
  5. package/dist/autorig.js +660 -0
  6. package/dist/bar-grip.d.ts +7 -0
  7. package/dist/checks.d.ts +50 -0
  8. package/dist/contact.d.ts +175 -0
  9. package/dist/contact.js +739 -0
  10. package/dist/correctives.d.ts +92 -0
  11. package/dist/correctives.js +162 -0
  12. package/dist/errors-D8rc8kzg.js +7 -0
  13. package/dist/face.d.ts +93 -0
  14. package/dist/face.js +144 -0
  15. package/dist/hands.d.ts +209 -0
  16. package/dist/hands.js +510 -0
  17. package/dist/heat.d.ts +38 -0
  18. package/dist/hinged-contact.d.ts +7 -0
  19. package/dist/hulls.d.ts +54 -0
  20. package/dist/hulls.js +134 -0
  21. package/dist/ik.d.ts +109 -0
  22. package/dist/ik.js +358 -0
  23. package/dist/index.d.ts +6 -0
  24. package/dist/index.js +390 -0
  25. package/dist/joint-limits.d.ts +44 -0
  26. package/dist/joint-limits.js +74 -0
  27. package/dist/limb-collision.d.ts +99 -0
  28. package/dist/loading-CZaYr1N7.js +67 -0
  29. package/dist/mesh-CyvLHNp0.js +142 -0
  30. package/dist/mesh.d.ts +47 -0
  31. package/dist/mtoon-data.d.ts +118 -0
  32. package/dist/mtoon-legacy.d.ts +17 -0
  33. package/dist/mtoon-shader.d.ts +4 -0
  34. package/dist/mtoon.d.ts +84 -0
  35. package/dist/mtoon.js +990 -0
  36. package/dist/paint.d.ts +82 -0
  37. package/dist/pose-tracking.d.ts +117 -0
  38. package/dist/pose-tracking.js +488 -0
  39. package/dist/retarget.d.ts +71 -0
  40. package/dist/retarget.js +351 -0
  41. package/dist/rig-BawZ5OLb.js +127 -0
  42. package/dist/rig.d.ts +65 -0
  43. package/dist/shared/gltf.d.ts +257 -0
  44. package/dist/shared/layers.d.ts +16 -0
  45. package/dist/springs.d.ts +180 -0
  46. package/dist/springs.js +458 -0
  47. package/dist/strand-springs.d.ts +46 -0
  48. package/dist/strand-springs.js +168 -0
  49. package/dist/swim.d.ts +55 -0
  50. package/dist/swim.js +167 -0
  51. package/dist/transfer.d.ts +41 -0
  52. package/dist/transfer.js +136 -0
  53. package/dist/voxel-weights-48ok-Dax.js +255 -0
  54. package/dist/voxel-weights.d.ts +42 -0
  55. package/dist/voxel-weights.js +1 -0
  56. package/dist/voxels.d.ts +36 -0
  57. package/dist/vrm-constraints.d.ts +60 -0
  58. package/dist/vrm-constraints.js +261 -0
  59. package/dist/vrm-first-person.d.ts +115 -0
  60. package/dist/vrm-first-person.js +618 -0
  61. package/dist/vrm-presets-CU4V4yq6.js +47 -0
  62. package/dist/vrm-presets.d.ts +1 -0
  63. package/dist/vrm.d.ts +298 -0
  64. package/dist/vrm.js +574 -0
  65. package/dist/vrm0.d.ts +134 -0
  66. package/dist/vrm0.js +377 -0
  67. package/dist/vrma.d.ts +90 -0
  68. package/dist/vrma.js +315 -0
  69. package/dist/weight-map-D8cAONQQ.js +92 -0
  70. package/dist/weight-map.d.ts +58 -0
  71. package/package.json +175 -6
@@ -0,0 +1,92 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Animator } from '@margoengine/animator';
3
+ /** A morph target of a model: glTF node with the mesh, and target index. */
4
+ export interface ShapeTarget {
5
+ /** glTF node index of the mesh. */
6
+ node: number;
7
+ /** Morph target index. */
8
+ target: number;
9
+ }
10
+ /** A shape driven by one joint's rotation toward one pose: elbows and knees. */
11
+ export interface CorrectiveShape extends ShapeTarget {
12
+ /** The driving bone (glTF node index with {@link addCorrectives}). */
13
+ joint: number;
14
+ /** The joint's local rotation at which the shape is full, quaternion xyzw. */
15
+ pose: readonly number[];
16
+ /** The joint's local rotation at which the shape is off. Default its rest rotation, or identity with no rig. */
17
+ rest?: readonly number[];
18
+ /**
19
+ * How far from the line from `rest` to `pose` the joint can go, radians, before the shape fades out. Default none:
20
+ * only the bend along that line counts, so a hinge's twist does nothing.
21
+ */
22
+ cone?: number | null;
23
+ /** Reading at which the shape starts, 0 to below 1 (default 0): 0.5 keeps it off for the first half of the bend. */
24
+ start?: number;
25
+ /** `smooth` eases in and out, `linear` follows the angle (default). */
26
+ curve?: 'linear' | 'smooth';
27
+ /** Weight at full bend, 0 to 1 (default 1). */
28
+ amount?: number;
29
+ }
30
+ /** A pose of a {@link PoseSpace}. */
31
+ export interface PoseSample {
32
+ /** The joint's local rotation, quaternion xyzw. */
33
+ rotation: readonly number[];
34
+ /** Weight of each of the space's `shapes`, by position, at this pose. */
35
+ weights: readonly number[];
36
+ }
37
+ /** Several shapes driven together by a joint that swings every way: shoulders and hips. */
38
+ export interface PoseSpace {
39
+ /** The driving bone. */
40
+ joint: number;
41
+ /** The shapes the samples mix. */
42
+ shapes: readonly ShapeTarget[];
43
+ /** Sculpted poses, 1 to 64. Include the rest pose with zero weights, or the shapes hold outside the samples. */
44
+ samples: readonly PoseSample[];
45
+ /** Gaussian width, radians. Default the mean angle from each sample to its nearest neighbour. */
46
+ width?: number;
47
+ }
48
+ /** What {@link Correctives} drives. */
49
+ export interface CorrectivesOptions {
50
+ shapes?: readonly CorrectiveShape[];
51
+ spaces?: readonly PoseSpace[];
52
+ }
53
+ /** One morph weight. */
54
+ export interface ShapeWeight extends ShapeTarget {
55
+ weight: number;
56
+ }
57
+ /**
58
+ * Shape weights from joint rotations, as plain data: no engine or GPU. {@link addCorrectives} runs it on a model.
59
+ * Shapes are read every call, so settings change live; pose spaces are solved once, here.
60
+ */
61
+ export declare class Correctives {
62
+ readonly options: CorrectivesOptions;
63
+ private readonly spaces;
64
+ /**
65
+ * @param options what to drive.
66
+ * @throws RangeError for bad poses, samples or settings.
67
+ */
68
+ constructor(options: CorrectivesOptions);
69
+ private check;
70
+ /** How far `rotation` has gone from `shape.rest` to `shape.pose`, with the shape's settings: the shape's weight. */
71
+ private reading;
72
+ /**
73
+ * Every driven shape's weight. Shapes on one target add up, then clamp to 0 to 1.
74
+ * @param rotationOf the current local rotation of a joint.
75
+ * @param restOf a joint's rest rotation, for shapes with no `rest`. Default identity.
76
+ */
77
+ evaluate(rotationOf: (joint: number) => readonly number[], restOf?: (joint: number) => readonly number[]): ShapeWeight[];
78
+ }
79
+ /** A running {@link addCorrectives}. */
80
+ export interface CorrectivesHandle {
81
+ readonly correctives: Correctives;
82
+ /** Stops driving and sets the shapes to 0. */
83
+ dispose(): void;
84
+ [Symbol.dispose](): void;
85
+ }
86
+ /**
87
+ * Drives corrective shapes on `animator` (`@margoengine/animator`), every frame after the pose and the solvers added
88
+ * before it, so IK and foot placement count. Joints and mesh nodes are glTF node indices of the animator's model. A
89
+ * driven morph target belongs to this: a clip's track on the same target is overwritten. Returns the handle.
90
+ * @throws RangeError for bad settings or a target the model lacks.
91
+ */
92
+ export declare function addCorrectives(animator: Animator, options: CorrectivesOptions): CorrectivesHandle;
@@ -0,0 +1,162 @@
1
+ import { multiplyQuaternions as e, normalizeQuaternion as t } from "@margoengine/math/quat";
2
+ //#region src/correctives.ts
3
+ var n = [
4
+ 0,
5
+ 0,
6
+ 0,
7
+ 1
8
+ ], r = (e) => [
9
+ -e[0],
10
+ -e[1],
11
+ -e[2],
12
+ e[3]
13
+ ];
14
+ function i(e, t) {
15
+ let n = e;
16
+ if (!n || n.length !== 4) throw RangeError(`${t} must be a quaternion: four numbers, x y z w`);
17
+ for (let e = 0; e < 4; e++) if (!Number.isFinite(n[e])) throw RangeError(`${t} must be finite`);
18
+ if (!(Math.hypot(n[0], n[1], n[2], n[3]) > 0)) throw RangeError(`${t} must not be all zeros`);
19
+ }
20
+ function a(e) {
21
+ let t = e[3] < 0 ? -1 : 1, n = Math.hypot(e[0], e[1], e[2]), r = 2 * Math.atan2(n, e[3] * t);
22
+ if (n < 1e-12) return [
23
+ 0,
24
+ 0,
25
+ 0
26
+ ];
27
+ let i = t * r / n;
28
+ return [
29
+ e[0] * i,
30
+ e[1] * i,
31
+ e[2] * i
32
+ ];
33
+ }
34
+ var o = (e, t) => 2 * Math.acos(Math.min(1, Math.abs(e[0] * t[0] + e[1] * t[1] + e[2] * t[2] + e[3] * t[3])));
35
+ function s(e, t, n, r) {
36
+ for (let i = 0; i < n; i++) {
37
+ let a = i;
38
+ for (let t = i + 1; t < n; t++) Math.abs(e[t * n + i]) > Math.abs(e[a * n + i]) && (a = t);
39
+ if (Math.abs(e[a * n + i]) < 1e-12) throw RangeError("Pose samples repeat; give each sample a different rotation");
40
+ if (a !== i) {
41
+ for (let t = 0; t < n; t++) [e[i * n + t], e[a * n + t]] = [e[a * n + t], e[i * n + t]];
42
+ for (let e = 0; e < r; e++) [t[i * r + e], t[a * r + e]] = [t[a * r + e], t[i * r + e]];
43
+ }
44
+ for (let a = 0; a < n; a++) {
45
+ if (a === i) continue;
46
+ let o = e[a * n + i] / e[i * n + i];
47
+ if (o !== 0) {
48
+ for (let t = i; t < n; t++) e[a * n + t] -= o * e[i * n + t];
49
+ for (let e = 0; e < r; e++) t[a * r + e] -= o * t[i * r + e];
50
+ }
51
+ }
52
+ }
53
+ for (let i = 0; i < n; i++) for (let a = 0; a < r; a++) t[i * r + a] /= e[i * n + i];
54
+ }
55
+ function c(e) {
56
+ let { samples: n, shapes: r } = e, a = n?.length, c = r?.length;
57
+ if (!Array.isArray(n) || a < 1 || a > 64) throw RangeError("A pose space needs 1 to 64 samples");
58
+ if (!Array.isArray(r) || !c) throw RangeError("A pose space needs at least one shape");
59
+ let l = n.map((e, n) => {
60
+ if (i(e?.rotation, `Pose sample ${n} rotation`), e.weights?.length !== c || !e.weights.every(Number.isFinite)) throw RangeError(`Pose sample ${n} needs one finite weight per shape`);
61
+ return t([...e.rotation]);
62
+ }), u = e.width;
63
+ if (u === void 0) {
64
+ let e = 0;
65
+ l.forEach((t, n) => {
66
+ let r = Infinity;
67
+ l.forEach((e, i) => {
68
+ n !== i && (r = Math.min(r, o(t, e)));
69
+ }), e += r === Infinity ? 1 : r;
70
+ }), u = e / a;
71
+ }
72
+ if (!(u > 0 && u < Infinity)) throw RangeError("Pose space width must be above 0; separate the samples");
73
+ let d = new Float64Array(a * a), f = new Float64Array(a * c);
74
+ for (let e = 0; e < a; e++) {
75
+ for (let t = 0; t < a; t++) d[e * a + t] = Math.exp(-((o(l[e], l[t]) / u) ** 2));
76
+ for (let t = 0; t < c; t++) f[e * c + t] = n[e].weights[t];
77
+ }
78
+ return s(d, f, a, c), {
79
+ spec: e,
80
+ rotations: l,
81
+ width: u,
82
+ coefficients: f
83
+ };
84
+ }
85
+ var l = (e) => e < 0 ? 0 : e > 1 ? 1 : e, u = class {
86
+ constructor(e) {
87
+ this.options = e, this.spaces = (e?.spaces ?? []).map(c), this.check();
88
+ }
89
+ check() {
90
+ for (let e of this.options?.shapes ?? []) {
91
+ i(e?.pose, "Corrective pose"), e.rest !== void 0 && i(e.rest, "Corrective rest");
92
+ let { cone: t = null, start: n = 0, curve: r = "linear", amount: a = 1 } = e;
93
+ if (t !== null && !(t > 0 && t < Infinity)) throw RangeError("Corrective cone must be above 0");
94
+ if (!(n >= 0 && n < 1)) throw RangeError("Corrective start must be from 0 to below 1");
95
+ if (r !== "linear" && r !== "smooth") throw RangeError("Corrective curve must be 'linear' or 'smooth'");
96
+ if (!(a >= 0 && a <= 1)) throw RangeError("Corrective amount must be from 0 to 1");
97
+ }
98
+ }
99
+ reading(n, i, o) {
100
+ let s = r(n.rest ?? o), c = a(t(e(s, n.pose))), u = a(t(e(s, i))), d = c[0] ** 2 + c[1] ** 2 + c[2] ** 2;
101
+ if (!(d > 0)) throw RangeError("A corrective pose must differ from its rest; turn the joint");
102
+ let f = (u[0] * c[0] + u[1] * c[1] + u[2] * c[2]) / d, { start: p = 0, curve: m = "linear", amount: h = 1, cone: g = null } = n, _ = l((f - p) / (1 - p));
103
+ if (m === "smooth" && (_ = _ * _ * (3 - 2 * _)), g !== null) {
104
+ let e = l(1 - Math.hypot(u[0] - c[0] * f, u[1] - c[1] * f, u[2] - c[2] * f) / g);
105
+ _ *= e * e * (3 - 2 * e);
106
+ }
107
+ return _ * h;
108
+ }
109
+ evaluate(e, r = () => n) {
110
+ this.check();
111
+ let i = /* @__PURE__ */ new Map(), a = (e, t) => {
112
+ let n = `${e.node}:${e.target}`, r = i.get(n) ?? {
113
+ node: e.node,
114
+ target: e.target,
115
+ weight: 0
116
+ };
117
+ i.set(n, r), r.weight += t;
118
+ };
119
+ for (let t of this.options.shapes ?? []) a(t, this.reading(t, e(t.joint), r(t.joint)));
120
+ for (let { spec: n, rotations: r, width: i, coefficients: s } of this.spaces) {
121
+ let c = t([...e(n.joint)]), l = n.shapes.length, u = new Float64Array(l);
122
+ r.forEach((e, t) => {
123
+ let n = Math.exp(-((o(c, e) / i) ** 2));
124
+ for (let e = 0; e < l; e++) u[e] += n * s[t * l + e];
125
+ }), n.shapes.forEach((e, t) => a(e, u[t]));
126
+ }
127
+ for (let e of i.values()) e.weight = l(e.weight);
128
+ return [...i.values()];
129
+ }
130
+ };
131
+ function d(e, t) {
132
+ let n = new u(t), r = e.animation, i = r.model.nodes, a = r.model.root.engine.store.transforms, o = (e) => {
133
+ let t = i[e];
134
+ if (!t) throw RangeError(`Corrective joint ${e} is not a node of this model; pass a glTF node index`);
135
+ let n = t.id;
136
+ return [
137
+ a.qx[n],
138
+ a.qy[n],
139
+ a.qz[n],
140
+ a.qw[n]
141
+ ];
142
+ }, s = (t) => e.restRotation(t), c = n.evaluate(o, s);
143
+ for (let { node: e, target: t } of c) r.setMorph(e, t, 0);
144
+ let l = e.addSolver(() => {
145
+ c = n.evaluate(o, s);
146
+ for (let { node: e, target: t, weight: n } of c) r.setMorph(e, t, n);
147
+ }), d = () => {
148
+ l?.(), l = null, f?.(), f = null;
149
+ }, f = r.model.onDispose(d), p = () => {
150
+ if (l) {
151
+ d();
152
+ for (let { node: e, target: t } of c) r.setMorph(e, t, 0);
153
+ }
154
+ };
155
+ return {
156
+ correctives: n,
157
+ dispose: p,
158
+ [Symbol.dispose]: p
159
+ };
160
+ }
161
+ //#endregion
162
+ export { u as Correctives, d as addCorrectives };
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => TypeError(t(e, n)), i = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { r as i, e as n, i as r, n as t };
package/dist/face.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Animator } from '@margoengine/animator';
3
+ import type { VRMHandle } from './vrm.js';
4
+ /** The 52 face shapes, in the order of Apple's documentation. Left and right are the face's own. */
5
+ export declare const FACE_SHAPES: readonly ['eyeBlinkLeft', 'eyeLookDownLeft', 'eyeLookInLeft', 'eyeLookOutLeft', 'eyeLookUpLeft', 'eyeSquintLeft', 'eyeWideLeft', 'eyeBlinkRight', 'eyeLookDownRight', 'eyeLookInRight', 'eyeLookOutRight', 'eyeLookUpRight', 'eyeSquintRight', 'eyeWideRight', 'jawForward', 'jawLeft', 'jawRight', 'jawOpen', 'mouthClose', 'mouthFunnel', 'mouthPucker', 'mouthLeft', 'mouthRight', 'mouthSmileLeft', 'mouthSmileRight', 'mouthFrownLeft', 'mouthFrownRight', 'mouthDimpleLeft', 'mouthDimpleRight', 'mouthStretchLeft', 'mouthStretchRight', 'mouthRollLower', 'mouthRollUpper', 'mouthShrugLower', 'mouthShrugUpper', 'mouthPressLeft', 'mouthPressRight', 'mouthLowerDownLeft', 'mouthLowerDownRight', 'mouthUpperUpLeft', 'mouthUpperUpRight', 'browDownLeft', 'browDownRight', 'browInnerUp', 'browOuterUpLeft', 'browOuterUpRight', 'cheekPuff', 'cheekSquintLeft', 'cheekSquintRight', 'noseSneerLeft', 'noseSneerRight', 'tongueOut'];
6
+ /** One of the {@link FACE_SHAPES}. */
7
+ export type FaceShape = (typeof FACE_SHAPES)[number];
8
+ /**
9
+ * One tracker frame: a record of shape names to values, or a list of `{ categoryName, score }` as MediaPipe's
10
+ * `faceBlendshapes[0].categories` gives. Names need not match exactly (see {@link faceShapeOf}); others are ignored.
11
+ */
12
+ export type FaceFrame = Readonly<Record<string, number>> | readonly {
13
+ categoryName: string;
14
+ score: number;
15
+ }[];
16
+ /** Options of {@link FaceMapper}. */
17
+ export interface FaceMapperOptions {
18
+ /** Time constant of the smoothing, seconds; 0 follows the tracker exactly (default 0.05). */
19
+ smoothing?: number;
20
+ /** Multiplies values before they clamp to 0 to 1: one number for all, or per shape, the rest at 1 (default 1). */
21
+ gain?: number | Partial<Record<FaceShape, number>>;
22
+ /** Swaps left and right, for a tracker fed by a mirrored camera (default false). */
23
+ mirror?: boolean;
24
+ }
25
+ /**
26
+ * The face shape a name stands for, or null. Ignores case, separators and anything before the shape, so
27
+ * `EyeBlinkLeft`, `eye_blink_left`, `eyeBlink_L` and `blendShape1.ARKit_eyeBlinkLeft` all read as `eyeBlinkLeft`.
28
+ */
29
+ export declare function faceShapeOf(name: string): FaceShape | null;
30
+ /**
31
+ * A tracker's frames as smoothed shape values, plain data with no engine: {@link addFace} runs one on a model. Settings
32
+ * can be changed between frames.
33
+ */
34
+ export declare class FaceMapper {
35
+ /** The 52 current values, in {@link FACE_SHAPES} order. */
36
+ readonly values: Float32Array<ArrayBuffer>;
37
+ /** Seconds; see {@link FaceMapperOptions.smoothing}. */
38
+ smoothing: number;
39
+ /** See {@link FaceMapperOptions.gain}. */
40
+ gain: number | Partial<Record<FaceShape, number>>;
41
+ /** See {@link FaceMapperOptions.mirror}. */
42
+ mirror: boolean;
43
+ private readonly target;
44
+ constructor(options?: FaceMapperOptions);
45
+ private check;
46
+ private take;
47
+ /** Takes a tracker's latest frame; shapes it leaves out hold their value. Pass null when tracking is lost: all go to 0. */
48
+ push(frame: FaceFrame | null): this;
49
+ /** Moves `values` toward the last frame by `delta` seconds, the same at any frame rate. */
50
+ update(delta: number): this;
51
+ /** The current value of `shape`. */
52
+ get(shape: FaceShape): number;
53
+ /** Back to neutral at once. */
54
+ reset(): this;
55
+ }
56
+ /**
57
+ * VRM 1.0 preset expressions from the 52 values. Blinks are split so `blink` holds what both eyes share and
58
+ * `blinkLeft`, `blinkRight` the rest; the look presets are the two eyes' mean. The tracker has no reading for `relaxed`,
59
+ * so it stays out. `get` is a {@link FaceMapper}'s `get`, bound.
60
+ */
61
+ export declare function vrmFaceExpressions(get: (shape: FaceShape) => number): Record<string, number>;
62
+ /** Options of {@link addFace}. */
63
+ export interface AddFaceOptions extends FaceMapperOptions {
64
+ /** Run inside this `Animator`, after its pose; with none, run as an engine plugin. */
65
+ animator?: Animator;
66
+ /** Drive this avatar's expressions rather than morph targets by name. */
67
+ vrm?: VRMHandle;
68
+ /** Morph target names for shapes the names alone do not find: `{ jawOpen: 'Mouth_Open', eyeBlinkLeft: ['A', 'B'] }`. */
69
+ map?: Partial<Record<FaceShape, string | readonly string[]>>;
70
+ }
71
+ /** A running {@link addFace}. */
72
+ export interface FaceHandle {
73
+ readonly mapper: FaceMapper;
74
+ /** Shapes that drive something on this model. Empty with `vrm`, which goes through expressions. */
75
+ readonly matched: readonly FaceShape[];
76
+ /** Shapes with nothing to drive. */
77
+ readonly missing: readonly FaceShape[];
78
+ /** Takes the tracker's latest frame; see {@link FaceMapper.push}. */
79
+ push(frame: FaceFrame | null): void;
80
+ /** Runs one frame by hand; the Animator or the engine does this each frame by itself. */
81
+ update(delta: number): void;
82
+ /** Puts the face back to neutral and stops. */
83
+ dispose(): void;
84
+ [Symbol.dispose](): void;
85
+ }
86
+ /**
87
+ * Drives a character's face from a tracker: call `push` with each tracker frame, at the tracker's own rate. Morph
88
+ * targets are found on every mesh of the model by the names in `extras.targetNames`, so head, teeth and lashes move
89
+ * together; pass `map` for other names, or `vrm` for an avatar. A driven morph target belongs to this: a clip's track
90
+ * on it is overwritten.
91
+ * @throws MargoError (code `state`) when nothing on the model matches or the model already has a live face; RangeError for bad settings.
92
+ */
93
+ export declare function addFace(animation: Animator['animation'], options?: AddFaceOptions): FaceHandle;
package/dist/face.js ADDED
@@ -0,0 +1,144 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { MargoError as e } from "@margoengine/math/errors";
5
+ //#region src/face.ts
6
+ var t = /* @__PURE__ */ "eyeBlinkLeft.eyeLookDownLeft.eyeLookInLeft.eyeLookOutLeft.eyeLookUpLeft.eyeSquintLeft.eyeWideLeft.eyeBlinkRight.eyeLookDownRight.eyeLookInRight.eyeLookOutRight.eyeLookUpRight.eyeSquintRight.eyeWideRight.jawForward.jawLeft.jawRight.jawOpen.mouthClose.mouthFunnel.mouthPucker.mouthLeft.mouthRight.mouthSmileLeft.mouthSmileRight.mouthFrownLeft.mouthFrownRight.mouthDimpleLeft.mouthDimpleRight.mouthStretchLeft.mouthStretchRight.mouthRollLower.mouthRollUpper.mouthShrugLower.mouthShrugUpper.mouthPressLeft.mouthPressRight.mouthLowerDownLeft.mouthLowerDownRight.mouthUpperUpLeft.mouthUpperUpRight.browDownLeft.browDownRight.browInnerUp.browOuterUpLeft.browOuterUpRight.cheekPuff.cheekSquintLeft.cheekSquintRight.noseSneerLeft.noseSneerRight.tongueOut".split("."), n = new Map(t.map((e, t) => [e, t])), r = (e) => e.replace(/[^a-zA-Z0-9]/g, "").toLowerCase(), i = t.flatMap((e) => {
7
+ let t = r(e), n = t.replace(/left$/, "l").replace(/right$/, "r");
8
+ return n === t ? [[t, e]] : [[t, e], [n, e]];
9
+ }).sort((e, t) => t[0].length - e[0].length);
10
+ function a(e) {
11
+ if (n.has(e)) return e;
12
+ let t = r(e);
13
+ for (let [e, n] of i) if (t.endsWith(e)) return n;
14
+ return null;
15
+ }
16
+ function o(e) {
17
+ return e.endsWith("Left") ? `${e.slice(0, -4)}Right` : e.endsWith("Right") ? `${e.slice(0, -5)}Left` : e;
18
+ }
19
+ var s = t.map((e) => n.get(o(e))), c = (e) => e < 0 ? 0 : e > 1 ? 1 : e, l = class {
20
+ constructor(e = {}) {
21
+ this.values = new Float32Array(t.length), this.target = new Float32Array(t.length), this.smoothing = e.smoothing ?? .05, this.gain = e.gain ?? 1, this.mirror = e.mirror ?? !1, this.check();
22
+ }
23
+ check() {
24
+ let { smoothing: e, gain: t } = this;
25
+ if (!(e >= 0 && e < Infinity)) throw RangeError("Face smoothing must be 0 or more seconds");
26
+ if (typeof t == "number") {
27
+ if (!(t >= 0 && t < Infinity)) throw RangeError("Face gain must be finite and 0 or more");
28
+ } else if (typeof t != "object" || !t) throw TypeError("Face gain must be a number or a record");
29
+ else for (let [e, r] of Object.entries(t)) {
30
+ if (!n.has(e)) throw RangeError(`Face gain names ${e}; use a name from FACE_SHAPES`);
31
+ if (!(r >= 0 && r < Infinity)) throw RangeError(`Face gain of ${e} must be finite and 0 or more`);
32
+ }
33
+ }
34
+ take(e, t) {
35
+ let r = a(e);
36
+ if (r === null) return;
37
+ if (!Number.isFinite(t)) throw RangeError(`Face value of ${e} must be finite`);
38
+ let i = typeof this.gain == "number" ? this.gain : this.gain[r] ?? 1, o = n.get(r);
39
+ this.target[this.mirror ? s[o] : o] = c(t * i);
40
+ }
41
+ push(e) {
42
+ if (this.check(), e === null) this.target.fill(0);
43
+ else if (Array.isArray(e)) for (let t of e) this.take(t.categoryName, t.score);
44
+ else if (typeof e == "object") for (let [t, n] of Object.entries(e)) this.take(t, n);
45
+ else throw TypeError("A face frame must be a record, a list of {categoryName, score}, or null");
46
+ return this;
47
+ }
48
+ update(e) {
49
+ if (!(e >= 0 && e < Infinity)) throw RangeError("Face update delta must be 0 or more seconds");
50
+ this.check();
51
+ let t = this.smoothing === 0 ? 1 : 1 - Math.exp(-e / this.smoothing);
52
+ for (let e = 0; e < this.values.length; e++) this.values[e] += (this.target[e] - this.values[e]) * t;
53
+ return this;
54
+ }
55
+ get(e) {
56
+ let t = n.get(e);
57
+ if (t === void 0) throw RangeError(`Unknown face shape ${e}; use a name from FACE_SHAPES`);
58
+ return this.values[t];
59
+ }
60
+ reset() {
61
+ return this.values.fill(0), this.target.fill(0), this;
62
+ }
63
+ };
64
+ function u(e) {
65
+ let t = (t, n) => (e(t) + e(n)) / 2, n = e("eyeBlinkLeft"), r = e("eyeBlinkRight"), i = Math.min(n, r);
66
+ return {
67
+ blink: i,
68
+ blinkLeft: n - i,
69
+ blinkRight: r - i,
70
+ lookUp: t("eyeLookUpLeft", "eyeLookUpRight"),
71
+ lookDown: t("eyeLookDownLeft", "eyeLookDownRight"),
72
+ lookLeft: t("eyeLookOutLeft", "eyeLookInRight"),
73
+ lookRight: t("eyeLookInLeft", "eyeLookOutRight"),
74
+ aa: e("jawOpen"),
75
+ ih: t("mouthLowerDownLeft", "mouthLowerDownRight"),
76
+ ou: e("mouthPucker"),
77
+ ee: t("mouthStretchLeft", "mouthStretchRight"),
78
+ oh: e("mouthFunnel"),
79
+ happy: t("mouthSmileLeft", "mouthSmileRight"),
80
+ sad: t("mouthFrownLeft", "mouthFrownRight"),
81
+ angry: t("browDownLeft", "browDownRight"),
82
+ surprised: t("eyeWideLeft", "eyeWideRight")
83
+ };
84
+ }
85
+ var d = /* @__PURE__ */ new WeakSet();
86
+ function f(r, i = {}) {
87
+ let o = new l(i), s = r.model, c = s.root.engine, { animator: f, vrm: p, map: m = {} } = i;
88
+ for (let e of Object.keys(m)) if (!n.has(e)) throw RangeError(`Face map names ${e}; use a name from FACE_SHAPES`);
89
+ let h = /* @__PURE__ */ new Map();
90
+ for (let [e, t] of Object.entries(m)) for (let n of typeof t == "string" ? [t] : t) h.set(n, e);
91
+ let g = [], _ = /* @__PURE__ */ new Set();
92
+ if (!p) for (let { nodeIndex: e, targetNames: t } of s.primitives) t.forEach((t, r) => {
93
+ let i = h.get(t) ?? a(t), o = `${e}:${r}`;
94
+ i === null || _.has(o) || (_.add(o), g.push({
95
+ node: e,
96
+ target: r,
97
+ shape: n.get(i)
98
+ }));
99
+ });
100
+ if (!p && !g.length) throw new e("state", "This model has no morph target named like a face shape; pass map, or vrm for an avatar");
101
+ let v = new Set(g.map((e) => e.shape)), y = p ? [] : t.filter((e, t) => v.has(t)), b = p ? [] : t.filter((e, t) => !v.has(t)), x = (e) => o.get(e), S = () => {
102
+ if (p) for (let [e, t] of Object.entries(u(x))) p.expressions.set(e, t);
103
+ else for (let { node: e, target: t, shape: n } of g) r.setMorph(e, t, o.values[n]);
104
+ }, C = (e) => {
105
+ o.update(e), S();
106
+ };
107
+ if (d.has(s)) throw new e("state", "This model already has a face from addFace; dispose that face before adding another");
108
+ let w = `face:${s.root.id}`, T;
109
+ if (f) T = f.addSolver(C);
110
+ else {
111
+ let e = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
112
+ name: w,
113
+ setup() {},
114
+ onPreUpdate: C,
115
+ dispose: () => {
116
+ T && (T = () => {}, O());
117
+ }
118
+ };
119
+ c.use(e), T = () => {
120
+ let t = c.sceneOf(e);
121
+ t?.plugins.get(w) === e && t.removePlugin(w);
122
+ };
123
+ }
124
+ d.add(s);
125
+ let E = () => {
126
+ let e = T;
127
+ T = null, e && d.delete(s), e?.(), D?.(), D = null;
128
+ }, D = s.onDispose(E), O = () => {
129
+ T && (E(), o.reset(), S());
130
+ };
131
+ return {
132
+ mapper: o,
133
+ matched: y,
134
+ missing: b,
135
+ push: (e) => {
136
+ o.push(e);
137
+ },
138
+ update: C,
139
+ dispose: O,
140
+ [Symbol.dispose]: O
141
+ };
142
+ }
143
+ //#endregion
144
+ export { t as FACE_SHAPES, l as FaceMapper, f as addFace, a as faceShapeOf, u as vrmFaceExpressions };