Skip to content

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

Add a clean avatar stream view with configurable backgrounds

shinshin8681a4892d0116
diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.js
index 9b0d0a4..d7d83a5 100644
--- a/src/engine/createMeshAvatar.js
+++ b/src/engine/createMeshAvatar.js
@@ -86,7 +86,7 @@ export async function createMeshAvatarImpl(canvas, options) {
// The source image is cut flat at its top edge (crown and right bun). A negative top margin
// keeps the top ~88px (7%) above the canvas, which the layout puts at the top of the panel:
// the cut stays off screen even at the deepest head tilt.
- const R = new Renderer(canvas, { padTop: options.padTop ?? rig.view.padTop, padSide: options.padSide ?? rig.view.padSide });
+ const R = new Renderer(canvas, { padTop: options.padTop ?? rig.view.padTop, padSide: options.padSide ?? rig.view.padSide, fit: options.fit });
const rects = { base: [0, 0, IMG.w, IMG.h], ...meta.layers };
// base layer, denser where hair strands bend and the face parts shift
diff --git a/src/engine/index.ts b/src/engine/index.ts
index 21c31bf..01cf9a8 100644
--- a/src/engine/index.ts
+++ b/src/engine/index.ts
@@ -9,6 +9,7 @@ export interface MeshAvatarOptions {
manual?: boolean;
padTop?: number;
padSide?: number;
+ fit?: 'contain' | 'cover';
}
export interface MeshAvatar {
readonly motions: { id: string; label: string; idle: boolean }[];
diff --git a/src/engine/renderer.js b/src/engine/renderer.js
index 0eaced5..88d1b12 100644
--- a/src/engine/renderer.js
+++ b/src/engine/renderer.js
@@ -198,8 +198,9 @@ export function createRenderer(engine, _rig) {
class Renderer {
// padTop / padSide: margin around the image, as a share of its height / width. A negative
// padTop pushes the top of the image above the canvas (hides a cut-off top edge).
- constructor(canvas, { padTop = 0, padSide = 0 } = {}) {
+ constructor(canvas, { padTop = 0, padSide = 0, fit = 'contain' } = {}) {
this.pad = { top: padTop, side: padSide };
+ this.fit = fit;
const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: true, alpha: true, preserveDrawingBuffer: true });
if (!gl) throw new Error('WebGL2 is not available');
this.gl = gl; this.canvas = canvas;
@@ -268,7 +269,7 @@ export function createRenderer(engine, _rig) {
const w = Math.round(c.clientWidth * dpr), h = Math.round(c.clientHeight * dpr);
if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
// fit the source image, anchored to the bottom so the cut-off body stays at the edge
- const s = Math.min(w / (IMG.w * (1 + 2 * this.pad.side)), h / (IMG.h * (1 + this.pad.top)));
+ const s = (this.fit === 'cover' ? Math.max : Math.min)(w / (IMG.w * (1 + 2 * this.pad.side)), h / (IMG.h * (1 + this.pad.top)));
const ox = (w - IMG.w * s) / 2, oy = h - IMG.h * s;
this.scale = [2 * s / w, -2 * s / h];
this.offset = [-1 + 2 * ox / w, 1 - 2 * oy / h];
diff --git a/src/live/avatar-view.ts b/src/live/avatar-view.ts
new file mode 100644
index 0000000..d4a4b27
--- /dev/null
+++ b/src/live/avatar-view.ts
@@ -0,0 +1,32 @@
+import { createMeshAvatar, type MeshAvatar } from '../engine';
+import { PARAMS } from '../engine/rig.js';
+import { localProjects, openLocalProject } from '../editor/project';
+import fixture from 'virtual:sample-rig';
+import { SAMPLE_PROJECT, type ViewSettings } from './settings';
+
+export const neutralParameters: Record<string, number> = Object.fromEntries(PARAMS.map(param => [param.id, param.def]));
+export interface FrameTiming { frames: number; totalMs: number; maxMs: number }
+export async function createAvatarView(canvas: HTMLCanvasElement, settings: ViewSettings,
+ beforeFrame?: (avatar: MeshAvatar, now: number, dt: number) => void) {
+ canvas.dataset.state = 'loading';
+ const projects = await localProjects(), project = projects?.find(entry => entry.name === settings.project);
+ if (project?.error || (!project && settings.project !== SAMPLE_PROJECT)) throw new Error('Project unavailable');
+ const loaded = project ? await openLocalProject(project) : { rig: fixture, assets: undefined };
+ const avatar = await createMeshAvatar(canvas, { rig: loaded.rig!, assets: loaded.assets, manual: true, fit: settings.fit });
+ avatar.setAutoIdle(settings.idle); avatar.setAutoMotion(settings.idle);
+ if (!settings.idle) avatar.setParameters(neutralParameters);
+ canvas.dataset.state = 'ready';
+ const timing: FrameTiming = { frames: 0, totalMs: 0, maxMs: 0 };
+ let raf = 0, previous = performance.now();
+ const frame = (now: number) => {
+ const dt = Math.min(0.05, Math.max(0.001, (now - previous) / 1000)); previous = now;
+ beforeFrame?.(avatar, now, dt);
+ const start = performance.now();
+ avatar.advance(dt, 1 / dt);
+ const elapsed = performance.now() - start;
+ timing.frames++; timing.totalMs += elapsed; timing.maxMs = Math.max(timing.maxMs, elapsed);
+ raf = requestAnimationFrame(frame);
+ };
+ raf = requestAnimationFrame(frame);
+ return { avatar, timing, destroy() { cancelAnimationFrame(raf); avatar.destroy(); } };
+}
diff --git a/src/live/settings.ts b/src/live/settings.ts
new file mode 100644
index 0000000..2e3707a
--- /dev/null
+++ b/src/live/settings.ts
@@ -0,0 +1,23 @@
+export const SAMPLE_PROJECT = 'sample-miko-qipao';
+export interface ViewSettings {
+ project: string;
+ background: string;
+ fit: 'contain' | 'cover';
+ idle: boolean;
+}
+export function backgroundColor(value: string | null): string {
+ if (value === 'green') return '#00ff00';
+ if (value === 'blue') return '#0000ff';
+ if (value && /^#?(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value)) return `#${value.replace('#', '')}`;
+ return 'transparent';
+}
+export function viewSettings(search: string): ViewSettings {
+ const query = new URLSearchParams(search), project = query.get('project');
+ return { project: project && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(project) ? project : SAMPLE_PROJECT,
+ background: backgroundColor(query.get('bg')), fit: query.get('fit') === 'cover' ? 'cover' : 'contain', idle: query.get('idle') !== '0' };
+}
+export function streamUrl(settings: ViewSettings, origin: string): string {
+ const url = new URL('/stream.html', origin);
+ url.search = new URLSearchParams({ project: settings.project, bg: settings.background, fit: settings.fit, idle: settings.idle ? '1' : '0' }).toString();
+ return url.href;
+}
diff --git a/src/live/stream.css b/src/live/stream.css
new file mode 100644
index 0000000..10a485e
--- /dev/null
+++ b/src/live/stream.css
@@ -0,0 +1,2 @@
+html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: transparent; }
+#avatar { display: block; width: 100%; height: 100%; }
diff --git a/src/live/stream.ts b/src/live/stream.ts
new file mode 100644
index 0000000..f9c5dd7
--- /dev/null
+++ b/src/live/stream.ts
@@ -0,0 +1,10 @@
+import { createAvatarView } from './avatar-view';
+import { viewSettings } from './settings';
+import './stream.css';
+
+const settings = viewSettings(location.search);
+document.documentElement.style.background = settings.background;
+const canvas = document.querySelector<HTMLCanvasElement>('#avatar')!;
+void createAvatarView(canvas, settings).then(view => {
+ window.addEventListener('pagehide', () => view.destroy(), { once: true });
+}).catch(() => { canvas.dataset.state = 'error'; });
diff --git a/stream.html b/stream.html
new file mode 100644
index 0000000..bef10e4
--- /dev/null
+++ b/stream.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Mesh Avatar Studio · Stream</title>
+ </head>
+ <body>
+ <canvas id="avatar"></canvas>
+ <script type="module" src="/src/live/stream.ts"></script>
+ </body>
+</html>
diff --git a/tests/stream-settings.test.ts b/tests/stream-settings.test.ts
new file mode 100644
index 0000000..fc61e08
--- /dev/null
+++ b/tests/stream-settings.test.ts
@@ -0,0 +1,13 @@
+import { expect, test } from 'vitest';
+import { backgroundColor, streamUrl, viewSettings } from '../src/live/settings';
+
+test('stream defaults are transparent, contained, idle and use the bundled sample', () => {
+ expect(viewSettings('')).toEqual({ project: 'sample-miko-qipao', background: 'transparent', fit: 'contain', idle: true });
+});
+test('background and query parsing accept colors but reject CSS and project paths', () => {
+ for (const [value, expected] of [['green', '#00ff00'], ['blue', '#0000ff'], ['#abc', '#abc'], ['123456', '#123456'], ['url(https://example.com)', 'transparent']]) expect(backgroundColor(value)).toBe(expected);
+ expect(viewSettings('?project=../private&bg=blue&fit=cover&idle=0')).toEqual({ project: 'sample-miko-qipao', background: '#0000ff', fit: 'cover', idle: false });
+ const settings = viewSettings('?project=nova&bg=%23123456&fit=cover&idle=0');
+ const url = new URL(streamUrl(settings, 'http://127.0.0.1:5173'));
+ expect(url.pathname).toBe('/stream.html'); expect(viewSettings(url.search)).toEqual(settings);
+});
diff --git a/vite.config.ts b/vite.config.ts
index c12db95..65e5f11 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -18,5 +18,6 @@ export default defineConfig({
},
}],
publicDir: 'samples',
+ build: { rollupOptions: { input: { editor: 'index.html', stream: 'stream.html' } } },
test: { include: ['tests/**/*.test.ts'] },
});