Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add live expression switching

shinshin862678e00f5d73
diff --git a/README.ja.md b/README.ja.md
index 0a56d47..84e1bcb 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -84,6 +84,8 @@ npm run dev
![緑の背景にした配信用の画面](docs/images/ja/08-stream.png)
+「表情」のボタンか、キー1〜8で、笑顔、驚き、ウインクなどに切り替えられます。切り替えている間も、まばたきや口の動きはカメラとマイクに合わせて動きます([詳しく](docs/reference.md#expressions)、英語)。
+
配信用画面の URL で指定できる項目、うまく動かないときの確認点、プライバシーについては[リファレンス](docs/reference.md#live-and-streaming)(英語)にまとめています。
## 詳しい資料
diff --git a/README.md b/README.md
index a0fce19..9c3e253 100644
--- a/README.md
+++ b/README.md
@@ -119,6 +119,9 @@ stopped or slowed while hidden, bring its window to the front.
![The stream view with a green background](docs/images/en/08-stream.png)
+Switch expressions such as a smile, surprise or a wink with the **Expression** buttons or
+keys **1**–**8** while tracking continues ([details](docs/reference.md#expressions)).
+
Stream view options, troubleshooting and privacy details are in the
[reference](docs/reference.md#live-and-streaming).
diff --git a/docs/reference.md b/docs/reference.md
index ddbeb90..02bd8e3 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -200,6 +200,19 @@ for software without transparency support.
- With the microphone on, the voice level drives how far the mouth opens and the camera keeps
the mouth shape. Drawn mouth images are used automatically when the project has them.
+### Expressions
+
+The Live page's **Expression** buttons switch the face to Neutral, Smile, Shy, Surprised,
+Half-lidded, Angry, Sad or Wink. Keys **1**–**8** do the same while the Live page is focused;
+press the same key or button again to return to Neutral. Keys typed into a form field are
+ignored. Because browsers receive keys only for the focused page, a key press from another app
+reaches the Live page only when its window is in front.
+
+An expression is layered over tracking: blinking, gaze and the mouth keep following the camera
+or microphone, while the eyes, brows and blush hold the expression. Switching fades smoothly.
+An expression also reaches the stream view without the camera or microphone. Brows hidden
+under bangs show less difference between Half-lidded, Angry and Sad.
+
### Privacy
Camera video and microphone audio are processed in the browser and never leave your machine.
diff --git a/e2e/expressions.spec.ts b/e2e/expressions.spec.ts
new file mode 100644
index 0000000..234ed6c
--- /dev/null
+++ b/e2e/expressions.spec.ts
@@ -0,0 +1,40 @@
+import { expect, test } from '@playwright/test';
+import { samplePresent, sampleSkipReason } from './sample';
+
+test.beforeEach(() => test.skip(!samplePresent, sampleSkipReason));
+
+test('expression keys and buttons drive the stream view without camera or microphone', async ({ context, page }) => {
+ const outside: string[] = [];
+ await context.route('**/*', route => { const url = route.request().url(); if (new URL(url).hostname !== '127.0.0.1') { outside.push(url); return route.abort(); } return route.continue(); });
+ await page.goto('/live.html'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');
+ const stream = await context.newPage(); await stream.goto('/stream.html'); await expect(stream.locator('canvas')).toHaveAttribute('data-state', 'ready');
+ await stream.evaluate(async () => {
+ const path = '/src/live/relay.ts', { receiveLiveParameters } = await import(path);
+ Object.assign(window, { latest: null });
+ receiveLiveParameters((data: { params: Record<string, number> }) => Object.assign(window, { latest: data.params }));
+ });
+ const latest = () => stream.evaluate(() => (window as unknown as { latest: Record<string, number> | null }).latest);
+ const group = page.getByRole('group', { name: 'Expression' });
+ await expect(group.getByRole('button')).toHaveCount(8);
+ await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
+
+ await page.locator('body').press('2');
+ await expect(group.getByRole('button', { name: /Smile/ })).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(async () => (await latest())?.eyeSmile ?? 0).toBeGreaterThan(0.9);
+ expect((await latest())!.blush).toBeGreaterThan(0.3);
+
+ // The same key returns to neutral; the fade-out reaches the stream before updates stop.
+ await page.locator('body').press('2');
+ await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(async () => (await latest())?.eyeSmile ?? 1).toBeLessThan(0.05);
+
+ // Keys typed into form fields do not switch expressions.
+ await page.getByRole('textbox', { name: 'Copy OBS URL' }).press('4');
+ await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
+
+ await group.getByRole('button', { name: /Wink/ }).click();
+ await expect.poll(async () => (await latest())?.eyeLOpen ?? 1).toBeLessThan(0.05);
+ await page.getByRole('button', { name: '日本語', exact: true }).click();
+ await expect(page.getByRole('group', { name: '表情' }).getByRole('button', { name: /ウインク/ })).toHaveAttribute('aria-pressed', 'true');
+ expect(outside).toEqual([]);
+});
diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.js
index 9f93848..a3cffab 100644
--- a/src/engine/createMeshAvatar.js
+++ b/src/engine/createMeshAvatar.js
@@ -6,6 +6,7 @@ import { createRenderer } from './renderer.js';
import { createPhysics } from './physics.js';
import { createSpriteModule } from './sprites.js';
import { Motion } from './motion.js';
+import { ExpressionOverlay } from './expression-overlay.js';
import { MOTIONS, IDLE_MOTIONS } from './motions.js';
const EYE_PARTS = ['ball', 'low', 'crease', 'lash']; // back to front
@@ -140,6 +141,7 @@ export async function createMeshAvatarImpl(canvas, options) {
motion.onMotion = id => { for (const fn of listeners) fn(id); };
let parameters = {}, parameterWeight = 1, lastParameters = {};
+ const expression = new ExpressionOverlay();
const tmp = [0, 0];
function updateParameters(dt) {
const P = { ...motion.update(dt) };
@@ -149,8 +151,10 @@ export async function createMeshAvatarImpl(canvas, options) {
P.mouthOpen = motion.P.mouthOpen;
if (!options.preserveMouthForm || parameters.mouthForm === undefined) P.mouthForm = motion.P.mouthForm;
}
- lastParameters = P;
- return P;
+ // Live expressions sit above tracking and lip sync; neutral leaves the parameters untouched.
+ const out = expression.apply(P, dt);
+ lastParameters = out;
+ return out;
}
function tick(dt) {
const P = updateParameters(dt);
@@ -223,6 +227,9 @@ export async function createMeshAvatarImpl(canvas, options) {
setSpeaking(on) { motion.setSpeaking(on); },
/** AITuber OnAir emotion tag: happy / sad / angry / surprised / relaxed / neutral (or null). */
setEmotion(tag, opts) { motion.setEmotion(tag, opts); },
+ /** Live expression layered over tracking (see OVERLAY_EXPRESSIONS); 'neutral' clears it. */
+ setExpression(name) { expression.set(name); },
+ getExpression() { return { name: expression.name, active: expression.active }; },
/** How much the head moves with the voice while speaking (1 = default, calmer below). */
setTalkGain(g) { motion.talkGain = Math.max(0, Number(g) || 0); },
/** Play a motion or idle motion by id (see `motions`). */
diff --git a/src/engine/expression-overlay.js b/src/engine/expression-overlay.js
new file mode 100644
index 0000000..a123f6d
--- /dev/null
+++ b/src/engine/expression-overlay.js
@@ -0,0 +1,54 @@
+// Expressions layered over tracked or posed parameters, so blinking, gaze and the mouth keep
+// following the camera or microphone while the face holds a smile, a frown and so on.
+import { EXPRESSIONS } from './motion.js';
+
+/** Expressions offered for live switching, in key order (1 = neutral). */
+export const OVERLAY_EXPRESSIONS = {
+ neutral: 'normal', smile: 'smile', shy: 'shy', surprise: 'surprise',
+ halfLidded: 'jito', angry: 'angryTalk', sad: 'sadTalk', wink: 'wink',
+};
+// Brows are often hidden under bangs, so some faces also lean on gaze and head pitch to read.
+const POSE = { sad: { pitch: -6, gy: -0.45 } };
+const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
+const NEUTRAL = Object.freeze({ eyeOpen: 1, eyeOpenL: 1, eyeSmile: 0, eyeSmileL: 0, blush: 0, browY: 0, browAngle: 0, mouthOpen: 0, gx: 0, gy: 0, pitch: 0 });
+
+export function overlayTarget(name) {
+ const E = EXPRESSIONS[OVERLAY_EXPRESSIONS[name]]?.p ?? {}, pose = POSE[name] ?? {};
+ return { eyeOpen: E.eyeOpen ?? 1, eyeOpenL: E.eyeOpenL ?? E.eyeOpen ?? 1, eyeSmile: E.eyeSmile ?? 0,
+ eyeSmileL: E.eyeSmileL ?? E.eyeSmile ?? 0, blush: E.blush ?? 0, browY: E.browY ?? 0, browAngle: E.browAngle ?? 0,
+ mouthOpen: E.mouthOpen ?? 0, gx: E.glance?.[0] ?? 0, gy: pose.gy ?? E.glance?.[1] ?? 0, pitch: pose.pitch ?? 0 };
+}
+
+/** Eyes scale with the expression so blinks still show; smiles, blush and brows add on top. */
+export function applyOverlay(P, m) {
+ const out = { ...P };
+ out.eyeROpen = (P.eyeROpen ?? 1) * m.eyeOpen;
+ out.eyeLOpen = (P.eyeLOpen ?? 1) * m.eyeOpenL;
+ out.eyeSmile = Math.max(P.eyeSmile ?? 0, m.eyeSmile);
+ out.eyeSmileL = Math.max(P.eyeSmileL ?? P.eyeSmile ?? 0, m.eyeSmileL);
+ out.blush = Math.max(P.blush ?? 0, m.blush);
+ out.browY = clamp((P.browY ?? 0) + m.browY, -1, 1);
+ out.browAngle = clamp((P.browAngle ?? 0) + m.browAngle, -1, 1);
+ out.mouthOpen = Math.max(P.mouthOpen ?? 0, m.mouthOpen);
+ out.gazeX = clamp((P.gazeX ?? 0) + m.gx, -1, 1);
+ out.gazeY = clamp((P.gazeY ?? 0) + m.gy, -1, 1);
+ out.angleY = clamp((P.angleY ?? 0) + m.pitch, -30, 30);
+ return out;
+}
+
+/** Smoothed switching. While neutral and settled the parameters pass through untouched. */
+export class ExpressionOverlay {
+ /** @type {keyof typeof OVERLAY_EXPRESSIONS} */
+ name = 'neutral';
+ mix = { ...NEUTRAL };
+ /** @param {string} name */
+ set(name) { this.name = Object.hasOwn(OVERLAY_EXPRESSIONS, name) ? /** @type {keyof typeof OVERLAY_EXPRESSIONS} */ (name) : 'neutral'; }
+ /** True while an expression is shown or still fading out. */
+ get active() { return this.name !== 'neutral' || Object.keys(NEUTRAL).some(k => Math.abs(this.mix[k] - NEUTRAL[k]) > 1e-3); }
+ apply(P, dt) {
+ if (!this.active) { this.mix = { ...NEUTRAL }; return P; }
+ const target = overlayTarget(this.name), k = 1 - Math.exp(-Math.max(0, dt) * 12);
+ for (const key of Object.keys(NEUTRAL)) this.mix[key] += (target[key] - this.mix[key]) * k;
+ return applyOverlay(P, this.mix);
+ }
+}
diff --git a/src/engine/index.ts b/src/engine/index.ts
index 0db242c..44d7868 100644
--- a/src/engine/index.ts
+++ b/src/engine/index.ts
@@ -2,6 +2,10 @@ import type { LightingSettings } from '../lighting/settings';
import type { Rig } from '../rig/types';
import { parseRig } from '../rig/validate';
import { createMeshAvatarImpl } from './createMeshAvatar.js';
+import { OVERLAY_EXPRESSIONS } from './expression-overlay.js';
+
+export type LiveExpression = keyof typeof OVERLAY_EXPRESSIONS;
+export const LIVE_EXPRESSIONS = Object.keys(OVERLAY_EXPRESSIONS) as LiveExpression[];
export interface MeshAvatarOptions {
rig: Rig;
@@ -22,6 +26,8 @@ export interface MeshAvatar {
setVoiceLevel(value: number): void;
setSpeaking(on: boolean): void;
setEmotion(tag: string | null, options?: { playMotion?: boolean }): void;
+ setExpression(name: LiveExpression): void;
+ getExpression(): { name: LiveExpression; active: boolean };
setTalkGain(gain: number): void;
play(id: string): void;
speakKana(text: string, options?: { speed?: number; loop?: boolean }): void;
diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsx
index d1b084a..b0c59d2 100644
--- a/src/live/LiveApp.tsx
+++ b/src/live/LiveApp.tsx
@@ -1,6 +1,6 @@
import { LightingControls, LightHandle, lightingText } from '../lighting/Controls';
import { loadLighting, saveLighting } from '../lighting/settings';
-import type { MeshAvatar } from '../engine';
+import { LIVE_EXPRESSIONS, type LiveExpression, type MeshAvatar } from '../engine';
import { useEffect, useRef, useState } from 'react';
import { useI18n } from '../editor/i18n';
import { createAvatarView } from './avatar-view';
@@ -15,6 +15,8 @@ export function LiveApp() {
const { language, setLanguage } = useI18n(), t = liveText[language];
const [settings, setSettings] = useState(() => { const view = viewSettings(location.search); return { ...view, lighting: view.lighting ?? loadLighting(view.project) }; });
const [lightingOpen, setLightingOpen] = useState(false);
+ const [expression, setExpression] = useState<LiveExpression>('neutral');
+ const expressionRef = useRef(expression); expressionRef.current = expression;
const [options, setOptions] = useState<TrackingOptions>({ mirror: true, sensitivity: 1, smoothing: 0.35 });
const [cameraState, setCameraState] = useState<CameraState>('stopped');
const [micState, setMicState] = useState<MicState>('micOff');
@@ -58,8 +60,9 @@ export function LiveApp() {
const micOn = control.micState === 'micOn';
avatar.setSpeaking(micOn); avatar.setVoiceLevel(micOn ? microphone.current?.level(control.gain) ?? 0 : 0);
}, (avatar, now) => {
- if (controls.current.cameraState === 'running' || controls.current.micState === 'micOn') send(avatar.getParameters(), now);
- }).then(value => { if (cancelled) value.destroy(); else { view = value; avatarRef.current = value.avatar; value.avatar.setLighting(lightRef.current); setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });
+ // An expression alone also drives the stream view, including its fade back to neutral.
+ if (controls.current.cameraState === 'running' || controls.current.micState === 'micOn' || avatar.getExpression().active) send(avatar.getParameters(), now);
+ }).then(value => { if (cancelled) value.destroy(); else { view = value; avatarRef.current = value.avatar; value.avatar.setLighting(lightRef.current); value.avatar.setExpression(expressionRef.current); setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });
return () => { cancelled = true; clock.terminate(); view?.destroy(); avatarRef.current = null; };
}, [settings.project, settings.fit]);
useEffect(() => {
@@ -76,6 +79,19 @@ export function LiveApp() {
return () => clearInterval(timer);
}, [settings.project]);
const changeLighting = (lighting: typeof settings.lighting) => setSettings(current => ({ ...current, lighting }));
+ useEffect(() => { avatarRef.current?.setExpression(expression); }, [expression]);
+ const toggleExpression = (name: LiveExpression) => setExpression(current => current === name ? 'neutral' : name);
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ const target = event.target as HTMLElement | null;
+ if (event.repeat || event.altKey || event.ctrlKey || event.metaKey || target?.closest('input, select, textarea, [contenteditable="true"]')) return;
+ const name = LIVE_EXPRESSIONS[Number(event.key) - 1];
+ if (!/^[1-8]$/.test(event.key) || !name) return;
+ event.preventDefault(); toggleExpression(name);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, []);
const cameraActive = cameraState === 'starting' || cameraState === 'running';
const micActive = micState === 'micStarting' || micState === 'micOn';
const url = streamUrl(settings, location.origin);
@@ -107,6 +123,9 @@ export function LiveApp() {
<select aria-label={t.microphone} value={micId} disabled={micActive} onChange={event => setMicId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'audioinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.microphone} ${i + 1}`}</option>)}</select>
<label>{t.gain}<input type="range" min="0.25" max="5" step="0.05" value={gain} onChange={event => setGain(Number(event.target.value))} /></label><small role="status">{t[micState]}</small>
</section>
+ <section><h2>{t.expression}</h2><div className="expression-buttons" role="group" aria-label={t.expression}>
+ {LIVE_EXPRESSIONS.map((name, i) => <button key={name} type="button" aria-pressed={expression === name} aria-keyshortcuts={String(i + 1)} onClick={() => toggleExpression(name)}><kbd>{i + 1}</kbd>{t[name]}</button>)}
+ </div><small>{t.expressionHint}</small></section>
<section><h2>{t.background}</h2><select aria-label={t.background} value={settings.background} onChange={event => setSettings(current => ({ ...current, background: backgroundColor(event.target.value) }))}>
<option value="transparent">{t.transparent}</option><option value="#00ff00">{t.green}</option><option value="#0000ff">{t.blue}</option>{!['transparent', '#00ff00', '#0000ff'].includes(settings.background) && <option value={settings.background}>{t.custom}</option>}
</select><label>{t.custom}<input type="color" value={settings.background === 'transparent' ? '#ffffff' : settings.background} onChange={event => setSettings(current => ({ ...current, background: event.target.value }))} /></label>
diff --git a/src/live/i18n.ts b/src/live/i18n.ts
index 2dd3d6d..0e3ff5a 100644
--- a/src/live/i18n.ts
+++ b/src/live/i18n.ts
@@ -17,6 +17,8 @@ export const liveEn = {
micOff: 'Microphone off', micStarting: 'Starting microphone…', micOn: 'Microphone on',
micBlocked: 'Microphone access was blocked. Allow access in your browser and try again.', micUnavailable: 'Microphone unavailable. Check the selected device.',
liveUnavailable: 'Open this project from the local project list before using Live.',
+ expression: 'Expression', expressionHint: 'While this page is focused, keys 1–8 switch expressions. Press the same key again to return to neutral.',
+ neutral: 'Neutral', smile: 'Smile', shy: 'Shy', surprise: 'Surprised', halfLidded: 'Half-lidded', angry: 'Angry', sad: 'Sad', wink: 'Wink',
};
const liveJa: typeof liveEn = {
title: '配信', back: 'エディタに戻る', camera: 'カメラ', device: 'デバイス', defaultDevice: '既定のデバイス',
@@ -37,6 +39,8 @@ const liveJa: typeof liveEn = {
micOff: 'マイク停止中', micStarting: 'マイクを開始中…', micOn: 'マイク使用中',
micBlocked: 'マイクへのアクセスが拒否されました。ブラウザで許可してから、もう一度お試しください。', micUnavailable: 'マイクを使用できません。選択したデバイスを確認してください。',
liveUnavailable: '配信するには、エディタのローカルプロジェクト一覧からこのプロジェクトを開いてください。',
+ expression: '表情', expressionHint: 'この画面を操作している間は、キー1〜8で表情を切り替えられます。同じキーをもう一度押すと通常に戻ります。',
+ neutral: '通常', smile: '笑顔', shy: '照れ', surprise: '驚き', halfLidded: 'ジト目', angry: '怒り', sad: '悲しみ', wink: 'ウインク',
};
const liveZh: typeof liveEn = {
title: '直播', back: '返回编辑器', camera: '摄像头', device: '设备', defaultDevice: '默认设备',
@@ -57,5 +61,7 @@ const liveZh: typeof liveEn = {
micOff: '麦克风已关闭', micStarting: '正在启动麦克风…', micOn: '麦克风已开启',
micBlocked: '麦克风访问被拒绝。请在浏览器中允许访问后重试。', micUnavailable: '麦克风不可用。请检查所选设备。',
liveUnavailable: '请先从本地项目列表打开此项目,再使用直播功能。',
+ expression: '表情', expressionHint: '在此页面操作时,可用 1–8 键切换表情。再按一次同一键恢复普通表情。',
+ neutral: '普通', smile: '微笑', shy: '害羞', surprise: '惊讶', halfLidded: '半眯眼', angry: '生气', sad: '难过', wink: '眨眼',
};
export const liveText = { en: liveEn, ja: liveJa, zh: liveZh };
diff --git a/src/live/live.css b/src/live/live.css
index d694468..f913c77 100644
--- a/src/live/live.css
+++ b/src/live/live.css
@@ -41,3 +41,7 @@ input[type="color"] { width: 100%; height: 32px; border: 0; padding: 0; }
.live-controls .live-lighting .lighting-slider { display: grid; }
.live-controls .live-lighting select { width: auto; max-width: 60%; }
.live-controls .live-lighting input[type="color"] { width: 58px; height: 28px; }
+.expression-buttons { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; margin-bottom: 8px; }
+.expression-buttons button { display: flex; align-items: center; gap: 8px; text-align: left; }
+.expression-buttons button[aria-pressed="true"] { border-color: #3977d8; background: #e8f0fd; color: #1d4f9c; font-weight: 600; }
+.expression-buttons kbd { min-width: 1.4em; padding: 0 4px; border: 1px solid #c8d3e2; border-radius: 4px; font: 11px/1.5 ui-monospace, monospace; text-align: center; color: #5a6a80; background: #f6f8fb; }
diff --git a/tests/expression-overlay.test.ts b/tests/expression-overlay.test.ts
new file mode 100644
index 0000000..d682606
--- /dev/null
+++ b/tests/expression-overlay.test.ts
@@ -0,0 +1,46 @@
+import { expect, test } from 'vitest';
+import { ExpressionOverlay, OVERLAY_EXPRESSIONS, applyOverlay, overlayTarget } from '../src/engine/expression-overlay.js';
+
+const tracked = { angleY: 0, eyeLOpen: 1, eyeROpen: 1, eyeSmile: 0, eyeSmileL: 0, mouthOpen: 0.7, mouthForm: 0.4, browY: 0.1, browAngle: 0, blush: 0, gazeX: 0.2, gazeY: 0 };
+
+test('neutral leaves parameters untouched and the eight live expressions are in key order', () => {
+ const overlay = new ExpressionOverlay();
+ expect(overlay.apply(tracked, 1 / 60)).toBe(tracked);
+ expect(overlay.active).toBe(false);
+ expect(Object.keys(OVERLAY_EXPRESSIONS)).toEqual(['neutral', 'smile', 'shy', 'surprise', 'halfLidded', 'angry', 'sad', 'wink']);
+ for (const name of Object.keys(OVERLAY_EXPRESSIONS)) expect(overlayTarget(name)).toBeTruthy();
+});
+
+test('expressions shape the face while tracking keeps the mouth and blinks', () => {
+ const smile = applyOverlay(tracked, overlayTarget('smile'));
+ expect(smile.eyeROpen).toBe(0); expect(smile.eyeSmile).toBe(1); expect(smile.blush).toBeGreaterThan(0.3);
+ expect(smile.mouthOpen).toBe(0.7); expect(smile.mouthForm).toBe(0.4);
+ const surprise = overlayTarget('surprise');
+ expect(applyOverlay({ ...tracked, eyeROpen: 0 }, surprise).eyeROpen).toBe(0);
+ expect(applyOverlay(tracked, surprise).eyeROpen).toBeGreaterThan(1);
+ const wink = applyOverlay(tracked, overlayTarget('wink'));
+ expect(wink.eyeLOpen).toBe(0); expect(wink.eyeROpen).toBe(1);
+ const sad = applyOverlay(tracked, overlayTarget('sad'));
+ expect(sad.angleY).toBeLessThan(0); expect(sad.gazeY).toBeLessThan(0);
+ const angry = applyOverlay(tracked, overlayTarget('angry'));
+ expect(angry.browAngle).toBeGreaterThan(0.5); expect(angry.browY).toBeLessThan(tracked.browY);
+ for (const value of Object.values(applyOverlay({ ...tracked, browY: 0.9, gazeX: 0.9 }, overlayTarget('shy')))) expect(Number.isFinite(value)).toBe(true);
+ expect(applyOverlay({ ...tracked, browY: 0.9 }, overlayTarget('surprise')).browY).toBe(1);
+});
+
+test('switching fades in and out, then passes parameters through again', () => {
+ const overlay = new ExpressionOverlay();
+ overlay.set('smile');
+ const first = overlay.apply(tracked, 1 / 60);
+ expect(first.eyeSmile).toBeGreaterThan(0); expect(first.eyeSmile).toBeLessThan(1);
+ for (let i = 0; i < 120; i++) overlay.apply(tracked, 1 / 60);
+ expect(overlay.apply(tracked, 1 / 60).eyeSmile).toBeCloseTo(1, 3);
+ overlay.set('neutral'); expect(overlay.active).toBe(true);
+ for (let i = 0; i < 240 && overlay.active; i++) overlay.apply(tracked, 1 / 60);
+ expect(overlay.active).toBe(false); expect(overlay.apply(tracked, 1 / 60)).toBe(tracked);
+});
+
+test('unknown names, including inherited object keys, fall back to neutral', () => {
+ const overlay = new ExpressionOverlay();
+ for (const name of ['unknown', 'toString', '__proto__', 'constructor']) { overlay.set(name); expect(overlay.name).toBe('neutral'); }
+});