@hackbuild/motion-views 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -69,7 +69,11 @@ document.querySelector("hb-avatar-drop")!.addEventListener("picked", (e) => stag
69
69
 
70
70
  ### speech on the stage
71
71
 
72
- `say(speech)` plays an AudioBuffer or an audio element through an analyser whose level and bands open the mouth, with the word or phoneme timings a speech engine reports. Text alone moves the lips on estimated word timings with no sound. `speechSource` says where the last timings came from. `gesture("wave" | "nod" | "shake" | "bow")` plays a gesture written in code over the body's own bones, and `play(clip)` plays a presence clip or a three.js AnimationClip.
72
+ `say(speech)` plays an AudioBuffer or an audio element through an analyser whose level and bands open the mouth, with the word or phoneme timings a speech engine reports. Text alone moves the lips on estimated word timings with no sound. `speechSource` says where the last timings came from. `gesture("wave" | "nod" | "shake" | "bow")` plays a gesture built on the rig itself: each bone is aimed or turned in world space in the body's own frame, so the same wave works on a VRM or on any other humanoid rig, and the arm eases up, waves and eases down (`rigGestureClip`). `play(clip)` plays a presence clip or a three.js AnimationClip.
73
+
74
+ ### a clip pack for the idle
75
+
76
+ `clips` takes a clip pack baked onto the shown body's rig (its URL or the parsed file, the dog simulator's `anims.json` shape: roles, fps and int16 rotations per clip). Its `Idle_Loop` plays under everything once the body loads and `Idle_Talking_Loop` while the body speaks, with the clip player's fades. A body the pack does not fit (fewer than 12 roles land) keeps the rest stance. `packClips` and `packCoverage` do the conversion for any host. The name and doing plate at the top left shows only with `plate: true`.
73
77
 
74
78
  ### the rig check in plain words
75
79
 
