Skip to content

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

Keep integer-only rig fields integral and explain rebuild failures

shinshin86d756edadf765
diff --git a/docs/rig-fields.md b/docs/rig-fields.md
index ace693a..7105f23 100644
--- a/docs/rig-fields.md
+++ b/docs/rig-fields.md
@@ -3,7 +3,8 @@
Version 1 uses the original `source.png` coordinate system: origin at the top left, x right,
y down. Coordinates, radii, lengths, grid spacing and bands are **source pixels**; angles are
**radians**, not the degrees used by the pose sliders. All numbers must be finite. Ellipse
-radii and mesh cell sizes must be positive. A band is `[start, end]` with `start < end`.
+radii and mesh cell sizes must be positive. Mesh cell sizes and fine-mesh rectangle
+coordinates must be integers. Accessory boxes must be integer rectangles inside the image. A band is `[start, end]` with `start < end`.
Ellipses are smooth influence regions, not hard cut-out boundaries.
Only `buns`, `strands`, `accessories`, `hand` and `view.gazeCenter` are optional. Omit absent
diff --git a/e2e/integer-geometry.spec.ts b/e2e/integer-geometry.spec.ts
new file mode 100644
index 0000000..d51041b
--- /dev/null
+++ b/e2e/integer-geometry.spec.ts
@@ -0,0 +1,85 @@
+import { test, expect, type Page } from '@playwright/test';
+import { cp, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';
+import { basename, join, resolve } from 'node:path';
+import fixture from '../samples/miko-qipao/rig.json' with { type: 'json' };
+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+let directory: string, name: string;
+test.beforeEach(async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ await mkdir(resolve('projects'), { recursive: true });
+ directory = await mkdtemp(join(resolve('projects'), 'integer-check-')); name = basename(directory);
+ await cp(resolve('samples/miko-qipao'), directory, { recursive: true });
+ await page.goto('/'); await dismissGuide(page);
+ await page.locator('.open-menu > summary').click(); await page.getByTestId(`project-${name}`).click();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+});
+test.afterEach(async () => { if (directory) await rm(directory, { recursive: true, force: true }); });
+async function point(page: Page, x: number, y: number) {
+ return page.getByTestId('editor').evaluate((canvas, point) => {
+ const box = canvas.getBoundingClientRect(), scale = Number(canvas.dataset.scale);
+ return { x: box.x + Number(canvas.dataset.offsetX) + point.x * scale, y: box.y + Number(canvas.dataset.offsetY) + point.y * scale };
+ }, { x, y });
+}
+async function drag(page: Page, from: [number, number], to: [number, number]) {
+ const start = await point(page, ...from), end = await point(page, ...to);
+ await page.mouse.move(start.x, start.y); await page.mouse.down(); await page.mouse.move(end.x, end.y, { steps: 3 }); await page.mouse.up();
+}
+
+test('accessory dragging and numeric input save integer boxes and the real rebuild succeeds', async ({ page }) => {
+ test.setTimeout(90000);
+ await page.getByTestId('part-accessories').click();
+ const box = fixture.accessories[1].box;
+ await drag(page, [box[2], box[3]], [1075.9, 482.7]);
+ await page.getByText('Cut-out box (4)', { exact: true }).click();
+ const x = page.getByRole('spinbutton', { name: 'accessories.1.box.2', exact: true });
+ const y = page.getByRole('spinbutton', { name: 'accessories.1.box.3', exact: true });
+ await expect(x).toHaveValue('1076'); await expect(y).toHaveValue('483'); await expect(x).toHaveAttribute('step', '1');
+ await x.fill('1075.9'); await expect(x).toHaveValue('1076');
+ await y.fill('482.7'); await expect(y).toHaveValue('483');
+ await page.getByRole('button', { name: 'Save and rebuild layers', exact: true }).click();
+ await expect(page.getByTestId('stale-banner')).toHaveCount(0, { timeout: 60000 });
+ const saved = JSON.parse(await readFile(join(directory, 'rig.json'), 'utf8'));
+ expect(saved.accessories[1].box).toEqual([box[0], box[1], 1076, 483]);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+});
+
+test('mesh cell sizes and fine rectangle coordinates are integers while other fields retain decimals', async ({ page }) => {
+ await page.locator('.advanced-section > summary').click(); await page.getByTestId('part-mesh').click();
+ for (const key of ['baseCell', 'handCell', 'tasselCell', 'eyeBallCell', 'eyeCell', 'spriteCell']) {
+ const field = page.getByRole('spinbutton', { name: `mesh.${key}`, exact: true });
+ await expect(field).toHaveAttribute('step', '1'); await field.fill('7.6'); await expect(field).toHaveValue('8');
+ }
+ await drag(page, [fixture.mesh.fine.x1, fixture.mesh.fine.y1], [880.3, 760.8]);
+ await expect(page.getByRole('spinbutton', { name: 'mesh.fine.x1', exact: true })).toHaveValue('880');
+ await expect(page.getByRole('spinbutton', { name: 'mesh.fine.y1', exact: true })).toHaveValue('761');
+ const cell = page.getByRole('spinbutton', { name: 'mesh.fine.cell', exact: true }); await cell.fill('6.6'); await expect(cell).toHaveValue('7');
+ await page.getByTestId('part-head').click();
+ const head = page.getByRole('spinbutton', { name: 'head.cx', exact: true }); await expect(head).toHaveAttribute('step', '0.1');
+ await head.fill('615.4'); await head.blur(); await expect(head).toHaveValue('615.4');
+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();
+ await expect.poll(async () => JSON.parse(await readFile(join(directory, 'rig.json'), 'utf8')).head.cx).toBe(615.4);
+});
+
+test('rebuild errors explain the part and correction in both languages while retaining the raw log', async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.getByTestId('part-head').click(); await page.getByRole('spinbutton', { name: 'head.cx', exact: true }).fill('635');
+ const log = 'build-layers: accessories[1].box has no area inside the image';
+ await page.route(`**/__studio/projects/${name}/rebuild`, route => route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({ code: 'toolFailed', log }) }));
+ await page.getByRole('button', { name: 'Save and rebuild layers', exact: true }).click();
+ const feedback = page.getByTestId('stale-banner').getByTestId('job-feedback');
+ await expect(feedback.getByRole('alert')).toContainText('Accessory 2 (tassel_r)');
+ await expect(feedback.getByRole('alert')).toContainText('no width or height inside the image');
+ await expect(feedback.getByRole('alert')).not.toContainText('build-layers:');
+ await page.getByRole('button', { name: '日本語', exact: true }).click();
+ await expect(feedback.getByRole('alert')).toContainText('飾り 2 (tassel_r) の切り抜き範囲に幅や高さがありません');
+ await feedback.getByText('ログを表示', { exact: true }).click(); await expect(feedback.locator('pre')).toHaveText(log);
+ await page.unroute(`**/__studio/projects/${name}/rebuild`);
+ const validation = 'Invalid rig: rig.accessories[1].box: rectangle must stay inside the image';
+ await page.route(`**/__studio/projects/${name}/rebuild`, route => route.fulfill({ status: 400, contentType: 'application/json', body: JSON.stringify({ error: validation }) }));
+ await page.getByRole('button', { name: '保存してレイヤーを作り直す', exact: true }).click();
+ await expect(feedback.getByRole('alert')).toContainText('飾り 2 (tassel_r) の切り抜き範囲が画像の外');
+ await expect(feedback.getByRole('alert')).not.toContainText('PNG');
+ await feedback.locator('details').evaluate(element => { (element as HTMLDetailsElement).open = false; });
+ await page.screenshot({ path: 'docs/screenshots/ui8-rebuild-error-ja-1440x900.png' });
+});
diff --git a/src/editor/App.tsx b/src/editor/App.tsx
index 9f175d7..b2446b6 100644
--- a/src/editor/App.tsx
+++ b/src/editor/App.tsx
@@ -371,7 +371,7 @@ function Workspace() {
{help && <Help onClose={() => setHelp(false)} onGuide={() => { setGuide(true); setHelp(false); }} />}
{(dragStale ?? changed.length > 0) && <div className="stale" data-testid="stale-banner"><p role="status">{localProject && !localProject.readOnly ? t.staleLocal : sampleEditing ? t.staleSample : listedProject ? t.staleListed : t.stale}</p><small>{t.changedParts}: {changed.map(key => parts[key as PartGroup]?.[0] ?? title(key)).join(' · ')}</small>
{localProject && !localProject.readOnly ? <button className="primary" disabled={job !== null || saving} onClick={() => { setRebuildError(null); void runJob('rebuild').catch(error => setRebuildError(error instanceof ProjectJobError ? error : new ProjectJobError('toolFailed'))); }}>{job === 'rebuild' ? t.rebuilding : t.rebuild}</button> : <><small>{sampleEditing ? t.sampleRebuildReason : t.folderRebuildReason}</small>{sampleEditing || listedProject ? <button className="primary" disabled={opening || saving || job !== null || (sampleEditing && !rootPath)} onClick={() => { void continueEditing(); }}>{opening ? t.operationBusy : sampleEditing ? t.copyContinue : t.reopenListed}</button> : <p>{t.rebuildUnavailable}</p>}</>}
- {rebuildError && <JobFeedback error={rebuildError} />}
+ {rebuildError && <JobFeedback error={rebuildError} rig={rig} />}
{error?.kind === 'continueError' && errorNotice}
</div>}
{!sourceUrl && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} />{errorNotice}</section>}
diff --git a/src/editor/JobFeedback.tsx b/src/editor/JobFeedback.tsx
index 9d9ef77..6137950 100644
--- a/src/editor/JobFeedback.tsx
+++ b/src/editor/JobFeedback.tsx
@@ -1,10 +1,12 @@
+import type { Rig } from '../rig/types';
+import { jobReason } from './job-reason';
import { useI18n } from './i18n';
import { ProjectJobError } from './project';
-export function JobFeedback({ error, log = '', accepted = false, importing = false }: { error?: ProjectJobError | null; log?: string; accepted?: boolean; importing?: boolean }) {
- const { t } = useI18n();
+export function JobFeedback({ error, log = '', accepted = false, importing = false, rig }: { error?: ProjectJobError | null; log?: string; accepted?: boolean; importing?: boolean; rig?: Rig }) {
+ const { t, title } = useI18n();
const details = error?.log || log;
- const reason = error?.code === 'dependencies' ? t.dependenciesHelp : error?.code === 'unsafeFiles' ? t.unsafeFilesHelp : error?.code === 'invalidImages' ? t.importInvalid : /outside-mask changes/.test(details) ? t.importOutside : /expected PNG size/.test(details) ? t.importSize : /mask/.test(details) ? t.importMask : t.jobFailed;
+ const reason = error?.code === 'dependencies' ? t.dependenciesHelp : error?.code === 'unsafeFiles' ? t.unsafeFilesHelp : error?.code === 'invalidImages' ? t.importInvalid : jobReason(details, t, rig, title) ?? (/outside-mask changes/.test(details) ? t.importOutside : /expected PNG size/.test(details) ? t.importSize : /mask/.test(details) ? t.importMask : t.jobFailed);
const metrics = [...details.matchAll(/(eyes_\w+|mouth_\w+): outside-mask max ([\d.]+)\/255, mean ([\d.]+)\/255, (\d+) pixels over tolerance ([\d.]+)/g)];
return <div className="job-feedback" data-testid="job-feedback">
{error && <p role="alert">{error.code === 'reloadFailed' ? t.reloadFailed : <>{importing ? t.importRejected : t.jobFailed}{reason !== t.jobFailed && ` ${reason}`}</>}</p>}
diff --git a/src/editor/NumericField.tsx b/src/editor/NumericField.tsx
index e60b5d0..44735c3 100644
--- a/src/editor/NumericField.tsx
+++ b/src/editor/NumericField.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
+import { editorNumber, isIntegerField } from '../rig/numeric';
export function NumericField({ path, value, label, onChange }: {
path: string; label?: string; value: number; onChange: (value: number) => void;
@@ -7,11 +8,12 @@ export function NumericField({ path, value, label, onChange }: {
useEffect(() => setDraft(String(value)), [value]);
return (
<label title={path}><span>{label}</span>
- <input type="number" step="0.1" aria-label={path} value={draft}
+ <input type="number" step={isIntegerField(path) ? 1 : 0.1} aria-label={path} value={draft}
onChange={event => {
- setDraft(event.target.value);
const number = event.target.valueAsNumber;
- if (Number.isFinite(number)) onChange(number);
+ const rounded = editorNumber(path, number);
+ setDraft(Number.isFinite(number) && isIntegerField(path) ? String(rounded) : event.target.value);
+ if (Number.isFinite(number)) onChange(rounded);
}}
onBlur={() => setDraft(String(value))} /><small className="field-path">{path}</small>
</label>
diff --git a/src/editor/job-reason.ts b/src/editor/job-reason.ts
new file mode 100644
index 0000000..f5bdb89
--- /dev/null
+++ b/src/editor/job-reason.ts
@@ -0,0 +1,22 @@
+import type { Rig } from '../rig/types';
+
+type Messages = Record<'accessory' | 'jobBoxOutside' | 'jobBoxEmpty' | 'jobBoxInvalid' | 'jobAccessoryPixels' | 'jobEyeRegion' | 'jobHandRegion' | 'jobFaceRegion' | 'jobImageSize' | 'jobMeshRegion', string>;
+export function jobReason(log: string, t: Messages, rig?: Rig, fieldTitle: (field: string) => string = field => field): string | undefined {
+ const error = log.split('\n').filter(line => !/rounded outward/.test(line)).join('\n');
+ const accessory = error.match(/accessories\[(\d+)\]\.box[^\n]*/);
+ if (accessory) {
+ const index = Number(accessory[1]), name = rig?.accessories?.[index]?.name;
+ const part = `${t.accessory} ${index + 1}${name ? ` (${name})` : ''}`;
+ const message = /integer|finite coordinates/.test(accessory[0]) ? t.jobBoxInvalid : /no area|positive width|positive area/.test(accessory[0]) ? t.jobBoxEmpty : /inside|within|outside/.test(accessory[0]) ? t.jobBoxOutside : t.jobBoxInvalid;
+ return message.replace('PART', part);
+ }
+ const pixels = error.match(/accessory ([A-Za-z0-9_-]+): no pixels/);
+ if (pixels) return t.jobAccessoryPixels.replace('PART', pixels[1]);
+ const eye = error.match(/eyes\[(\d+)\]\.(opening|roi)/);
+ if (eye) return t.jobEyeRegion.replace('INDEX', String(Number(eye[1]) + 1));
+ if (/hand\.(outline|background|jaw|jawRange)/.test(error)) return t.jobHandRegion;
+ const face = error.match(/face\.(brow|mouth|nose)/);
+ if (face) return t.jobFaceRegion.replace('FIELD', fieldTitle(face[1]));
+ if (/rig\.image must match/.test(error)) return t.jobImageSize;
+ if (/mesh\.(fine|\w*Cell)/.test(error)) return t.jobMeshRegion;
+}
diff --git a/src/editor/model.ts b/src/editor/model.ts
index fbc613e..3c17c77 100644
--- a/src/editor/model.ts
+++ b/src/editor/model.ts
@@ -1,3 +1,4 @@
+import { editorNumber, isIntegerField } from '../rig/numeric';
import type { Point, Rig } from '../rig/types';
export interface Viewport { scale: number; x: number; y: number }
@@ -31,7 +32,7 @@ export function setAt(rig: Rig, path: string, value: unknown): 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;
+ target[parts.at(-1)!] = typeof value === 'number' ? editorNumber(path, value) : value;
return next;
}
export function numericFields(value: unknown, path: string): { path: string; value: number }[] {
@@ -56,15 +57,15 @@ export function nearestHandle(handles: Handle[], point: Point, view: Viewport, t
return nearest;
}
export function moveHandle(rig: Rig, handle: Handle, point: Point): Rig {
- const rounded = (value: number) => Math.round(value * 10) / 10;
+ const rounded = (value: number, path: string) => isIntegerField(path) ? Math.round(value) : 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(rig, handle.xPath, Math.max(1, rounded(Math.abs(amount), handle.xPath)));
}
- return setAt(setAt(rig, handle.xPath, rounded(point[0])), handle.yPath!, rounded(point[1]));
+ return setAt(setAt(rig, handle.xPath, rounded(point[0], handle.xPath)), handle.yPath!, rounded(point[1], handle.yPath!));
}
export function changeVertex(rig: Rig, path: string, index: number, point: Point | null, closed: boolean): Rig {
const points = structuredClone(getAt(rig, path)) as Point[];
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 2b7afb9..73bf2ea 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -84,7 +84,7 @@ export async function runProjectJob(project: LocalProject, action: ProjectJob, r
}
const response = await fetch(`${baseUrl(project)}${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const result = await response.json();
- if (!response.ok) throw new ProjectJobError(result.code ?? (response.status === 400 ? 'invalidImages' : 'toolFailed'), result.log ?? result.error);
+ if (!response.ok) throw new ProjectJobError(result.code ?? (response.status === 400 && action === 'import-variants' ? 'invalidImages' : 'toolFailed'), result.log ?? result.error);
return result;
}
export async function projectVariantRequests(project: LocalProject): Promise<VariantRequest[]> {
diff --git a/src/editor/workflow-i18n.ts b/src/editor/workflow-i18n.ts
index a81ea2a..795e8a4 100644
--- a/src/editor/workflow-i18n.ts
+++ b/src/editor/workflow-i18n.ts
@@ -18,6 +18,15 @@ export const workflowEn = {
sampleRebuildReason: 'Rebuild is unavailable because the sample is read-only.', folderRebuildReason: 'Rebuild is unavailable because the browser cannot identify this folder’s location.',
continueError: 'Could not open an editable project. Your edits are still here; try again.',
rebuildUnavailable: 'Save rig.json, run build-layers in the project folder, then reopen it.',
+ jobBoxOutside: 'PART’s cut-out box is outside the image. Move its corners inside the image.',
+ jobBoxEmpty: 'PART’s cut-out box has no width or height inside the image. Separate its corners within the image.',
+ jobBoxInvalid: 'Check PART’s cut-out box. Use four integer coordinates for a rectangle inside the image.',
+ jobAccessoryPixels: 'No pixels were found for PART. Check its cut-out box and colour thresholds.',
+ jobEyeRegion: 'Check eye INDEX’s opening and surrounding cut-out region. Keep them inside the image and overlap the opening.',
+ jobHandRegion: 'Check the hand outline and jaw range. Keep them inside the image with enough width.',
+ jobFaceRegion: 'Check the face’s FIELD cut-out region. Its horizontal and vertical radii must be positive.',
+ jobImageSize: 'The source image size differs from the project settings. Use the matching source.png and rig.json.',
+ jobMeshRegion: 'Check the mesh cell sizes and fine rectangle. Use positive integer cell sizes and a rectangle with width and height.',
jobFailed: 'The local tool could not finish. Previous layers were kept.', dependenciesHelp: 'Install uv and Python 3.10 or later, then try again. With Homebrew: brew install uv python. Setup: docs/agent-guide.md.',
unsafeFilesHelp: 'The project contains redirected files. Use regular files inside this project and try again.', showLog: 'Show log', operationBusy: 'Working locally…', reloadFailed: 'Could not reload the project. The current view is still open.',
variantsTitle: 'Drawn variants', variantMissing: 'Missing', variantsHelp: 'Drawn expressions make closed eyes and speaking look more natural.',
@@ -52,6 +61,15 @@ export const workflowJa: typeof workflowEn = {
sampleRebuildReason: '読み取り専用のため、このままでは作り直せません。', folderRebuildReason: 'ブラウザで選んだフォルダの場所を取得できないため、このままでは作り直せません。',
continueError: '編集できるプロジェクトを開けませんでした。今の編集内容は残っています。もう一度お試しください。',
rebuildUnavailable: '設定を保存し、そのフォルダで build-layers を実行してから開き直してください。',
+ jobBoxOutside: 'PART の切り抜き範囲が画像の外にはみ出しています。枠の角を画像内に移してください。',
+ jobBoxEmpty: 'PART の切り抜き範囲に幅や高さがありません。枠の角を画像内で離して配置してください。',
+ jobBoxInvalid: 'PART の切り抜き範囲を確認してください。画像内の矩形になる4つの整数座標を指定してください。',
+ jobAccessoryPixels: 'PART の切り抜く画素が見つかりません。切り抜き範囲と色の条件を確認してください。',
+ jobEyeRegion: '目 INDEX の開いた範囲と周囲の切り抜き範囲を確認してください。画像内に収め、開いた範囲を切り抜き範囲に含めてください。',
+ jobHandRegion: '手の輪郭と顎の範囲を確認してください。画像内に収め、横幅を持たせてください。',
+ jobFaceRegion: '顔の FIELD の切り抜き範囲を確認してください。横半径と縦半径は0より大きくしてください。',
+ jobImageSize: '元画像の大きさが設定と一致しません。対応する source.png と rig.json を使ってください。',
+ jobMeshRegion: '格子幅と細かい格子の範囲を確認してください。格子幅は正の整数にし、範囲に幅と高さを持たせてください。',
jobFailed: '作業を完了できませんでした。以前のレイヤーは残しています。', dependenciesHelp: 'uv と Python 3.10 以降を用意してから、もう一度お試しください。Homebrew の場合: brew install uv python。準備手順: docs/agent-guide.md。',
unsafeFilesHelp: 'プロジェクトに別の場所へ転送するファイルがあります。このプロジェクト内の通常のファイルにしてからお試しください。', showLog: 'ログを表示', operationBusy: 'この端末で処理中…', reloadFailed: 'プロジェクトを読み込み直せませんでした。現在の画面は残っています。',
variantsTitle: '描き分け画像', variantMissing: 'なし', variantsHelp: '目を閉じたときや話すときの絵を描き分けると、動きが自然になります。',
diff --git a/src/rig/numeric.ts b/src/rig/numeric.ts
new file mode 100644
index 0000000..a28b5f3
--- /dev/null
+++ b/src/rig/numeric.ts
@@ -0,0 +1,7 @@
+// These values count pixels or cells; subpixel precision is useful for other geometry.
+export function isIntegerField(path: string): boolean {
+ return /^(?:image\.(?:width|height)|accessories\.\d+\.box\.\d+|mesh\.(?:baseCell|handCell|tasselCell|eyeBallCell|eyeCell|spriteCell|fine\.(?:x0|x1|y0|y1|cell)))$/.test(path);
+}
+export function editorNumber(path: string, value: number): number {
+ return isIntegerField(path) ? Math.round(value) : value;
+}
diff --git a/src/rig/validate.ts b/src/rig/validate.ts
index d51c069..f2f59c8 100644
--- a/src/rig/validate.ts
+++ b/src/rig/validate.ts
@@ -12,6 +12,10 @@ const integer: Check = (v, p, e) => {
positive(v, p, e);
if (typeof v === 'number' && !Number.isInteger(v)) e.push(`${p}: expected an integer`);
};
+const wholeNumber: Check = (v, p, e) => {
+ number(v, p, e);
+ if (typeof v === 'number' && !Number.isInteger(v)) e.push(`${p}: expected an integer`);
+};
const string: Check = (v, p, e) => {
if (typeof v !== 'string' || !v.trim()) e.push(`${p}: expected a non-empty string`);
};
@@ -59,14 +63,14 @@ const schema = (draft: boolean) => object({
cheeks: array(point, 2, 2),
strands: array(object({ name: string, nodes: line, sigma: positive, k: positive, max: positive })),
accessories: array(object({ name: string, pivot: point, tip: point, split: unit,
- box: array(number, 4, 4), color: object({ redness: unit, minRed: number }) })),
+ box: array(wholeNumber, 4, 4), color: object({ redness: unit, minRed: number }) })),
hand: object({ outline: polygon, jaw: line, jawRange: band, background: polygon,
elbow: point, wrist: point, knuckle: point, contact: point, forearmShare: unit,
armBand: band, wristBand: band, handBand: band, fingerXBand: band,
fingerYBand: band, pinBand: band }),
- mesh: object({ baseCell: positive, fine: object({ x0: number, x1: number,
- y0: number, y1: number, cell: positive }), handCell: positive,
- tasselCell: positive, eyeBallCell: positive, eyeCell: positive, spriteCell: positive }),
+ mesh: object({ baseCell: integer, fine: object({ x0: wholeNumber, x1: wholeNumber,
+ y0: wholeNumber, y1: wholeNumber, cell: integer }), handCell: integer,
+ tasselCell: integer, eyeBallCell: integer, eyeCell: integer, spriteCell: integer }),
view: object({ padTop: number, padSide: number, gazeCenter: point }, ['gazeCenter']),
}, ['buns', 'strands', 'accessories', 'hand']);
@@ -94,6 +98,8 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):
errors.push(`rig.strands[${i}].nodes: consecutive nodes must differ`);
}
for (const [i, accessory] of (rig.accessories ?? []).entries()) {
+ if (accessory.box[0] < 0 || accessory.box[1] < 0 || accessory.box[2] > rig.image.width || accessory.box[3] > rig.image.height)
+ errors.push(`rig.accessories[${i}].box: rectangle must stay inside the image`);
if (accessory.split <= 0 || accessory.split >= 1) errors.push(`rig.accessories[${i}].split: must be strictly between 0 and 1`);
if (accessory.pivot.every((n, k) => n === accessory.tip[k])) errors.push(`rig.accessories[${i}].tip: must differ from pivot`);
if (accessory.box[0] >= accessory.box[2] || accessory.box[1] >= accessory.box[3]) errors.push(`rig.accessories[${i}].box: rectangle must have positive area`);
diff --git a/tests/editor.test.ts b/tests/editor.test.ts
index 71e81a0..795ff2a 100644
--- a/tests/editor.test.ts
+++ b/tests/editor.test.ts
@@ -1,7 +1,7 @@
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';
+import { buildOverlay, changeVertex, moveHandle, nearestHandle, getAt, setAt } from '../src/editor/model';
const view = { scale: 0.5, x: 20, y: 10 };
test('hit-testing finds the nearest handle within eight screen pixels', () => {
@@ -32,3 +32,17 @@ test('vertex insertion and deletion preserve polygon and polyline minimum sizes'
expect(changeVertex(rig, 'strands.0.nodes', 0, null, false).strands![0].nodes).toHaveLength(2);
expect(validateRig(rig)).toEqual([]);
});
+
+
+test('integer rectangles and cells round in both handle moves and numeric edits without rounding other geometry', () => {
+ const rig = parseRig(fixture), handles = buildOverlay(rig).handles;
+ const box = moveHandle(rig, handles.find(h => h.id === 'accessories.1.box.end')!, [1075.9, 482.7]);
+ expect(box.accessories![1].box.slice(2)).toEqual([1076, 483]);
+ expect(moveHandle(rig, handles.find(h => h.id === 'accessories.1.box.end')!, [1075.49, 482.49]).accessories![1].box.slice(2)).toEqual([1075, 482]);
+ const fine = moveHandle(rig, handles.find(h => h.id === 'mesh.fine.end')!, [880.3, 760.8]);
+ expect(fine.mesh.fine).toMatchObject({ x1: 880, y1: 761 });
+ for (const path of ['mesh.baseCell', 'mesh.handCell', 'mesh.fine.cell', 'accessories.0.box.0']) expect(getAt(setAt(rig, path, 14.7), path)).toBe(15);
+ expect(setAt(rig, 'head.cx', 615.4).head.cx).toBe(615.4);
+ expect(moveHandle(rig, handles.find(h => h.id === 'head.center')!, [615.35, 400.24]).head).toMatchObject({ cx: 615.4, cy: 400.2 });
+ expect(validateRig(box)).toEqual([]); expect(validateRig(fine)).toEqual([]);
+});
diff --git a/tests/job-reason.test.ts b/tests/job-reason.test.ts
new file mode 100644
index 0000000..7c23be9
--- /dev/null
+++ b/tests/job-reason.test.ts
@@ -0,0 +1,28 @@
+import { expect, test, vi } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { jobReason } from '../src/editor/job-reason';
+import { workflowEn, workflowJa } from '../src/editor/workflow-i18n';
+import { runProjectJob, type LocalProject } from '../src/editor/project';
+import { parseRig } from '../src/rig/validate';
+
+test('tool geometry failures name the part and correction in each language, ignoring successful rounding logs', () => {
+ const rig = parseRig(fixture), en = { ...workflowEn, accessory: 'Accessory' }, ja = { ...workflowJa, accessory: '飾り' };
+ const outside = 'Invalid rig: rig.accessories[1].box: rectangle must stay inside the image';
+ expect(jobReason(outside, en, rig)).toContain('Accessory 2 (tassel_r)');
+ expect(jobReason(outside, ja, rig)).toContain('飾り 2 (tassel_r) の切り抜き範囲が画像の外');
+ expect(jobReason('build-layers: accessories[1].box must be an integer rectangle inside the image', ja, rig)).toContain('4つの整数座標');
+ expect(jobReason('build-layers: accessories[1].box has no area inside the image', ja, rig)).toContain('幅や高さがありません');
+ expect(jobReason('accessories[1].box rounded outward and clipped: [1,2,3.4,5] -> [1,2,4,5]', ja, rig)).toBeUndefined();
+ expect(jobReason('build-layers: accessory tassel_r: no pixels match its box and color thresholds', ja)).toContain('色の条件');
+ expect(jobReason('build-layers: eyes[0].opening: points must be within source.png', ja)).toContain('目 1');
+ expect(jobReason('build-layers: rig.image must match source.png dimensions', ja)).toContain('元画像の大きさ');
+});
+
+
+test('rebuild validation errors remain geometry failures rather than image-import failures', async () => {
+ vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ error: 'Invalid rig: rig.accessories[1].box: rectangle must stay inside the image' }), { status: 400, headers: { 'Content-Type': 'application/json' } }));
+ try {
+ const project = { name: 'nova' } as LocalProject;
+ await expect(runProjectJob(project, 'rebuild', parseRig(fixture))).rejects.toMatchObject({ code: 'toolFailed', log: expect.stringContaining('accessories[1].box') });
+ } finally { vi.unstubAllGlobals(); }
+});
diff --git a/tests/rig.test.ts b/tests/rig.test.ts
index e01170e..30359e1 100644
--- a/tests/rig.test.ts
+++ b/tests/rig.test.ts
@@ -40,3 +40,16 @@ test('draft validation permits omitted generated curves without weakening comple
partial.eyes[0].opening = [[1, 2], [3, 4]];
expect(validateRig(partial, { draft: true }).join()).toContain('rig.eyes[0].opening');
});
+
+
+test('rejects fractional and out-of-image accessory boxes and fractional mesh values', () => {
+ for (const box of [[856, 279, 1075.9, 482.7], [-1, 279, 1000, 480], [856, 279, 1255, 480], [856, 279, 1000, 1255], [900, 279, 900, 480]]) {
+ const rig = parseRig(fixture); rig.accessories![1].box = box as [number, number, number, number];
+ expect(validateRig(rig).join()).toContain('rig.accessories[1].box');
+ }
+ for (const key of ['baseCell', 'handCell', 'tasselCell', 'eyeBallCell', 'eyeCell', 'spriteCell'] as const) {
+ const rig = parseRig(fixture); rig.mesh[key] = 3.5; expect(validateRig(rig).join()).toContain(`rig.mesh.${key}`);
+ }
+ const rig = parseRig(fixture); rig.mesh.fine.x0 = 340.2; rig.mesh.fine.cell = 7.2;
+ expect(validateRig(rig).join()).toContain('rig.mesh.fine.x0'); expect(validateRig(rig).join()).toContain('rig.mesh.fine.cell');
+});
diff --git a/tools/build-layers.py b/tools/build-layers.py
index b22accc..b8d86ed 100755
--- a/tools/build-layers.py
+++ b/tools/build-layers.py
@@ -8,6 +8,7 @@ Run with: uv run --with numpy --with pillow --with opencv-python-headless
import argparse
import hashlib
import json
+import math
import re
import sys
import tempfile
@@ -478,15 +479,23 @@ def validate_inputs(rig, rgba):
)
names.add(name)
box = accessory["box"]
- if (
- len(box) != 4
- or not 0 <= box[0] < box[2] <= w
- or not 0 <= box[1] < box[3] <= h
- or any(int(n) != n for n in box)
+ if len(box) != 4 or any(
+ not isinstance(n, (int, float)) or not math.isfinite(n) for n in box
):
- raise ValueError(
- f"accessories[{i}].box must be an integer rectangle inside the image"
- )
+ raise ValueError(f"accessories[{i}].box must contain four finite coordinates")
+ if box[0] >= box[2] or box[1] >= box[3]:
+ raise ValueError(f"accessories[{i}].box must have positive width and height")
+ rounded = [
+ max(0, min(w, math.floor(box[0]))),
+ max(0, min(h, math.floor(box[1]))),
+ max(0, min(w, math.ceil(box[2]))),
+ max(0, min(h, math.ceil(box[3]))),
+ ]
+ if rounded[0] >= rounded[2] or rounded[1] >= rounded[3]:
+ raise ValueError(f"accessories[{i}].box has no area inside the image")
+ if rounded != box:
+ print(f"accessories[{i}].box rounded outward and clipped: {box} -> {rounded}")
+ accessory["box"] = rounded
colour = accessory["color"]
if not 0 <= colour["redness"] <= 1 or not 0 <= colour["minRed"] <= 255:
raise ValueError(f"accessories[{i}].color thresholds are out of range")
diff --git a/tools/test_build_layers.py b/tools/test_build_layers.py
index 2a7bad4..ee8f52e 100644
--- a/tools/test_build_layers.py
+++ b/tools/test_build_layers.py
@@ -108,6 +108,44 @@ class BuildLayersTest(unittest.TestCase):
(self.project / "built/layers.json").read_text(), "existing layers"
)
+ def test_accessory_boxes_round_outward_clip_and_keep_valid_integers(self):
+ for box, expected in [
+ ([10.2, 20.8, 30.1, 40.2], [10, 20, 31, 41]),
+ ([-5.2, -3.1, 101.7, 81.2], [0, 0, 100, 80]),
+ ([10, 20, 30, 40], [10, 20, 30, 40]),
+ ]:
+ with self.subTest(box=box):
+ self.rig["accessories"] = [{"name": "tassel", "box": box, "color": {"redness": 0.5, "minRed": 60}}]
+ # Add source pixels that satisfy the accessory's colour thresholds.
+ with Image.open(self.project / "source.png") as original:
+ image = original.convert("RGBA")
+ ImageDraw.Draw(image).rectangle((22, 21, 25, 25), fill=(220, 30, 30, 255))
+ image.save(self.project / "source.png")
+ self.draft.write_text(json.dumps(self.rig))
+ result = self.run_cli()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ saved = json.loads((self.project / "rig.json").read_text())
+ self.assertEqual(saved["accessories"][0]["box"], expected)
+ self.assertTrue(all(isinstance(n, int) for n in saved["accessories"][0]["box"]))
+ if expected != box:
+ self.assertIn("rounded outward and clipped", result.stdout)
+ else:
+ self.assertNotIn("rounded outward and clipped", result.stdout)
+
+ def test_collapsed_or_nonfinite_boxes_fail_without_replacing_output(self):
+ (self.project / "rig.json").write_text("existing rig")
+ (self.project / "built").mkdir()
+ (self.project / "built/layers.json").write_text("existing layers")
+ for box in [[101, 20, 110, 40], [20, 80, 30, 90], [20, 20, 20, 40], [30.5, 20, 30.4, 40], [float("nan"), 20, 30, 40]]:
+ with self.subTest(box=box):
+ self.rig["accessories"] = [{"name": "tassel", "box": box, "color": {"redness": 0.5, "minRed": 60}}]
+ self.draft.write_text(json.dumps(self.rig))
+ result = self.run_cli()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("accessories[0].box", result.stderr)
+ self.assertEqual((self.project / "rig.json").read_text(), "existing rig")
+ self.assertEqual((self.project / "built/layers.json").read_text(), "existing layers")
+
def test_sampled_eye_curves_match_existing_fixture(self):
rig = json.loads((ROOT / "samples/miko-qipao/rig.json").read_text())
for eye in rig["eyes"]: