Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add rig editor with live preview
shinshin86f6c8f66e551a
diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.tsnew file mode 100644index 0000000..7cfccfa--- /dev/null+++ b/e2e/editor.spec.ts@@ -0,0 +1,100 @@+import { samplePresent, sampleSkipReason } from './sample';+import { expect, test } from '@playwright/test';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import fixture from '../samples/miko-qipao/rig.json' with { type: 'json' };++test('dragging a head handle synchronizes the inspector', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.goto('/');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ const canvas = page.getByTestId('editor');+ await expect(canvas).toHaveAttribute('data-scale', /0\./);+ await page.screenshot({ path: 'docs/screenshots/all-groups.png' });+ const box = (await canvas.boundingBox())!;+ const scale = Number(await canvas.getAttribute('data-scale'));+ const x = box.x + Number(await canvas.getAttribute('data-offset-x')) + 615 * scale;+ const y = box.y + Number(await canvas.getAttribute('data-offset-y')) + 400 * scale;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x + 20 * scale, y + 15 * scale, { steps: 4 });+ await page.mouse.up();+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('635');+ await expect(page.getByRole('spinbutton', { name: 'head.cy', exact: true })).toHaveValue('415');+ await page.screenshot({ path: 'docs/screenshots/head-drag.png' });+ await page.getByRole('button', { name: 'Undo', exact: true }).click();+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('615');+ await page.getByRole('button', { name: 'Redo', exact: true }).click();+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('635');+ const downloadPromise = page.waitForEvent('download');+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();+ const download = await downloadPromise;+ const saved = JSON.parse(await readFile((await download.path())!, 'utf8'));+ expect(saved.head.cx).toBe(635);+ expect(saved.head.cy).toBe(415);+ expect(saved.eyes[0].top).toEqual(fixture.eyes[0].top);+});++test('opens a validated rig and rejects malformed files without replacing the project', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.goto('/');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ const edited = structuredClone(fixture);+ edited.head.cx = 645;+ await page.getByLabel('Open rig file', { exact: true }).setInputFiles({ name: 'rig.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(edited)) });+ await page.getByLabel('Selected rig item').selectOption('head');+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('645');+ await page.getByLabel('Open rig file', { exact: true }).setInputFiles({ name: 'invalid.json', mimeType: 'application/json', buffer: Buffer.from('{"version":1}') });+ await expect(page.getByRole('alert')).toContainText('rig.image');+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('645');+});++test('rebuilds from cached assets, marks cut-outs stale, and sweeps angles', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ const assets: string[] = [];+ page.on('request', request => {+ if (new URL(request.url()).pathname.startsWith('/miko-qipao/')) assets.push(request.url());+ });+ await page.goto('/');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ const count = assets.length;+ const canvas = page.getByTestId('preview');+ const revision = Number(await canvas.getAttribute('data-revision'));+ await page.getByRole('checkbox', { name: 'Idle animation' }).uncheck();+ await expect.poll(async () => Number(await canvas.getAttribute('data-revision'))).toBeGreaterThan(revision);+ await page.getByRole('slider', { name: 'Angle X', exact: true }).focus();+ await page.getByRole('slider', { name: 'Angle X', exact: true }).press('End');+ await page.getByLabel('Selected rig item').selectOption('eyes');+ await page.getByText(`Eye · 1 · opening (${fixture.eyes[0].opening.length})`, { exact: true }).click();+ await page.getByRole('spinbutton', { name: 'eyes.0.opening.0.0', exact: true }).fill('451');+ await expect(page.getByText(/Layers are stale:/)).toBeVisible();+ await expect.poll(async () => Number(await canvas.getAttribute('data-revision'))).toBeGreaterThan(revision + 1);+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ expect(assets.length).toBe(count);+ await page.screenshot({ path: 'docs/screenshots/stale.png' });+ await page.getByRole('button', { name: 'Undo', exact: true }).click();+ await expect(page.getByText(/Layers are stale:/)).toBeHidden();+ await page.getByRole('button', { name: 'Stress test', exact: true }).click();+ await expect(page.getByRole('button', { name: 'Stop sweep' })).toBeVisible();+ for (let frame = 0; frame < 3; frame++) {+ await page.waitForTimeout(650);+ await page.screenshot({ path: `docs/screenshots/stress-${frame}.png` });+ }+ await page.getByRole('button', { name: 'Stop sweep', exact: true }).click();+ await expect(page.getByRole('button', { name: 'Stress test', exact: true })).toBeVisible();+});++test('opens a local image folder without the installed sample', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.route('**/miko-qipao/**', route => {+ if (new URL(route.request().url()).pathname.endsWith('.png')) return route.fulfill({ status: 404, body: '' });+ return route.continue();+ });+ await page.goto('/');+ await expect(page.getByRole('heading', { name: 'Open a project', exact: true })).toBeVisible();+ await page.getByLabel('Open image folder files', { exact: true }).setInputFiles(fileURLToPath(new URL('../samples/miko-qipao/', import.meta.url)));+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ await expect(page.getByTestId('editor')).toBeVisible();+ await page.getByLabel('Selected rig item').selectOption('head');+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('615');+});diff --git a/e2e/empty.spec.ts b/e2e/empty.spec.tsnew file mode 100644index 0000000..d402667--- /dev/null+++ b/e2e/empty.spec.ts@@ -0,0 +1,15 @@+import { expect, test } from '@playwright/test';++test('missing sample images show an empty workspace with project opening controls', async ({ page }) => {+ await page.route('**/miko-qipao/**', route => {+ if (new URL(route.request().url()).pathname.endsWith('.png')) return route.fulfill({ status: 404, body: '' });+ return route.continue();+ });+ await page.goto('/');+ await expect(page.getByRole('heading', { name: 'Open a project', exact: true })).toBeVisible();+ await expect(page.getByText('Open rig.json and an image folder to begin. Sample images are installed separately.')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Open rig', exact: true })).toBeEnabled();+ await expect(page.getByRole('button', { name: 'Open image folder', exact: true })).toBeEnabled();+ await expect(page.getByTestId('preview')).toHaveCount(0);+ await page.screenshot({ path: 'docs/screenshots/empty-workspace.png' });+});diff --git a/e2e/engine.spec.ts b/e2e/engine.spec.tsnew file mode 100644index 0000000..c2d442b--- /dev/null+++ b/e2e/engine.spec.ts@@ -0,0 +1,12 @@+import { samplePresent, sampleSkipReason } from './sample';+import { expect, test } from '@playwright/test';++test('renders the data-driven engine without browser errors', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto('/');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ await page.screenshot({ path: 'docs/screenshots/shell.png' });+ expect(errors).toEqual([]);+});diff --git a/e2e/preview-editing.spec.ts b/e2e/preview-editing.spec.tsnew file mode 100644index 0000000..dfcc3f1--- /dev/null+++ b/e2e/preview-editing.spec.ts@@ -0,0 +1,119 @@+import { samplePresent, sampleSkipReason } from './sample';+import { createHash } from 'node:crypto';+import { readFile, writeFile } from 'node:fs/promises';+import { expect, test, type Page } from '@playwright/test';+import { PNG } from 'pngjs';+import fixture from '../samples/miko-qipao/rig.json' with { type: 'json' };++const hash = (buffer: Buffer) => createHash('sha256').update(buffer).digest('hex');+async function drag(page: Page, point: [number, number], delta: [number, number]) {+ const canvas = page.getByTestId('editor');+ const box = (await canvas.boundingBox())!;+ const scale = Number(await canvas.getAttribute('data-scale'));+ const origin = [box.x + Number(await canvas.getAttribute('data-offset-x')), box.y + Number(await canvas.getAttribute('data-offset-y'))];+ const x = origin[0] + point[0] * scale, y = origin[1] + point[1] * scale;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x + delta[0] * scale, y + delta[1] * scale, { steps: 8 });+ await page.mouse.up();+}++test('strand and head drags change inspector, saved JSON and frozen preview pixels', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto('/');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ await page.getByRole('slider', { name: 'Angle X', exact: true }).focus();+ await page.getByRole('slider', { name: 'Angle X', exact: true }).press('End');+ const preview = page.getByTestId('preview');+ let revision = Number(await preview.getAttribute('data-revision'));+ await page.getByRole('checkbox', { name: 'Idle animation' }).uncheck();+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ const before = await preview.screenshot({ path: 'docs/screenshots/strand-before.png' });+ // Confirm that no idle animation can cause a false-positive pixel change.+ expect(hash(await preview.screenshot())).toBe(hash(before));+ revision = Number(await preview.getAttribute('data-revision'));+ await drag(page, [445, 340], [40, -10]);+ await page.getByText(`strands · 1 · nodes (${fixture.strands[0].nodes.length})`, { exact: true }).click();+ await expect(page.getByRole('spinbutton', { name: 'strands.0.nodes.2.0', exact: true })).toHaveValue('485');+ await expect(page.getByRole('spinbutton', { name: 'strands.0.nodes.2.1', exact: true })).toHaveValue('330');+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ const after = await preview.screenshot({ path: 'docs/screenshots/strand-after.png' });+ expect(hash(after)).not.toBe(hash(before));+ expect(hash(await preview.screenshot())).toBe(hash(after));+ const first = PNG.sync.read(before), second = PNG.sync.read(after);+ const difference = new PNG({ width: first.width, height: first.height });+ let changed = 0, hairChanged = 0;+ for (let y = 0; y < first.height; y++) for (let x = 0; x < first.width; x++) {+ const i = (y * first.width + x) * 4;+ const delta = Math.max(...[0, 1, 2, 3].map(channel => Math.abs(first.data[i + channel] - second.data[i + channel])));+ if (delta > 0) {+ changed++;+ if (x > first.width * 0.25 && x < first.width * 0.55 && y < first.height * 0.4) hairChanged++;+ }+ difference.data[i] = delta ? 255 : Math.round(first.data[i] * 0.3);+ difference.data[i + 1] = delta ? 30 : Math.round(first.data[i + 1] * 0.3);+ difference.data[i + 2] = delta ? 30 : Math.round(first.data[i + 2] * 0.3);+ difference.data[i + 3] = 255;+ }+ expect(hairChanged).toBeGreaterThan(100);+ await writeFile('docs/screenshots/strand-diff.png', PNG.sync.write(difference));+ await page.screenshot({ path: 'docs/screenshots/strand-editor.png' });+ revision = Number(await preview.getAttribute('data-revision'));+ await drag(page, [615, 400], [20, 15]);+ await expect(page.getByRole('spinbutton', { name: 'head.cx', exact: true })).toHaveValue('635');+ await expect(page.getByRole('spinbutton', { name: 'head.cy', exact: true })).toHaveValue('415');+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ const headAfter = await preview.screenshot({ path: 'docs/screenshots/head-preview.png' });+ expect(hash(headAfter)).not.toBe(hash(after));+ const downloadPromise = page.waitForEvent('download');+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();+ const download = await downloadPromise;+ const saved = JSON.parse(await readFile((await download.path())!, 'utf8'));+ expect(saved.strands[0].nodes[2]).toEqual([485, 330]);+ expect(saved.head.cx).toBe(635);+ expect(saved.head.cy).toBe(415);+ expect(saved.eyes).toEqual(fixture.eyes);+ expect(errors).toEqual([]);+ console.log(`Preview changes: ${changed} pixels, ${hairChanged} in the hair region`);+});++test('angle sliders retain the rendered pose after rebuilding and stopping a sweep', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.goto('/');+ const preview = page.getByTestId('preview');+ await expect(page.getByText('Engine ready', { exact: true })).toBeVisible();+ let revision = Number(await preview.getAttribute('data-revision'));+ await page.getByRole('checkbox', { name: 'Idle animation' }).uncheck();+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ const front = hash(await preview.screenshot());+ await page.getByRole('slider', { name: 'Angle X', exact: true }).press('End');+ await page.getByLabel('Selected rig item').selectOption('eyes');+ await page.getByText(`Eye · 1 · opening (${fixture.eyes[0].opening.length})`, { exact: true }).click();+ revision = Number(await preview.getAttribute('data-revision'));+ await page.getByRole('spinbutton', { name: 'eyes.0.opening.0.0', exact: true }).fill('451');+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ const turned = hash(await preview.screenshot());+ expect(turned).not.toBe(front);+ await expect(page.getByRole('slider', { name: 'Angle X', exact: true })).toHaveValue('30');+ const point = page.locator('.point-field').first();+ await expect(point.getByRole('spinbutton')).toHaveCount(2);+ await page.screenshot({ path: 'docs/screenshots/inspector-points-angle.png' });+ await page.getByLabel('Selected rig item').selectOption('head');+ await page.screenshot({ path: 'docs/screenshots/selected-band-lines.png' });+ await page.getByRole('button', { name: 'Stress test', exact: true }).click();+ await page.waitForTimeout(700);+ expect(hash(await preview.screenshot())).not.toBe(turned);+ revision = Number(await preview.getAttribute('data-revision'));+ await page.getByRole('button', { name: 'Stop sweep', exact: true }).click();+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);+ expect(hash(await preview.screenshot())).toBe(turned);+ await page.screenshot({ path: 'docs/screenshots/pose-after-sweep.png' });+ // Automatic completion restores the same slider-driven pose as a manual stop.+ await page.getByRole('button', { name: 'Stress test', exact: true }).click();+ await expect(page.getByRole('button', { name: 'Stress test', exact: true })).toBeVisible({ timeout: 10000 });+ await expect.poll(async () => hash(await preview.screenshot())).toBe(turned);+});diff --git a/e2e/sample.ts b/e2e/sample.tsnew file mode 100644index 0000000..1b6e58c--- /dev/null+++ b/e2e/sample.ts@@ -0,0 +1,10 @@+import { existsSync, readFileSync } from 'node:fs';++const metadata = JSON.parse(readFileSync(new URL('../samples/miko-qipao/built/layers.json', import.meta.url), 'utf8')) as { layers: Record<string, unknown> };+const sprites = JSON.parse(readFileSync(new URL('../samples/miko-qipao/built/sprites/sprites.json', import.meta.url), 'utf8')) as { layers: Record<string, unknown> };+const paths = ['source.png', 'built/base.png', 'built/hairmask.png',+ ...Object.keys(metadata.layers).map(name => `built/${name}.png`),+ ...Object.keys(sprites.layers).map(name => `built/sprites/${name}.png`)];+export const samplePresent = paths.every(path => existsSync(new URL(`../samples/miko-qipao/${path}`, import.meta.url)));+export const sampleSkipReason = 'Matching sample images are not installed; image-dependent checks are skipped.';+if (!samplePresent) console.info(sampleSkipReason);diff --git a/src/editor/App.tsx b/src/editor/App.tsxnew file mode 100644index 0000000..9ea4aef--- /dev/null+++ b/src/editor/App.tsx@@ -0,0 +1,150 @@+import { useEffect, useRef, useState } from 'react';+import fixture from 'virtual:sample-rig';+import { EditorCanvas } from './EditorCanvas';+import { setAt } from './model';+import type { Rig } from '../rig/types';+import { parseRig, validateRig } from '../rig/validate';+import { Preview } from './Preview';+import { RigHistory, downloadRig } from './history';+import { openImageFolder, sampleImagesAvailable } from './project';+import { layerSignature } from './stale';+import { RigFields } from './RigFields';+import './style.css';++export const GROUPS = ['head', 'body', 'face', 'eyes', 'mouth', 'cheeks', 'strands', 'accessories', 'hand', 'buns', 'mesh', 'view'] as const;++const builtSignature = layerSignature(parseRig(fixture));++export function App() {+ const [history] = useState(() => new RigHistory(parseRig(fixture)));+ const [rig, setRig] = useState(history.present);+ const fileInput = useRef<HTMLInputElement>(null);+ const folderInput = useRef<HTMLInputElement>(null);+ const projectOpened = useRef(false);+ const objectUrls = useRef<string[]>([]);+ const [sourceUrl, setSourceUrl] = useState('');+ const [assets, setAssets] = useState<Record<string, string> | undefined>(undefined);+ const [checking, setChecking] = useState(true);+ useEffect(() => {+ let cancelled = false;+ sampleImagesAvailable().then(available => {+ if (cancelled) return;+ if (available && !projectOpened.current) setSourceUrl('/miko-qipao/source.png');+ setChecking(false);+ });+ return () => { cancelled = true; objectUrls.current.forEach(url => URL.revokeObjectURL(url)); };+ }, []);+ const [visible, setVisible] = useState<string[]>([...GROUPS]);+ const [selected, setSelected] = useState<string | null>(null);+ const [error, setError] = useState('');+ const update = (next: Rig) => {+ const errors = validateRig(next);+ if (errors.length) { setError(errors.join('\n')); return; }+ setError('');+ history.change(next);+ setRig(history.present);+ };+ const openFile = async (file?: File) => {+ if (!file) return;+ try {+ update(parseRig(JSON.parse(await file.text())));+ setSelected(null);+ } catch (error) { setError(error instanceof Error ? error.message : String(error)); }+ };+ const openFolder = async (files: File[]) => {+ try {+ const project = await openImageFolder(files);+ projectOpened.current = true;+ if (project.rig) update(project.rig);+ objectUrls.current.forEach(url => URL.revokeObjectURL(url));+ objectUrls.current = project.urls;+ setSourceUrl(project.sourceUrl);+ setAssets(project.assets);+ setChecking(false);+ setError('');+ } catch (error) { setError(error instanceof Error ? error.message : String(error)); }+ };+ useEffect(() => {+ const keyboard = (event: KeyboardEvent) => {+ if (!(event.ctrlKey || event.metaKey)) return;+ const typing = event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement;+ if (event.key.toLowerCase() === 's') { event.preventDefault(); downloadRig(history.present); }+ if (!typing && event.key.toLowerCase() === 'z') {+ event.preventDefault();+ setRig(event.shiftKey ? history.redo() : history.undo());+ }+ };+ window.addEventListener('keydown', keyboard);+ return () => window.removeEventListener('keydown', keyboard);+ }, [history]);+ return (+ <main onDragOver={event => event.preventDefault()} onDrop={event => {+ event.preventDefault();+ void openFile(event.dataTransfer.files[0]);+ }}>+ <header className="toolbar">+ <div><h1>Mesh Avatar Studio</h1><p>Rig editor</p></div>+ <nav aria-label="Project tools">+ <input ref={fileInput} type="file" accept=".json,application/json" hidden aria-label="Open rig file"+ onChange={event => { void openFile(event.target.files?.[0]); event.target.value = ''; }} />+ <input ref={folderInput} type="file" multiple hidden aria-label="Open image folder files"+ {...{ webkitdirectory: '' }} onChange={event => {+ void openFolder(Array.from(event.target.files ?? []));+ event.target.value = '';+ }} />+ <button onClick={() => fileInput.current!.click()}>Open rig</button>+ <button onClick={() => folderInput.current!.click()}>Open image folder</button>+ <button onClick={() => downloadRig(rig)}>Save rig</button>+ <button disabled={!history.canUndo} onClick={() => setRig(history.undo())}>Undo</button>+ <button disabled={!history.canRedo} onClick={() => setRig(history.redo())}>Redo</button>+ </nav>+ </header>+ <div className="layer-bar" aria-label="Rig groups">+ {GROUPS.map(group => (+ <label key={group}>+ <input type="checkbox" checked={visible.includes(group)} onChange={() => setVisible(current =>+ current.includes(group) ? current.filter(value => value !== group) : [...current, group])} />+ {group}+ </label>+ ))}+ </div>+ {layerSignature(rig) !== builtSignature && (+ <p role="status" className="stale">Layers are stale: cut-out geometry changed. The existing images and eye curves are retained; re-cutting requires the planned layer builder.</p>+ )}+ {!sourceUrl && (+ <section className="panel empty-project">+ <h2>{checking ? 'Checking for sample images…' : 'Open a project'}</h2>+ <p>Open rig.json and an image folder to begin. Sample images are installed separately.</p>+ {error && <p role="alert" className="error">{error}</p>}+ </section>+ )}+ {sourceUrl && <div className="workspace">+ <section className="panel editor-panel">+ <div className="panel-title"><h2>Source & rig</h2><span>{rig.image.width} × {rig.image.height} px</span></div>+ <EditorCanvas sourceUrl={sourceUrl} rig={rig} visible={visible} selected={selected} onSelect={setSelected} onChange={update}+ onBegin={() => history.begin()} onEnd={() => {+ history.end();+ setRig(structuredClone(history.present));+ }} />+ </section>+ <Preview rig={rig} assets={assets} />+ <aside className="panel inspector">+ <h2>Selection</h2>+ <select aria-label="Selected rig item" value={selected ?? ''} onChange={event => setSelected(event.target.value || null)}>+ <option value="">Select a rig item</option>+ {GROUPS.map(group => <option key={group} value={group}>{group}</option>)}+ {(rig.strands ?? []).map((strand, i) => <option key={strand.name} value={`strands.${i}`}>{strand.name}</option>)}+ {selected && !GROUPS.includes(selected as typeof GROUPS[number]) && !/^strands\.\d+$/.test(selected) &&+ <option value={selected}>{selected}</option>}+ </select>+ {error && <p role="alert" className="error">{error}</p>}+ {!selected && <p className="muted">Select a rig handle to edit its fields.</p>}+ <div className="fields">+ {selected && <RigFields rig={rig} path={selected}+ onChange={(path, value) => update(setAt(rig, path, value))} /> }+ </div>+ </aside>+ </div>}+ </main>+ );+}diff --git a/src/editor/EditorCanvas.tsx b/src/editor/EditorCanvas.tsxnew file mode 100644index 0000000..2c19624--- /dev/null+++ b/src/editor/EditorCanvas.tsx@@ -0,0 +1,156 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import type { Point, Rig } from '../rig/types';+import { buildOverlay, changeVertex, imagePoint, moveHandle, nearestEdge, nearestHandle, screen, type Handle, type Viewport } from './model';++interface Props {+ rig: Rig;+ sourceUrl: string;+ visible: string[];+ selected: string | null;+ onSelect: (path: string) => void;+ onChange: (rig: Rig) => void;+ onBegin?: () => void;+ onEnd?: () => void;+}+const colors: Record<string, string> = {+ head: '#159447', body: '#7c4dce', face: '#d72c68', eyes: '#0098a8', mouth: '#ea671a',+ cheeks: '#d05383', strands: '#ca9b00', accessories: '#cf3030', hand: '#6c55d8',+ buns: '#ba31ad', mesh: '#5a6a7c', view: '#2b69d5',+};+export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChange, onBegin, onEnd }: Props) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const source = useRef<HTMLImageElement | null>(null);+ const [imageReady, setImageReady] = useState(false);+ const [size, setSize] = useState({ width: 600, height: 600 });+ const [view, setView] = useState<Viewport>({ scale: 1, x: 0, y: 0 });+ const [zoom, setZoom] = useState(1);+ const [pan, setPan] = useState<Point>([0, 0]);+ const space = useRef(false);+ const drag = useRef<{ handle?: Handle; rig: Rig; start: Point; pan: Point; offset: Point } | null>(null);+ const overlay = useMemo(() => buildOverlay(rig), [rig]);+ const handles = overlay.handles.filter(h => visible.includes(h.group));+ const shapes = overlay.shapes.filter(s => visible.includes(s.group));+ useEffect(() => {+ const image = new Image();+ image.onload = () => { source.current = image; setImageReady(true); };+ image.src = sourceUrl;+ const observer = new ResizeObserver(entries => {+ const rect = entries[0].contentRect;+ setSize({ width: rect.width, height: rect.height });+ });+ observer.observe(canvas.current!);+ return () => { image.onload = null; observer.disconnect(); };+ }, [sourceUrl]);+ useEffect(() => {+ const scale = Math.min(size.width / rig.image.width, size.height / rig.image.height) * zoom;+ setView({ scale, x: (size.width - rig.image.width * scale) / 2 + pan[0],+ y: (size.height - rig.image.height * scale) / 2 + pan[1] });+ }, [size, rig.image.width, rig.image.height, zoom, pan]);+ useEffect(() => {+ const element = canvas.current!;+ element.width = Math.round(size.width);+ element.height = Math.round(size.height);+ const context = element.getContext('2d')!;+ context.fillStyle = '#f9fafc';+ context.fillRect(0, 0, element.width, element.height);+ if (imageReady && source.current) {+ context.globalAlpha = 0.7;+ context.drawImage(source.current, view.x, view.y, rig.image.width * view.scale, rig.image.height * view.scale);+ context.globalAlpha = 1;+ }+ for (const shape of shapes) {+ if (shape.band && selected?.split('.')[0] !== shape.group) continue;+ const active = selected === shape.item || (selected !== null && shape.item.startsWith(`${selected}.`));+ context.strokeStyle = active ? '#004ef0' : colors[shape.group];+ context.lineWidth = active ? 2.5 : 1;+ context.beginPath();+ if (shape.kind === 'ellipse') {+ const [x, y] = screen(shape.points[0], view);+ context.ellipse(x, y, shape.radius![0] * view.scale, shape.radius![1] * view.scale, shape.angle ?? 0, 0, Math.PI * 2);+ } else {+ shape.points.forEach((point, i) => {+ const [x, y] = screen(point, view);+ if (i === 0) context.moveTo(x, y); else context.lineTo(x, y);+ });+ if (shape.closed) context.closePath();+ }+ context.stroke();+ }+ for (const handle of handles) {+ const [x, y] = screen(handle.point, view);+ const active = selected === handle.item;+ context.beginPath();+ context.arc(x, y, active ? 5 : 3.5, 0, Math.PI * 2);+ context.fillStyle = active ? '#004ef0' : colors[handle.group];+ context.fill();+ context.strokeStyle = '#ffffff';+ context.lineWidth = 1;+ context.stroke();+ }+ }, [rig, handles, shapes, selected, size, imageReady, view]);+ const local = (event: { clientX: number; clientY: number }): Point => {+ const rect = canvas.current!.getBoundingClientRect();+ return [event.clientX - rect.left, event.clientY - rect.top];+ };+ return (+ <>+ <canvas ref={canvas} className="editor-canvas" data-testid="editor" tabIndex={0}+ aria-label="Rig editor canvas" data-scale={view.scale} data-offset-x={view.x} data-offset-y={view.y}+ onKeyDown={event => { if (event.code === 'Space') { event.preventDefault(); space.current = true; } }}+ onKeyUp={event => { if (event.code === 'Space') space.current = false; }}+ onBlur={() => { space.current = false; }}+ onContextMenu={event => event.preventDefault()}+ onWheel={event => {+ event.preventDefault();+ const point = local(event), ratio = Math.exp(-event.deltaY * 0.001);+ const nextZoom = Math.min(8, Math.max(0.25, zoom * ratio));+ const effective = nextZoom / zoom;+ setZoom(nextZoom);+ setPan([pan[0] + (point[0] - size.width / 2 - pan[0]) * (1 - effective),+ pan[1] + (point[1] - size.height / 2 - pan[1]) * (1 - effective)]);+ }}+ onPointerDown={event => {+ event.preventDefault();+ event.currentTarget.focus();+ const point = local(event);+ if (event.button === 1 || space.current) {+ drag.current = { rig, start: point, pan, offset: [0, 0] };+ } else if (event.button === 0) {+ const handle = nearestHandle(handles, point, view);+ if (!handle) return;+ onSelect(handle.item);+ if (event.altKey && handle.vertex) {+ onChange(changeVertex(rig, handle.vertex.path, handle.vertex.index, null, handle.vertex.closed));+ return;+ }+ const origin = imagePoint(point, view);+ drag.current = { handle, rig, start: point, pan, offset: [handle.point[0] - origin[0], handle.point[1] - origin[1]] };+ onBegin?.();+ } else return;+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={event => {+ if (!drag.current) return;+ const point = local(event), current = drag.current;+ if (!current.handle) setPan([current.pan[0] + point[0] - current.start[0], current.pan[1] + point[1] - current.start[1]]);+ else {+ const target = imagePoint(point, view);+ onChange(moveHandle(current.rig, current.handle, [target[0] + current.offset[0], target[1] + current.offset[1]]));+ }+ }}+ onPointerUp={() => { if (drag.current?.handle) onEnd?.(); drag.current = null; }}+ onPointerCancel={() => { if (drag.current?.handle) onEnd?.(); drag.current = null; }}+ onDoubleClick={event => {+ const edge = nearestEdge(shapes, local(event), view);+ if (edge) {+ onSelect(edge.shape.item);+ onChange(changeVertex(rig, edge.shape.item, edge.index, edge.point, !!edge.shape.closed));+ }+ }} />+ <div className="canvas-help">+ Drag handles · double-click edges to insert · Alt-click vertices to remove · wheel to zoom · Space-drag to pan+ <button style={{ marginLeft: 8, padding: '3px 7px' }} onClick={() => { setZoom(1); setPan([0, 0]); }}>Fit</button>+ </div>+ </>+ );+}diff --git a/src/editor/NumericField.tsx b/src/editor/NumericField.tsxnew file mode 100644index 0000000..3c7ae9e--- /dev/null+++ b/src/editor/NumericField.tsx@@ -0,0 +1,19 @@+import { useEffect, useState } from 'react';++export function NumericField({ path, value, label, onChange }: {+ path: string; label?: string; value: number; onChange: (value: number) => void;+}) {+ const [draft, setDraft] = useState(String(value));+ useEffect(() => setDraft(String(value)), [value]);+ return (+ <label title={path}>{label ?? path.split('.').at(-1)}+ <input type="number" step="0.1" aria-label={path} value={draft}+ onChange={event => {+ setDraft(event.target.value);+ const number = event.target.valueAsNumber;+ if (Number.isFinite(number)) onChange(number);+ }}+ onBlur={() => setDraft(String(value))} />+ </label>+ );+}diff --git a/src/editor/Preview.tsx b/src/editor/Preview.tsxnew file mode 100644index 0000000..2c97fdb--- /dev/null+++ b/src/editor/Preview.tsx@@ -0,0 +1,102 @@+import { useEffect, useRef, useState } from 'react';+import { createMeshAvatar, type MeshAvatar } from '../engine';+import { PARAMS } from '../engine/rig.js';+import type { Rig } from '../rig/types';++const defaults: Record<string, number> = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));+const sliders = [+ { id: 'ParamAngleX', label: 'Angle X', min: -30, max: 30, def: 0 },+ { id: 'ParamAngleY', label: 'Angle Y', min: -30, max: 30, def: 0 },+ { id: 'ParamAngleZ', label: 'Angle Z', min: -30, max: 30, def: 0 },+ { id: 'EyeOpen', label: 'Eye open', min: 0, max: 1.25, def: 1 },+ { id: 'ParamMouthOpenY', label: 'Mouth open', min: 0, max: 1, def: 0 },+ { id: 'ParamBodyAngleZ', label: 'Body roll', min: -10, max: 10, def: 0 },+];+export function Preview({ rig, assets }: { rig: Rig; assets?: Record<string, string> }) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const avatar = useRef<MeshAvatar | null>(null);+ const [status, setStatus] = useState('Loading local assets…');+ const [revision, setRevision] = useState(0);+ const [idle, setIdle] = useState(true);+ const [stress, setStress] = useState(false);+ const [parameters, setParameters] = useState<Record<string, number>>({});+ const controls = useRef({ idle, stress, parameters });+ controls.current = { idle, stress, parameters };+ useEffect(() => {+ let cancelled = false;+ let instance: MeshAvatar | undefined;+ setStatus('Updating preview…');+ const timer = setTimeout(() => {+ createMeshAvatar(canvas.current!, { rig, assets, assetsBase: '/miko-qipao/built/', manual: true }).then(value => {+ if (cancelled) { value.destroy(); return; }+ instance = value;+ avatar.current = value;+ const control = controls.current;+ value.setAutoIdle(control.idle && !control.stress);+ value.setAutoMotion(control.idle && !control.stress);+ value.setParameters(control.idle && !control.stress ? control.parameters : { ...defaults, ...control.parameters });+ // A paused preview uses a fixed warm-up so edited rigs are compared at the same physics time.+ value.advance(control.idle && !control.stress ? 1 / 60 : 1);+ setRevision(current => current + 1);+ setStatus('Engine ready');+ }).catch(error => { if (!cancelled) setStatus(String(error)); });+ }, 150);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ instance?.destroy();+ if (avatar.current === instance) avatar.current = null;+ };+ }, [rig, idle, stress, assets]);+ useEffect(() => {+ const value = avatar.current;+ if (!value) return;+ value.setAutoIdle(idle && !stress);+ value.setAutoMotion(idle && !stress);+ value.setParameters(idle && !stress ? parameters : { ...defaults, ...parameters });+ value.advance(0);+ if (!idle && !stress) return;+ let raf = 0;+ const start = performance.now();+ const frame = (now: number) => {+ if (stress) {+ const t = (now - start) / 1000;+ value.setParameters({ ...defaults, ...parameters,+ ParamAngleX: Math.sin(t * 2) * 30, ParamAngleY: Math.cos(t * 1.3) * 25,+ ParamAngleZ: Math.sin(t * 1.1) * 25, ParamBodyAngleZ: Math.cos(t * 0.7) * 8 });+ if (t >= 6) { setStress(false); return; }+ }+ value.advance(1 / 60);+ raf = requestAnimationFrame(frame);+ };+ raf = requestAnimationFrame(frame);+ return () => cancelAnimationFrame(raf);+ }, [rig, assets, idle, stress, parameters, revision]);+ return (+ <section className="panel preview-panel">+ <div className="panel-title"><h2>Live preview</h2><span role="status">{status}</span></div>+ <canvas ref={canvas} data-testid="preview" data-revision={revision} className="preview-canvas"+ style={{ aspectRatio: `${rig.image.width * (1 + 2 * rig.view.padSide)} / ${rig.image.height * (1 + rig.view.padTop)}` }} />+ <div className="preview-tools">+ <label><input type="checkbox" checked={idle} onChange={event => setIdle(event.target.checked)} /> Idle animation</label>+ <button onClick={() => setStress(current => !current)}>{stress ? 'Stop sweep' : 'Stress test'}</button>+ <button onClick={() => { setParameters({}); setStress(false); }}>Reset pose</button>+ </div>+ <div className="sliders">+ {sliders.map(slider => (+ <label key={slider.id}>{slider.label}+ <input type="range" aria-label={slider.label} min={slider.min} max={slider.max} step="0.05"+ value={parameters[slider.id === 'EyeOpen' ? 'ParamEyeLOpen' : slider.id] ?? slider.def}+ onChange={event => {+ const value = Number(event.target.value);+ setParameters(current => slider.id === 'EyeOpen'+ ? { ...current, ParamEyeLOpen: value, ParamEyeROpen: value }+ : { ...current, [slider.id]: value });+ }} />+ <output>{(parameters[slider.id === 'EyeOpen' ? 'ParamEyeLOpen' : slider.id] ?? slider.def).toFixed(2)}</output>+ </label>+ ))}+ </div>+ </section>+ );+}diff --git a/src/editor/RigFields.tsx b/src/editor/RigFields.tsxnew file mode 100644index 0000000..8267aea--- /dev/null+++ b/src/editor/RigFields.tsx@@ -0,0 +1,29 @@+import type { Rig } from '../rig/types';+import { getAt } from './model';+import { NumericField } from './NumericField';++function title(path: string) {+ return path.split('.').map((part, index, parts) => {+ if (/^\d+$/.test(part)) return String(Number(part) + 1);+ if (part === 'eyes') return 'Eye';+ if (/^\d+$/.test(parts[index + 1] ?? '') && ['opening', 'roi', 'nodes', 'outline', 'jaw'].includes(part)) return `${part} · point`;+ return part.replace(/([a-z])([A-Z])/g, '$1 $2');+ }).join(' · ');+}++export function RigFields({ rig, path, onChange }: {+ rig: Rig; path: string; onChange: (path: string, value: number) => void;+}) {+ const value = getAt(rig, path);+ if (typeof value === 'number') return <NumericField path={path} label={title(path)} value={value} onChange={number => onChange(path, number)} />;+ if (!value || typeof value !== 'object') return null;+ if (Array.isArray(value) && value.length === 2 && value.every(v => typeof v === 'number') && !/band$/i.test(path)) {+ return <div className="point-field"><span>{title(path)}</span><div className="point-inputs">+ {value.map((number, index) => <NumericField key={index} path={`${path}.${index}`} label={index === 0 ? 'x' : 'y'}+ value={number} onChange={next => onChange(`${path}.${index}`, next)} />)}+ </div><small>{path}</small></div>;+ }+ const children = Object.entries(value).map(([key]) => <RigFields key={key} rig={rig} path={`${path}.${key}`} onChange={onChange} />);+ if (Array.isArray(value)) return <details open={path === 'eyes' || path === 'strands'}><summary>{title(path)} ({value.length})</summary><div className="fields">{children}</div></details>;+ return <>{children}</>;+}diff --git a/src/editor/history.ts b/src/editor/history.tsnew file mode 100644index 0000000..e19f68d--- /dev/null+++ b/src/editor/history.ts@@ -0,0 +1,48 @@+import type { Rig } from '../rig/types';++export class RigHistory {+ present: Rig;+ private past: Rig[] = [];+ private future: Rig[] = [];+ private gesture: Rig | null = null;+ constructor(rig: Rig) { this.present = structuredClone(rig); }+ get canUndo() { return this.past.length > 0; }+ get canRedo() { return this.future.length > 0; }+ begin() { if (!this.gesture) this.gesture = structuredClone(this.present); }+ change(rig: Rig) {+ if (JSON.stringify(rig) === JSON.stringify(this.present)) return;+ if (!this.gesture) {+ this.past.push(structuredClone(this.present));+ this.future = [];+ }+ this.present = structuredClone(rig);+ }+ end() {+ if (this.gesture && JSON.stringify(this.gesture) !== JSON.stringify(this.present)) {+ this.past.push(this.gesture);+ this.future = [];+ }+ this.gesture = null;+ }+ undo() {+ this.end();+ const previous = this.past.pop();+ if (previous) { this.future.push(structuredClone(this.present)); this.present = previous; }+ return structuredClone(this.present);+ }+ redo() {+ this.end();+ const next = this.future.pop();+ if (next) { this.past.push(structuredClone(this.present)); this.present = next; }+ return structuredClone(this.present);+ }+}++export function downloadRig(rig: Rig) {+ const url = URL.createObjectURL(new Blob([JSON.stringify(rig, null, 2) + '\n'], { type: 'application/json' }));+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = 'rig.json';+ anchor.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}diff --git a/src/editor/model.ts b/src/editor/model.tsnew file mode 100644index 0000000..fbc613e--- /dev/null+++ b/src/editor/model.ts@@ -0,0 +1,169 @@+import type { Point, Rig } from '../rig/types';++export interface Viewport { scale: number; x: number; y: number }+export interface Handle {+ id: string;+ item: string;+ group: string;+ point: Point;+ xPath: string;+ yPath?: string;+ radius?: { axis: 'x' | 'y'; center: Point; angle: number };+ vertex?: { path: string; index: number; closed: boolean };+}+export interface Shape {+ item: string;+ group: string;+ kind: 'ellipse' | 'line';+ points: Point[];+ closed?: boolean;+ editable?: boolean;+ band?: boolean;+ radius?: Point;+ angle?: number;+}+export function getAt(root: unknown, path: string): unknown {+ return path.split('.').filter(Boolean).reduce<unknown>((value, key) =>+ value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined, root);+}+export function setAt(rig: Rig, path: string, value: unknown): Rig {+ const next = structuredClone(rig);+ const parts = path.split('.');+ let target = next as unknown as Record<string, unknown>;+ for (const part of parts.slice(0, -1)) target = target[part] as Record<string, unknown>;+ target[parts.at(-1)!] = value;+ return next;+}+export function numericFields(value: unknown, path: string): { path: string; value: number }[] {+ if (typeof value === 'number') return [{ path, value }];+ if (!value || typeof value !== 'object') return [];+ return Object.entries(value).flatMap(([key, child]) => numericFields(child, path ? `${path}.${key}` : key));+}+export function screen(point: Point, view: Viewport): Point {+ return [point[0] * view.scale + view.x, point[1] * view.scale + view.y];+}+export function imagePoint(point: Point, view: Viewport): Point {+ return [(point[0] - view.x) / view.scale, (point[1] - view.y) / view.scale];+}+export function nearestHandle(handles: Handle[], point: Point, view: Viewport, threshold = 8): Handle | undefined {+ let nearest: Handle | undefined;+ let distance = threshold;+ for (const handle of handles) {+ const p = screen(handle.point, view);+ const d = Math.hypot(p[0] - point[0], p[1] - point[1]);+ if (d <= distance) { distance = d; nearest = handle; }+ }+ return nearest;+}+export function moveHandle(rig: Rig, handle: Handle, point: Point): Rig {+ const rounded = (value: number) => Math.round(value * 10) / 10;+ if (handle.radius) {+ const { center, axis, angle } = handle.radius;+ const dx = point[0] - center[0], dy = point[1] - center[1];+ const amount = axis === 'x' ? dx * Math.cos(angle) + dy * Math.sin(angle)+ : -dx * Math.sin(angle) + dy * Math.cos(angle);+ return setAt(rig, handle.xPath, Math.max(1, rounded(Math.abs(amount))));+ }+ return setAt(setAt(rig, handle.xPath, rounded(point[0])), handle.yPath!, rounded(point[1]));+}+export function changeVertex(rig: Rig, path: string, index: number, point: Point | null, closed: boolean): Rig {+ const points = structuredClone(getAt(rig, path)) as Point[];+ if (point) points.splice(index, 0, point);+ else if (points.length > (closed ? 3 : 2)) points.splice(index, 1);+ return setAt(rig, path, points);+}+export function nearestEdge(shapes: Shape[], point: Point, view: Viewport) {+ let best: { shape: Shape; index: number; point: Point } | undefined;+ let distance = 8;+ for (const shape of shapes.filter(s => s.editable)) {+ const count = shape.closed ? shape.points.length : shape.points.length - 1;+ for (let i = 0; i < count; i++) {+ const a = screen(shape.points[i], view), b = screen(shape.points[(i + 1) % shape.points.length], view);+ const dx = b[0] - a[0], dy = b[1] - a[1];+ const t = Math.max(0, Math.min(1, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / (dx * dx + dy * dy || 1)));+ const closest: Point = [a[0] + dx * t, a[1] + dy * t];+ const d = Math.hypot(point[0] - closest[0], point[1] - closest[1]);+ if (d < distance) { distance = d; best = { shape, index: i + 1, point: imagePoint(closest, view) }; }+ }+ }+ return best;+}+export function buildOverlay(rig: Rig): { handles: Handle[]; shapes: Shape[] } {+ const handles: Handle[] = [], shapes: Shape[] = [];+ const pointHandle = (item: string, group: string, point: Point, xPath: string, yPath: string, id = item) =>+ handles.push({ id, item, group, point, xPath, yPath });+ function walk(value: unknown, path: string, group: string) {+ if (!value || typeof value !== 'object') return;+ const key = path.split('.').at(-1)!;+ if (Array.isArray(value)) {+ if (value.length >= 2 && value.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number'))) {+ const points = value as Point[];+ const closed = ['opening', 'roi', 'outline', 'background'].includes(key);+ const editable = closed || ['nodes', 'jaw'].includes(key);+ if (group !== 'cheeks') shapes.push({ item: path, group, kind: 'line', points, closed, editable });+ points.forEach((point, index) => {+ const item = group === 'strands' ? path.split('.').slice(0, 2).join('.') : path;+ const handle: Handle = { id: `${path}.${index}`, item, group, point,+ xPath: `${path}.${index}.0`, yPath: `${path}.${index}.1` };+ if (editable) handle.vertex = { path, index, closed };+ handles.push(handle);+ });+ return;+ }+ if (value.length === 2 && value.every(v => typeof v === 'number')) {+ if (!key.toLowerCase().endsWith('band') && !['band', 'jawRange'].includes(key))+ pointHandle(path, group, value as Point, `${path}.0`, `${path}.1`);+ else if (group !== 'hand' || !key.startsWith('fingerX')) {+ value.forEach((y, i) => {+ const center = group === 'body' ? rig.body.chest.cx : rig.head.cx;+ shapes.push({ item: path, group, kind: 'line', band: true, points: [[0, y], [rig.image.width, y]] });+ handles.push({ id: `${path}.${i}`, item: path, group, point: [center, y],+ xPath: `${path}.${i}`, radius: { axis: 'y', center: [center, 0], angle: 0 } });+ });+ }+ return;+ }+ if (key === 'box' && value.length === 4) {+ const [x0, y0, x1, y1] = value as number[];+ shapes.push({ item: path, group, kind: 'line', points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], closed: true });+ pointHandle(path, group, [x0, y0], `${path}.0`, `${path}.1`, `${path}.start`);+ pointHandle(path, group, [x1, y1], `${path}.2`, `${path}.3`, `${path}.end`);+ return;+ }+ value.forEach((child, index) => walk(child, `${path}.${index}`, group));+ return;+ }+ const object = value as Record<string, unknown>;+ if (typeof object.cx === 'number' && typeof object.cy === 'number') {+ const center: Point = [object.cx, object.cy];+ pointHandle(path, group, center, `${path}.cx`, `${path}.cy`, `${path}.center`);+ if (typeof object.rx === 'number' && typeof object.ry === 'number') {+ const angle = typeof object.angle === 'number' ? object.angle : 0;+ shapes.push({ item: path, group, kind: 'ellipse', points: [center], radius: [object.rx, object.ry], angle });+ for (const axis of ['x', 'y'] as const) {+ const theta = angle + (axis === 'y' ? Math.PI / 2 : 0);+ const radius = axis === 'x' ? object.rx : object.ry;+ handles.push({ id: `${path}.r${axis}`, item: path, group,+ point: [center[0] + Math.cos(theta) * radius, center[1] + Math.sin(theta) * radius],+ xPath: `${path}.r${axis}`, radius: { axis, center, angle } });+ }+ }+ if (typeof object.halfLen === 'number' && typeof object.angle === 'number') {+ shapes.push({ item: path, group, kind: 'line', points: [-1, 1].map(sign =>+ [center[0] + sign * (object.halfLen as number) * Math.cos(object.angle as number),+ center[1] + sign * (object.halfLen as number) * Math.sin(object.angle as number)]) });+ }+ }+ if (typeof object.pivotX === 'number' && typeof object.pivotY === 'number')+ pointHandle(path, group, [object.pivotX, object.pivotY], `${path}.pivotX`, `${path}.pivotY`, `${path}.pivot`);+ if (['x0', 'y0', 'x1', 'y1'].every(key => typeof object[key] === 'number')) {+ const { x0, y0, x1, y1 } = object as Record<string, number>;+ shapes.push({ item: path, group, kind: 'line', points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], closed: true });+ pointHandle(path, group, [x0, y0], `${path}.x0`, `${path}.y0`, `${path}.start`);+ pointHandle(path, group, [x1, y1], `${path}.x1`, `${path}.y1`, `${path}.end`);+ }+ Object.entries(object).forEach(([key, child]) => walk(child, `${path}.${key}`, group));+ }+ Object.entries(rig).forEach(([group, value]) => { if (group !== 'image') walk(value, group, group); });+ return { handles, shapes };+}diff --git a/src/editor/project.ts b/src/editor/project.tsnew file mode 100644index 0000000..717e136--- /dev/null+++ b/src/editor/project.ts@@ -0,0 +1,42 @@+import { parseRig } from '../rig/validate';+import type { Rig } from '../rig/types';++export interface ProjectAssets {+ sourceUrl: string;+ assets: Record<string, string>;+ rig?: Rig;+ urls: string[];+}+export async function openImageFolder(files: File[]): Promise<ProjectAssets> {+ const entries = files.map(file => ({ file, path: file.webkitRelativePath.replace(/^[^/]+\//, '') || file.name }));+ const source = entries.find(entry => /(^|\/)source\.png$/i.test(entry.path));+ const layers = entries.find(entry => /(^|\/)layers\.json$/i.test(entry.path));+ if (!source || !layers) throw new Error('Choose a project folder containing source.png, layers.json and the cut-out images.');+ const prefix = layers.path.slice(0, -'layers.json'.length);+ const rigFile = entries.find(entry => /(^|\/)rig\.json$/i.test(entry.path));+ const rig = rigFile ? parseRig(JSON.parse(await rigFile.file.text())) : undefined;+ const metadata = JSON.parse(await layers.file.text()) as { layers?: Record<string, unknown> };+ if (!metadata.layers || typeof metadata.layers !== 'object') throw new Error('layers.json must contain layer rectangles.');+ const available = new Set(entries.filter(entry => entry.path.startsWith(prefix)).map(entry => entry.path.slice(prefix.length)));+ const required = ['base.png', 'hairmask.png', ...Object.keys(metadata.layers).map(name => `${name}.png`)];+ const missing = required.filter(name => !available.has(name));+ if (missing.length) throw new Error(`Missing image files: ${missing.join(', ')}`);+ const urls: string[] = [];+ const sourceUrl = URL.createObjectURL(source.file);+ urls.push(sourceUrl);+ const assets = Object.fromEntries(entries.filter(entry => entry.path.startsWith(prefix)).map(entry => {+ const url = URL.createObjectURL(entry.file);+ urls.push(url);+ return [entry.path.slice(prefix.length), url];+ }));+ return { sourceUrl, assets, rig, urls };+}++export function sampleImagesAvailable(): Promise<boolean> {+ return Promise.all(['/miko-qipao/source.png', '/miko-qipao/built/base.png'].map(url => new Promise<boolean>(resolve => {+ const image = new Image();+ image.onload = () => resolve(true);+ image.onerror = () => resolve(false);+ image.src = url;+ }))).then(results => results.every(Boolean));+}diff --git a/src/editor/stale.ts b/src/editor/stale.tsnew file mode 100644index 0000000..5544ece--- /dev/null+++ b/src/editor/stale.ts@@ -0,0 +1,13 @@+import type { Rig } from '../rig/types';++export function layerSignature(rig: Rig) {+ return JSON.stringify({+ image: rig.image,+ eyes: rig.eyes,+ hand: rig.hand ? {+ outline: rig.hand.outline, jaw: rig.hand.jaw,+ jawRange: rig.hand.jawRange, background: rig.hand.background,+ } : null,+ accessories: (rig.accessories ?? []).map(part => ({ name: part.name, box: part.box, color: part.color })),+ });+}diff --git a/src/editor/style.css b/src/editor/style.cssnew file mode 100644index 0000000..5cda130--- /dev/null+++ b/src/editor/style.css@@ -0,0 +1,59 @@+:root {+ font-family: Inter, ui-sans-serif, system-ui, sans-serif;+ color: #233246;+ background: #edf1f5;+ font-synthesis: none;+}+* { box-sizing: border-box; }+body { margin: 0; }+main { padding: 20px; }+h1 { font-size: 22px; letter-spacing: -0.4px; margin: 0; }+h2 { font-size: 14px; margin: 0; }+p { font-size: 12px; margin: 6px 0; }+button, input { font: inherit; }+button {+ color: #243448;+ background: white;+ border: 1px solid #c9d3df;+ border-radius: 6px;+ padding: 8px 12px;+ cursor: pointer;+}+button:hover:not(:disabled) { border-color: #2563eb; color: #2563eb; }+button:disabled { opacity: 0.45; cursor: default; }+.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }+.toolbar nav { display: flex; gap: 8px; }+.layer-bar { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 16px; font-size: 12px; }+.layer-bar label { display: flex; align-items: center; gap: 4px; }+.workspace { display: grid; grid-template-columns: minmax(340px, 1.25fr) minmax(300px, 1fr) 280px; gap: 16px; }+.panel { background: white; border: 1px solid #d7dfe8; border-radius: 10px; overflow: hidden; }+.panel-title { display: flex; justify-content: space-between; align-items: center; padding: 14px; border-bottom: 1px solid #e4e9ef; }+.panel-title span { font-size: 11px; color: #61758c; }+.source-image { width: 100%; height: 600px; object-fit: contain; display: block; }+.preview-canvas { display: block; width: 100%; height: auto; }+.inspector { padding: 16px; max-height: 760px; overflow: auto; }+.muted { color: #6b7f94; line-height: 1.6; }+.editor-canvas { display: block; width: 100%; height: 600px; touch-action: none; outline: none; }+.canvas-help { padding: 10px 14px; font-size: 11px; color: #61758c; border-top: 1px solid #e4e9ef; }+.fields { display: grid; gap: 8px; margin-top: 14px; }+.fields label { display: grid; gap: 4px; font-size: 11px; overflow-wrap: anywhere; }+.fields input { width: 100%; padding: 6px 8px; border: 1px solid #cad5e1; border-radius: 4px; }+.error { color: #a12828; background: #fff1f1; padding: 8px; font-size: 12px; white-space: pre-wrap; }+.stale { color: #7c4b05; background: #fff6dd; padding: 10px 14px; font-size: 12px; margin: 10px 0; }+.sliders { padding: 14px; display: grid; gap: 8px; }+.sliders label { display: grid; grid-template-columns: 100px 1fr 35px; align-items: center; gap: 8px; font-size: 12px; }+.preview-tools { padding: 10px 14px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; font-size: 12px; }+@media (max-width: 1050px) {+ .workspace { grid-template-columns: 1fr 1fr; }+ .inspector { grid-column: 1 / -1; }+ .toolbar { align-items: flex-start; gap: 12px; }+ .toolbar nav { flex-wrap: wrap; }+}++.empty-project { padding: 48px 24px; text-align: center; }++.point-field { display: grid; gap: 5px; font-size: 12px; }+.point-inputs { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }+.point-field small { color: #61758c; font-size: 10px; }+.fields details { border-top: 1px solid #e4e9ef; padding-top: 8px; }+.fields summary { cursor: pointer; font-size: 12px; }diff --git a/src/main.tsx b/src/main.tsxnew file mode 100644index 0000000..c54454f--- /dev/null+++ b/src/main.tsx@@ -0,0 +1,4 @@+import { createRoot } from 'react-dom/client';+import { App } from './editor/App';++createRoot(document.getElementById('root')!).render(<App />);diff --git a/src/sample-rig.d.ts b/src/sample-rig.d.tsnew file mode 100644index 0000000..e19285b--- /dev/null+++ b/src/sample-rig.d.ts@@ -0,0 +1,4 @@+declare module 'virtual:sample-rig' {+ const rig: import('./rig/types').Rig;+ export default rig;+}diff --git a/tests/editor.test.ts b/tests/editor.test.tsnew file mode 100644index 0000000..71e81a0--- /dev/null+++ b/tests/editor.test.ts@@ -0,0 +1,34 @@+import { expect, test } from 'vitest';+import fixture from '../samples/miko-qipao/rig.json';+import { parseRig, validateRig } from '../src/rig/validate';+import { buildOverlay, changeVertex, moveHandle, nearestHandle, getAt } from '../src/editor/model';++const view = { scale: 0.5, x: 20, y: 10 };+test('hit-testing finds the nearest handle within eight screen pixels', () => {+ const handles = buildOverlay(parseRig(fixture)).handles.filter(h => h.id === 'head.center');+ expect(nearestHandle(handles, [615 * 0.5 + 27, 400 * 0.5 + 10], view)?.id).toBe('head.center');+ expect(nearestHandle(handles, [615 * 0.5 + 29, 400 * 0.5 + 10], view)).toBeUndefined();+ const competing = [...handles, { ...handles[0], id: 'nearer', point: [625, 400] as [number, number] }];+ expect(nearestHandle(competing, [625 * 0.5 + 20, 210], view)?.id).toBe('nearer');+});+test('dragging a center updates exactly its coordinates and radius handles preserve the center', () => {+ const rig = parseRig(fixture);+ const handles = buildOverlay(rig).handles;+ const next = moveHandle(rig, handles.find(h => h.id === 'head.center')!, [635, 420]);+ expect(next.head.cx).toBe(635);+ expect(next.head.cy).toBe(420);+ expect(rig.head.cx).toBe(615);+ const wider = moveHandle(rig, handles.find(h => h.id === 'head.rx')!, [1100, 400]);+ expect(wider.head.rx).toBe(485);+ expect(wider.head.cx).toBe(615);+});+test('vertex insertion and deletion preserve polygon and polyline minimum sizes', () => {+ let rig = parseRig(fixture);+ rig = changeVertex(rig, 'eyes.0.opening', 1, [448, 480], true);+ expect(getAt(rig, 'eyes.0.opening.1')).toEqual([448, 480]);+ while (rig.eyes[0].opening.length > 3) rig = changeVertex(rig, 'eyes.0.opening', 0, null, true);+ expect(changeVertex(rig, 'eyes.0.opening', 0, null, true).eyes[0].opening).toHaveLength(3);+ while (rig.strands![0].nodes.length > 2) rig = changeVertex(rig, 'strands.0.nodes', 0, null, false);+ expect(changeVertex(rig, 'strands.0.nodes', 0, null, false).strands![0].nodes).toHaveLength(2);+ expect(validateRig(rig)).toEqual([]);+});diff --git a/tests/history.test.ts b/tests/history.test.tsnew file mode 100644index 0000000..89eed8c--- /dev/null+++ b/tests/history.test.ts@@ -0,0 +1,28 @@+import { expect, test } from 'vitest';+import fixture from '../samples/miko-qipao/rig.json';+import { parseRig } from '../src/rig/validate';+import { RigHistory } from '../src/editor/history';+import { setAt } from '../src/editor/model';++test('one drag is one command and undo/redo restores exact JSON', () => {+ const rig = parseRig(fixture);+ const history = new RigHistory(rig);+ history.begin();+ history.change(setAt(rig, 'head.cx', 630));+ history.change(setAt(rig, 'head.cx', 650));+ history.end();+ const final = JSON.stringify(history.present);+ expect(history.undo()).toEqual(rig);+ expect(history.canUndo).toBe(false);+ expect(JSON.stringify(history.redo())).toBe(final);+ history.undo();+ history.change(setAt(rig, 'head.cy', 420));+ expect(history.canRedo).toBe(false);+});+test('a click with no change adds no history entry', () => {+ const history = new RigHistory(parseRig(fixture));+ history.begin();+ history.change(history.present);+ history.end();+ expect(history.canUndo).toBe(false);+});diff --git a/tests/stale.test.ts b/tests/stale.test.tsnew file mode 100644index 0000000..72ba424--- /dev/null+++ b/tests/stale.test.ts@@ -0,0 +1,16 @@+import { expect, test } from 'vitest';+import fixture from '../samples/miko-qipao/rig.json';+import { parseRig } from '../src/rig/validate';+import { layerSignature } from '../src/editor/stale';++test('cut-out changes mark layers stale without altering precut eye curves', () => {+ const rig = parseRig(fixture);+ const original = layerSignature(rig);+ rig.head.cx += 20;+ rig.hand!.wrist[0] += 10;+ expect(layerSignature(rig)).toBe(original);+ rig.eyes[0].opening[0][0] += 5;+ expect(layerSignature(rig)).not.toBe(original);+ expect(rig.eyes[0].top).toEqual(fixture.eyes[0].top);+ expect(rig.eyes[0].bot).toEqual(fixture.eyes[0].bot);+});