@@ -94,6 +98,12 @@ The stage writes a `.hb-lay-stage`, the card is `.hb-avcard`, the strip `.hb-cli
94
98
  | [`clipStrip`](../../docs/api/motion-views/vanilla.md#clipstrip) | mount the clip strip |
95
99
  | [`defineMotionViews`](../../docs/api/motion-views/vanilla.md#definemotionviews) | define the three custom elements |
96
100
  | [`gestureClip`](../../docs/api/motion-views/vanilla.md#gestureclip) | a gesture written in code as a clip |
101
+ | [`threeStage`](../../docs/api/motion-views/vanilla.md#threestage) | a lit stage that fills an element, ticks and frees itself |
102
+ | [`meshTurntable`](../../docs/api/motion-views/vanilla.md#meshturntable) | one object on a stage you drag to turn, for a relief or a surface |
103
+ | [`stageOrbit`](../../docs/api/motion-views/vanilla.md#stageorbit) | drag to turn a camera round a target, the wheel moves in and out |
104
+ | [`boxDog`](../../docs/api/motion-views/vanilla.md#boxdog) | a dog of bones and boxes with the bone names in `BOX_DOG_BONES` |
105
+ | [`walkBvh`](../../docs/api/motion-views/vanilla.md#walkbvh) | a walk loop as bvh text for another rig, to retarget |
106
+ | [`freeMeshes`](../../docs/api/motion-views/vanilla.md#freemeshes) | free the geometry and materials under an object |
97
107
  | [`CharacterStage`](../../docs/api/motion-views/vue.md#characterstage) | the stage as a Vue component |
98
108
  | [`AvatarDrop`](../../docs/api/motion-views/vue.md#avatardrop) | the drop card as a Vue component |
99
109
  | [`ClipStrip`](../../docs/api/motion-views/vue.md#clipstrip) | the strip as a Vue component |
@@ -155,6 +165,8 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
155
165
  | a bvh walk retargets onto the stand-in; six clips bake into one pack and read back; a loop cut short is flagged at its seam | pass |
156
166
  | the three demo pages at 1440 and 390 px against the suite's screen gate | pass |
157
167
  | unit tests over the words and the clip items | pass |
168
+ | unit tests: a pack maps onto the body's bone order; the rig wave raises the arm and ends where it began; the nod moves only the head | pass |
169
+ | the owner's person glb with its clip pack in headless Chrome: idle frames differ (head and both arms), the wave raises the right arm and hands back to the idle (frame strip, looked at by the coordinator) | pass, headless |
158
170
 
159
171
  ### Not verified by anything
160
172
 
@@ -169,8 +181,8 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
169
181
  | file | gzip (measured) | ceiling |
170
182
  |---|---|---|
171
183
  | `dist/index.js` (main entry, imports external) | 3,266 bytes | 3,429 bytes |
172
- | `dist/motion-views.iife.js` (single file build) | 215,543 bytes | 226,320 bytes |
184
+ | `dist/motion-views.iife.js` (single file build) | 221,256 bytes | 232,318 bytes |
173
185
 
174
- Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
186
+ Measured 2026-11-26 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
175
187
  tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
176
188
  5 percent from its row.
@@ -4,6 +4,7 @@ import { type Speech, type SpeechSource } from "./speech.js";
4
4
  import type { BodySource, DroppedFile } from "@hackbuild/avatar-host";
5
5
  import { AvatarStage, type Body, type BodyCaps, type StageOptions } from "@hackbuild/avatar-host/three";
6
6
  import { type Gesture } from "./gestures.js";
7
+ import { type ClipPack } from "./clip-pack.js";
7
8
  /** The stage shot: bust, or the full body. */
8
9
  export type Framing = "bust" | "full";
9
10
  /** One verb on the stage. `go` makes it the one pink action; give it to one verb at most. */
@@ -29,6 +30,14 @@ export interface CharacterStageOptions extends StageOptions {
29
30
  hello?: string | Speech | (() => Speech | Promise<Speech>);
30
31
  /** The context real speech plays through; default one made on the first audio. */
31
32
  audioContext?: AudioContext;
33
+ /**
34
+ * A clip pack baked onto the shown body's rig (its URL or the parsed
35
+ * file): its Idle_Loop plays under everything, Idle_Talking_Loop while it
36
+ * speaks. Ignored for bodies it does not fit (fewer than 12 bones land).
37
+ */
38
+ clips?: string | ClipPack;
39
+ /** Show the name and doing plate at the top left. Default false. */
40
+ plate?: boolean;
32
41
  }
33
42
  /** Events of CharacterStage: a body loaded or failed, what it is doing, a verb pressed, the framing changed. */
34
43
  export type CharacterStageEvent = {
@@ -12,7 +12,8 @@ import { posedBounds } from "@hackbuild/avatar/three";
12
12
  import { AvatarStage } from "@hackbuild/avatar-host/three";
13
13
  import { dropRoutes } from "@virgilvox/hackbuild-ui/vanilla";
14
14
  import { button, el, iconButton, part } from "./dom.js";
15
- import { GESTURES, gestureClip } from "./gestures.js";
15
+ import { GESTURES, gestureClip, rigGestureClip } from "./gestures.js";
16
+ import { packClips, packCoverage } from "./clip-pack.js";
16
17
  /** The verbs a stage shows by default: say hello is the next thing to do. */
17
18
  export const DEFAULT_VERBS = [
18
19
  { id: "say", label: "say hello", go: true },
@@ -40,6 +41,8 @@ export function characterStage(host, opts = {}) {
40
41
  const turnBtn = iconButton(doc, "flip", "turn around");
41
42
  const frameBtn = iconButton(doc, "frame", "full body", { "aria-pressed": "false" });
42
43
  const tag = el(doc, "div", "hb-stage-tag", {}, [nameEl, doingEl]);
44
+ if (!opts.plate)
45
+ tag.style.display = "none";
43
46
  const tagCorner = el(doc, "div", "hb-ov hb-ov-tl");
44
47
  const corner = el(doc, "div", "hb-ov hb-ov-tr", {}, [turnBtn, frameBtn]);
45
48
  // the stage first, so its canvas sits under the plate
@@ -78,8 +81,34 @@ export function characterStage(host, opts = {}) {
78
81
  nameEl.textContent = e.placeholder ? "stand-in" : e.name;
79
82
  applyFraming();
80
83
  setDoing("idle");
84
+ packed = null;
85
+ if (!e.placeholder)
86
+ void usePack();
81
87
  emit({ type: "loaded", name: e.name, caps: e.caps, warnings: e.warnings, placeholder: e.placeholder });
82
88
  }), stage.on("failed", (e) => emit({ type: "failed", message: e.message })));
89
+ // the clip pack: the body's own mocap idle under everything, the talking idle while it speaks
90
+ let packed = null;
91
+ let packFile = null;
92
+ async function usePack() {
93
+ const body = stage.body;
94
+ if (!opts.clips || !body)
95
+ return;
96
+ packFile ??= typeof opts.clips === "string"
97
+ ? fetch(opts.clips).then((r) => (r.ok ? r.json() : null)).catch(() => null)
98
+ : Promise.resolve(opts.clips);
99
+ const pack = await packFile;
100
+ if (!pack || stage.body !== body || packCoverage(pack, body.names) < 12)
101
+ return;
102
+ const base = new Float32Array(body.bones.length * 4);
103
+ body.bones.forEach((b, i) => b.quaternion.toArray(base, i * 4));
104
+ packed = packClips(pack, body.names, base);
105
+ idleLoop(0.4);
106
+ }
107
+ function idleLoop(fade, talking = false) {
108
+ const c = packed?.[talking ? "Idle_Talking_Loop" : "Idle_Loop"] ?? packed?.Idle_Loop;
109
+ if (c && stage.body)
110
+ stage.body.play(c, { layer: "body", loop: true, background: true, fade });
111
+ }
83
112
  // bust: the knees to the top of the head, the original's opening shot; full: the follow camera
84
113
  function applyFraming() {
85
114
  const body = stage.body;
@@ -149,9 +178,12 @@ export function characterStage(host, opts = {}) {
149
178
  const body = stage.body;
150
179
  if (!body)
151
180
  return false;
152
- const base = new Float32Array(body.bones.length * 4);
153
- body.bones.forEach((b, i) => b.quaternion.toArray(base, i * 4));
154
- const clip = gestureClip(id, body.names, base);
181
+ let clip = rigGestureClip(id, body.bones, body.names);
182
+ if (!clip) {
183
+ const base = new Float32Array(body.bones.length * 4);
184
+ body.bones.forEach((b, i) => b.quaternion.toArray(base, i * 4));
185
+ clip = gestureClip(id, body.names, base);
186
+ }
155
187
  if (!clip)
156
188
  return false;
157
189
  return play(clip, { layer: id === "bow" ? "body" : "upper" }) >= 0;
@@ -233,6 +265,7 @@ export function characterStage(host, opts = {}) {
233
265
  body.lip.push(events);
234
266
  body.setGazeMode("talk");
235
267
  setDoing("talking");
268
+ idleLoop(0.5, true);
236
269
  stage.loop.sync();
237
270
  start?.();
238
271
  if (analyser && audioCtx) {
@@ -260,6 +293,7 @@ export function characterStage(host, opts = {}) {
260
293
  analyser?.disconnect();
261
294
  stage.body?.lip.setLevel(0);
262
295
  stage.body?.setGazeMode("listen");
296
+ idleLoop(0.6);
263
297
  if (doing === "talking")
264
298
  setDoing("idle");
265
299
  }
@@ -0,0 +1,21 @@
1
+ import type { Clip } from "@hackbuild/presence";
2
+ /** The pack file: role names, frame rate and the clips. */
3
+ export interface ClipPack {
4
+ roles: readonly string[];
5
+ fps: number;
6
+ clips: Record<string, {
7
+ dur: number;
8
+ n: number;
9
+ loop: boolean;
10
+ q: string;
11
+ p?: string;
12
+ }>;
13
+ }
14
+ /** How many of the pack's roles land on one of `names`. */
15
+ export declare function packCoverage(pack: ClipPack, names: readonly string[]): number;
16
+ /**
17
+ * The pack's clips as presence clips over `names` (the body's bone order).
18
+ * `base` holds bones times 4 local rotations for the bones the pack does
19
+ * not move (fingers, eyes), usually the pose when the body loaded.
20
+ */
21
+ export declare function packClips(pack: ClipPack, names: readonly string[], base: ArrayLike<number>): Record<string, Clip>;
@@ -0,0 +1,53 @@
1
+ // pack role to the humanoid bone name the body uses
2
+ const ROLE = {
3
+ hips: "hips", spine: "spine", chest: "chest", upperChest: "upperChest", neck: "neck", head: "head",
4
+ shoulderL: "leftShoulder", upperArmL: "leftUpperArm", lowerArmL: "leftLowerArm", handL: "leftHand",
5
+ shoulderR: "rightShoulder", upperArmR: "rightUpperArm", lowerArmR: "rightLowerArm", handR: "rightHand",
6
+ upperLegL: "leftUpperLeg", lowerLegL: "leftLowerLeg", footL: "leftFoot",
7
+ upperLegR: "rightUpperLeg", lowerLegR: "rightLowerLeg", footR: "rightFoot",
8
+ };
9
+ function int16(b64) {
10
+ const s = atob(b64);
11
+ const u = new Uint8Array(s.length);
12
+ for (let i = 0; i < s.length; i++)
13
+ u[i] = s.charCodeAt(i);
14
+ return new Int16Array(u.buffer);
15
+ }
16
+ /** How many of the pack's roles land on one of `names`. */
17
+ export function packCoverage(pack, names) {
18
+ return pack.roles.filter((r) => ROLE[r] && names.includes(ROLE[r])).length;
19
+ }
20
+ /**
21
+ * The pack's clips as presence clips over `names` (the body's bone order).
22
+ * `base` holds bones times 4 local rotations for the bones the pack does
23
+ * not move (fingers, eyes), usually the pose when the body loaded.
24
+ */
25
+ export function packClips(pack, names, base) {
26
+ const R = pack.roles.length;
27
+ const n = names.length;
28
+ const slot = pack.roles.map((r) => (ROLE[r] ? names.indexOf(ROLE[r]) : -1));
29
+ const out = {};
30
+ for (const [name, c] of Object.entries(pack.clips)) {
31
+ const q = int16(c.q);
32
+ const frames = c.n;
33
+ const rotations = new Float32Array(frames * n * 4);
34
+ for (let f = 0; f < frames; f++) {
35
+ rotations.set(Array.prototype.slice.call(base, 0, n * 4), f * n * 4);
36
+ for (let r = 0; r < R; r++) {
37
+ const i = slot[r];
38
+ if (i < 0)
39
+ continue;
40
+ const a = (f * R + r) * 4;
41
+ let x = q[a] / 32767, y = q[a + 1] / 32767, z = q[a + 2] / 32767, w = q[a + 3] / 32767;
42
+ const len = Math.hypot(x, y, z, w) || 1;
43
+ x /= len;
44
+ y /= len;
45
+ z /= len;
46
+ w /= len;
47
+ rotations.set([x, y, z, w], (f * n + i) * 4);
48
+ }
49
+ }
50
+ out[name] = { name, fps: pack.fps, frames, bones: n, loop: c.loop, rotations };
51
+ }
52
+ return out;
53
+ }
@@ -1,4 +1,4 @@
1
- import { AnimationClip } from "three";
1
+ import { AnimationClip, type Object3D } from "three";
2
2
  import type { Clip } from "@hackbuild/presence";
3
3
  /** A gesture written in code over the body's own bones. */
4
4
  export type Gesture = "wave" | "nod" | "shake" | "bow";
@@ -12,3 +12,13 @@ export declare const GESTURES: readonly Gesture[];
12
12
  export declare function gestureClip(id: Gesture, names: readonly string[], base: ArrayLike<number>, fps?: number): Clip | null;
13
13
  /** A presence clip as a three.js AnimationClip with one quaternion track per bone object name. */
14
14
  export declare function animationClipOf(clip: Clip, names: readonly string[]): AnimationClip;
15
+ /**
16
+ * A gesture as a presence clip built on the rig itself: each bone is aimed
17
+ * or turned in world space, in the body's own frame (forward, left and up
18
+ * from its shoulders), then read back as local rotations. Works on any
19
+ * humanoid rig, whatever its bone axes. The arm eases up, waves and eases
20
+ * down; nod, shake and bow ease in and out. `bones` and `names` are the
21
+ * body's bone order; the pose they hold now is the base. Returns null when
22
+ * the rig lacks the gesture's bones.
23
+ */
24
+ export declare function rigGestureClip(id: Gesture, bones: readonly Object3D[], names: readonly string[], fps?: number): Clip | null;
package/dist/gestures.js CHANGED
@@ -71,3 +71,89 @@ export function animationClipOf(clip, names) {
71
71
  });
72
72
  return new AnimationClip(clip.name, (clip.frames - 1) / clip.fps, tracks);
73
73
  }
74
+ const ss = (a, b, x) => {
75
+ const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
76
+ return t * t * (3 - 2 * t);
77
+ };
78
+ /** Seconds each rig gesture runs. */
79
+ const RIG_SECONDS = { wave: 2.6, nod: 1.2, shake: 1.4, bow: 2 };
80
+ /**
81
+ * A gesture as a presence clip built on the rig itself: each bone is aimed
82
+ * or turned in world space, in the body's own frame (forward, left and up
83
+ * from its shoulders), then read back as local rotations. Works on any
84
+ * humanoid rig, whatever its bone axes. The arm eases up, waves and eases
85
+ * down; nod, shake and bow ease in and out. `bones` and `names` are the
86
+ * body's bone order; the pose they hold now is the base. Returns null when
87
+ * the rig lacks the gesture's bones.
88
+ */
89
+ export function rigGestureClip(id, bones, names, fps = 30) {
90
+ const at = (n) => {
91
+ const i = names.indexOf(n);
92
+ return i < 0 ? null : bones[i];
93
+ };
94
+ const lu = at("leftUpperArm"), ru = at("rightUpperArm"), rl = at("rightLowerArm"), rh = at("rightHand"), head = at("head");
95
+ const spine = at("spine"), chest = at("chest");
96
+ if (!lu || !ru)
97
+ return null;
98
+ if (id === "wave" && (!rl || !rh))
99
+ return null;
100
+ if ((id === "nod" || id === "shake") && !head)
101
+ return null;
102
+ if (id === "bow" && !spine)
103
+ return null;
104
+ const n = bones.length;
105
+ const base = bones.map((b) => b.quaternion.clone());
106
+ const top = bones[0].parent ?? bones[0];
107
+ top.updateMatrixWorld(true);
108
+ const wp = (o, v = new Vector3()) => o.getWorldPosition(v);
109
+ const up = new Vector3(0, 1, 0);
110
+ const L = wp(lu).sub(wp(ru)).setY(0).normalize();
111
+ const F = new Vector3().crossVectors(L, up).normalize();
112
+ const R = L.clone().negate();
113
+ const pq = new Quaternion(), bq = new Quaternion(), rq = new Quaternion();
114
+ const turnWorld = (b, rw) => {
115
+ b.parent.getWorldQuaternion(pq);
116
+ b.getWorldQuaternion(bq);
117
+ b.quaternion.copy(pq.invert().multiply(rw).multiply(bq));
118
+ b.updateMatrixWorld(true);
119
+ };
120
+ const aim = (b, child, dir, w) => {
121
+ const cur = wp(child).sub(wp(b)).normalize();
122
+ const want = cur.clone().lerp(dir, w).normalize();
123
+ turnWorld(b, rq.setFromUnitVectors(cur, want));
124
+ };
125
+ const seconds = RIG_SECONDS[id];
126
+ const frames = Math.round(seconds * fps) + 1;
127
+ const rotations = new Float32Array(frames * n * 4);
128
+ const armUp = R.clone().multiplyScalar(0.55).addScaledVector(up, 0.8).addScaledVector(F, 0.22).normalize();
129
+ for (let f = 0; f < frames; f++) {
130
+ const t = f / (frames - 1);
131
+ bones.forEach((b, i) => b.quaternion.copy(base[i]));
132
+ top.updateMatrixWorld(true);
133
+ if (id === "wave") {
134
+ const e = ss(0, 0.22, t) * (1 - ss(0.8, 1, t));
135
+ aim(ru, rl, armUp, e);
136
+ const osc = 0.42 * Math.sin(2 * Math.PI * 3 * ss(0.18, 0.84, t)) * ss(0.12, 0.3, t) * (1 - ss(0.74, 0.86, t));
137
+ const fore = up.clone().addScaledVector(F, 0.12).addScaledVector(R, 0.08).applyAxisAngle(F, -osc).normalize();
138
+ aim(rl, rh, fore, e);
139
+ }
140
+ else if (id === "nod") {
141
+ turnWorld(head, rq.setFromAxisAngle(L, 0.24 * Math.sin(2 * Math.PI * t) ** 2 * (1 - ss(0.85, 1, t))));
142
+ }
143
+ else if (id === "shake") {
144
+ turnWorld(head, rq.setFromAxisAngle(up, 0.32 * Math.sin(4 * Math.PI * t) * Math.sin(Math.PI * t)));
145
+ }
146
+ else {
147
+ const e = ss(0, 0.35, t) * (1 - ss(0.65, 1, t));
148
+ turnWorld(spine, rq.setFromAxisAngle(L, 0.32 * e));
149
+ if (chest)
150
+ turnWorld(chest, rq.setFromAxisAngle(L, 0.18 * e));
151
+ if (head)
152
+ turnWorld(head, rq.setFromAxisAngle(L, -0.12 * e));
153
+ }
154
+ bones.forEach((b, i) => b.quaternion.toArray(rotations, (f * n + i) * 4));
155
+ }
156
+ bones.forEach((b, i) => b.quaternion.copy(base[i]));
157
+ top.updateMatrixWorld(true);
158
+ return { name: id, fps, frames, bones: n, loop: false, rotations };
159
+ }