Skip to content

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

Document the avatar format and validate whole project folders

shinshin86cf02d8568f7e
diff --git a/README.ja.md b/README.ja.md
index b2d2887..e6484e2 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -97,6 +97,7 @@ npm run dev
- [エージェント向けの手順書](docs/agent-guide.md): エージェントが作業するときの手順
- [リファレンス](docs/reference.md): プロジェクトの扱い、レイヤーを手作業で作る方法、エディタの全操作、テスト
- [リグの項目](docs/rig-fields.md): `rig.json` の各値の意味
+- [アバターの形式](docs/format.md): フォルダと `.mavatar` の構成、メタデータ、検証方法
いずれも英語です。
diff --git a/README.md b/README.md
index dc36053..27dabee 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,7 @@ Stream view options, troubleshooting and privacy details are in the
- [Agent guide](docs/agent-guide.md): the step-by-step procedure agents follow
- [Reference](docs/reference.md): projects, building layers by hand, all editor controls, tests
- [Rig fields](docs/rig-fields.md): what every value in `rig.json` means
+- [Avatar format](docs/format.md): folder and `.mavatar` layouts, metadata and validation
## License
diff --git a/docs/format.md b/docs/format.md
new file mode 100644
index 0000000..0c22efa
--- /dev/null
+++ b/docs/format.md
@@ -0,0 +1,174 @@
+# Avatar file and folder format
+
+Version 1 uses the same files in a project folder and a `.mavatar` archive. A project
+folder is the working copy; a `.mavatar` is a ZIP containing those files at its root.
+The rig describes motion in source-image coordinates, and the built PNGs provide the
+textures. See [Rig fields](rig-fields.md) for the geometry and deformation settings.
+
+## Files
+
+```text
+avatar.json manifest; required in an archive, optional in a folder
+rig.json complete version 1 rig, including sampled eye curves
+built/
+ layers.json image size, layer rectangles and sampled eye curves
+ base.png image with movable parts removed and inpainted
+ hairmask.png full-size hair mask, read from the red channel
+ <name>.png one image for every entry in layers.json.layers
+ sprites/ optional drawn eye and mouth variants
+ sprites.json sprite rectangles
+ <name>.png one image for every entry in sprites.json.layers
+source.png optional original illustration; needed for editing
+thumbnail.png optional preview image
+```
+
+`base.png` and `hairmask.png` are required even when they have no rectangle entry in
+`layers.json`. Hand and accessory layers are required only when the rig contains those
+parts. The entire `sprites/` directory can be absent. The renderer then animates the
+generated eye layers and procedural mouth without drawn variants.
+
+Readers ignore unknown files and unknown JSON keys. A project may also contain drafts,
+source variants, masks and review images; these are not required for playback.
+
+## Manifest: `avatar.json`
+
+```json
+{
+ "format": "mesh-avatar",
+ "version": 1,
+ "name": "My avatar",
+ "author": "Artist name",
+ "source": "source.png",
+ "thumbnail": "thumbnail.png",
+ "studio": { "version": "0.1.0" }
+}
+```
+
+| Field | Meaning |
+| --- | --- |
+| `format` | Required literal `"mesh-avatar"`. |
+| `version` | Required format version, currently `1`. |
+| `name` | Required non-empty display name. It is not a filesystem path. |
+| `author` | Optional author or attribution string. |
+| `license` | Optional license text or reference to the artwork's terms. The runtime's MIT license does not grant rights to the artwork. |
+| `source` | Optional original-image filename relative to the root, normally `source.png`. |
+| `thumbnail` | Optional preview-image filename relative to the root, normally `thumbnail.png`. |
+| `studio.version` | Optional version string identifying the Studio that prepared the avatar. |
+
+An existing folder without `avatar.json` has the effective manifest
+`{ "format": "mesh-avatar", "version": 1, "name": "<folder name>" }`.
+Archives must contain an explicit manifest. `parseManifest` validates known fields,
+returns a new object containing those fields, and throws an error naming `avatar.json`
+when they are invalid. It ignores unknown keys, including those inside `studio`.
+
+## Built layers: `built/layers.json`
+
+| Field | Meaning |
+| --- | --- |
+| `version` | Metadata version `1`; omission also means `1`. |
+| `size` | `[width, height]` in source pixels, exactly matching `rig.image`. Both dimensions are positive integers. |
+| `build` | Non-empty cache-busting hash of build inputs. It is not a format version. |
+| `layers` | Object mapping each layer name to `[x, y, width, height]`. |
+| `eyes` | Two objects containing `x0`, `x1`, `top` and `bot`, in the same eye order as the rig. |
+
+Rectangle origins are non-negative integers; width and height are positive integers.
+Rectangles lie inside the source image. Each corresponding PNG is cropped to its
+rectangle's width and height. Names use letters, digits, hyphens or underscores, with
+no extension or path separator.
+
+| Reserved name | Contents |
+| --- | --- |
+| `base` | Full-size illustration after removing the eyes, optional hand and accessories and inpainting the exposed areas. |
+| `hairmask` | Full-size mask whose red channel controls hair deformation. |
+| `hand` | The movable hand and arm cutout; present when `rig.hand` exists. |
+| `eye0_ball`, `eye1_ball` | Eye white and iris, clipped by the eyelid curves at runtime. |
+| `eye0_low`, `eye1_low` | Lower eyelid strokes. |
+| `eye0_crease`, `eye1_crease` | Eyelid crease strokes. A transparent image is valid when no crease is drawn. |
+| `eye0_lash`, `eye1_lash` | Upper lash strokes. |
+
+All four parts are required for each eye. Accessory names come from
+`rig.accessories[*].name`; each needs a rectangle and a corresponding PNG.
+Accessory names must be unique and must not reuse reserved layer names.
+
+Each eye spans finite `x0 < x1` values. `top` and `bot` each contain 24 finite y
+coordinates sampled across that span; every top value is at or above its bottom value.
+These fields duplicate `rig.eyes[*].x0`, `x1`, `top` and `bot`. The layer builder writes
+both copies, and their values must agree exactly. A future format may keep them only
+in `layers.json`; version 1 requires both.
+
+## Drawn variants: `built/sprites/sprites.json`
+
+The optional sprite metadata contains `version`, `build` and `layers`.
+`version` is `1` (or omitted for older files), and `build` is a cache-busting hash.
+`layers` is a rectangle map, just like the layer metadata:
+
+```json
+{
+ "build": "example-build-hash",
+ "layers": {
+ "mouth_a": [100, 200, 80, 40]
+ },
+ "version": 1
+}
+```
+
+Each listed sprite has a PNG under `built/sprites/`. It uses the same source-pixel
+rectangle convention, including bounds and integer requirements. Sprites are optional
+individually; readers must not require a complete set.
+
+| Name | Drawing |
+| --- | --- |
+| `eyes_closed_0`, `eyes_closed_1` | Closed eyes with relaxed lids. |
+| `eyes_half_0`, `eyes_half_1` | Half-open eyes. |
+| `eyes_smile_0`, `eyes_smile_1` | Closed eyes in a smile. |
+| `mouth_a` | Open mouth for “a”. |
+| `mouth_a_half` | Partly open “a”; also reused for “e”. |
+| `mouth_i` | Wide mouth for “i”. |
+| `mouth_o` | Rounded mouth for “o”; also reused, with reduced width, for “u”. |
+
+The eye suffix is the index in `rig.eyes`, not a separate left/right convention.
+The original base drawing provides the closed mouth.
+
+## Archive rules and compatibility
+
+A `.mavatar` file is a ZIP with stored entries (compression method 0), UTF-8 names and
+forward slashes. Put `avatar.json`, `rig.json` and `built/` directly at its root, without
+a wrapping project directory. Entry names must not be absolute paths, contain `..`
+segments or use backslashes. Importers reject archives with more than 200 entries or
+any entry larger than 64 MB.
+
+Missing `avatar.json` is allowed only for folders. Missing `version` is allowed only
+in `layers.json` and `sprites.json`, where it means `1`. `rig.json` and any present
+`avatar.json` must specify version `1`. Readers reject unsupported versions with an
+error identifying the file and version, such as
+`built/layers.json.version: unsupported version 2 (expected 1)`.
+Unknown entries and unknown object keys do not change the interpretation of known
+fields. A listed layer or sprite still requires its PNG, even if its name is unfamiliar.
+
+Include `source.png` by default when preparing an archive for re-editing. It can be
+omitted for playback, but `built/base.png` already contains most of the illustration:
+omitting the source offers little protection for the artwork. Check the artwork's
+terms before sharing any of these files.
+
+## Validate a folder
+
+From the repository root, after installing Node dependencies:
+
+```sh
+npm run validate-avatar -- samples/miko-qipao
+npm run validate-avatar -- projects/my-avatar
+```
+
+The command currently accepts folders. It reads regular files without following
+symlinks, returns exit status 0 for valid folders and 1 for invalid input, and prints
+errors with the affected relative filename. Archive reading and writing are separate
+from folder validation.
+
+`validateAvatarFiles(files)` performs the same checks without filesystem or network
+access. Pass a map from root-relative, forward-slash paths to `Uint8Array` bytes.
+For images, `{ size: number }` can stand in for bytes; JSON always needs bytes. The
+validator checks JSON schemas, supported versions, required non-empty files, rectangle
+bounds, matching image-size metadata and matching eye curves. It ignores unknown
+files and JSON fields and leaves the input unchanged. It does not decode PNGs or
+verify that their actual dimensions match the rectangles, and it does not judge
+artwork or animation quality. Review the rendered avatar after validation.
diff --git a/docs/reference.md b/docs/reference.md
index 64ee275..97d2130 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -18,20 +18,8 @@ the project menu. Supported browsers retain a directory handle for picked folder
ask for permission again; other browsers show **Browse again**. Image data is never stored
in this history.
-```text
-project/
- rig.json
- source.png
- built/
- layers.json
- base.png
- hairmask.png
- eye0_ball.png
- ...other cut-out layers named in layers.json
- sprites/ # optional drawn eye/mouth variants
- sprites.json
- ...sprite images
-```
+See the [avatar file and folder format](format.md) for the file layout, manifest,
+layer and sprite metadata, compatibility rules, and whole-folder validation.
## Build a project by hand
diff --git a/docs/rig-fields.md b/docs/rig-fields.md
index 7105f23..7621fec 100644
--- a/docs/rig-fields.md
+++ b/docs/rig-fields.md
@@ -1,5 +1,8 @@
# Rig fields
+See the [avatar file and folder format](format.md) for the manifest, built images and
+metadata that accompany `rig.json`.
+
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
diff --git a/package.json b/package.json
index 9bd994f..8e5b659 100644
--- a/package.json
+++ b/package.json
@@ -12,6 +12,7 @@
"build": "tsc --noEmit && vite build",
"e2e": "playwright test",
"validate-rig": "node --experimental-strip-types tools/validate-rig.mjs",
+ "validate-avatar": "node --experimental-strip-types tools/validate-avatar.mjs",
"render-poses": "node --experimental-strip-types tools/render-poses.mjs"
},
"dependencies": {
diff --git a/packages/runtime/src/format/manifest.ts b/packages/runtime/src/format/manifest.ts
new file mode 100644
index 0000000..0e91617
--- /dev/null
+++ b/packages/runtime/src/format/manifest.ts
@@ -0,0 +1,39 @@
+export interface AvatarManifest {
+ format: 'mesh-avatar';
+ version: 1;
+ name: string;
+ author?: string;
+ license?: string;
+ thumbnail?: string;
+ source?: string;
+ studio?: { version: string };
+}
+
+export function parseManifest(input: unknown): AvatarManifest {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw new Error('avatar.json: expected an object');
+ }
+ const value = input as Record<string, unknown>, errors: string[] = [];
+ if (value.format !== 'mesh-avatar') errors.push('avatar.json.format: expected "mesh-avatar"');
+ if (value.version !== 1) errors.push(`avatar.json.version: unsupported version ${JSON.stringify(value.version) ?? 'missing'} (expected 1)`);
+ if (typeof value.name !== 'string' || !value.name.trim()) errors.push('avatar.json.name: expected a non-empty string');
+ const manifest: AvatarManifest = { format: 'mesh-avatar', version: 1, name: value.name as string };
+ for (const key of ['author', 'license', 'thumbnail', 'source'] as const) {
+ if (value[key] === undefined) continue;
+ if (typeof value[key] !== 'string') errors.push(`avatar.json.${key}: expected a string`);
+ else manifest[key] = value[key];
+ }
+ if (value.studio !== undefined) {
+ const studio = value.studio;
+ if (!studio || typeof studio !== 'object' || Array.isArray(studio)
+ || !('version' in studio) || typeof studio.version !== 'string' || !studio.version.trim()) {
+ errors.push('avatar.json.studio.version: expected a non-empty string');
+ } else manifest.studio = { version: studio.version };
+ }
+ if (errors.length) throw new Error(errors.join('\n'));
+ return manifest;
+}
+
+export function defaultManifest(name: string): AvatarManifest {
+ return parseManifest({ format: 'mesh-avatar', version: 1, name });
+}
diff --git a/packages/runtime/src/format/validate.ts b/packages/runtime/src/format/validate.ts
new file mode 100644
index 0000000..03ee9d0
--- /dev/null
+++ b/packages/runtime/src/format/validate.ts
@@ -0,0 +1,113 @@
+import { validateRig } from '../rig/validate.ts';
+import type { Rig } from '../rig/types';
+import { parseManifest } from './manifest.ts';
+
+type FileData = Uint8Array | { size: number };
+const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
+const numbers = (value: unknown, length: number): value is number[] => Array.isArray(value)
+ && value.length === length && value.every(n => typeof n === 'number' && Number.isFinite(n));
+const own = (value: object, key: string) => Object.hasOwn(value, key);
+
+/** Validate folder metadata and required files without decoding images or performing I/O. */
+export function validateAvatarFiles(files: Record<string, FileData>): string[] {
+ const errors: string[] = [];
+ function json(path: string, required = true): Record<string, unknown> | undefined {
+ if (!own(files, path)) {
+ if (required) errors.push(`${path}: missing file`);
+ return;
+ }
+ const data = files[path];
+ if (!(data instanceof Uint8Array)) { errors.push(`${path}: JSON bytes are required`); return; }
+ let value: unknown;
+ try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(data)); }
+ catch { errors.push(`${path}: invalid UTF-8 JSON`); return; }
+ if (!object(value)) { errors.push(`${path}: expected an object`); return; }
+ return value;
+ }
+ function version(value: Record<string, unknown>, path: string, legacy = true): boolean {
+ if (value.version === 1 || (legacy && value.version === undefined)) return true;
+ errors.push(`${path}.version: unsupported version ${JSON.stringify(value.version) ?? 'missing'} (expected 1)`);
+ return false;
+ }
+ function image(path: string) {
+ if (!own(files, path)) { errors.push(`${path}: missing file`); return; }
+ const data = files[path], size = data instanceof Uint8Array ? data.byteLength : data?.size;
+ if (!Number.isSafeInteger(size) || size <= 0) errors.push(`${path}: expected a non-empty file`);
+ }
+ function layers(value: unknown, path: string, directory: string, size?: number[]) {
+ if (!object(value)) { errors.push(`${path}.layers: expected a layer rectangle map`); return; }
+ for (const [name, rect] of Object.entries(value)) {
+ const field = `${path}.layers.${name}`;
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) {
+ errors.push(`${field}: expected a safe layer name (letters, digits, hyphens or underscores)`);
+ continue;
+ }
+ if (!numbers(rect, 4) || !rect.every(Number.isInteger) || rect[0] < 0 || rect[1] < 0 || rect[2] <= 0 || rect[3] <= 0) {
+ errors.push(`${field}: expected [x, y, width, height] with non-negative integer origins and positive integer dimensions`);
+ } else if (size && (rect[0] + rect[2] > size[0] || rect[1] + rect[3] > size[1])) {
+ errors.push(`${field}: rectangle must stay inside the image`);
+ }
+ image(`${directory}/${name}.png`);
+ }
+ return value;
+ }
+ function build(value: Record<string, unknown>, path: string) {
+ if (typeof value.build !== 'string' || !value.build.trim()) errors.push(`${path}.build: expected a non-empty string`);
+ }
+
+ const manifest = json('avatar.json', false);
+ if (manifest) {
+ try { parseManifest(manifest); }
+ catch (error) { errors.push((error as Error).message); }
+ }
+ const rawRig = json('rig.json');
+ let rig: Rig | undefined;
+ if (rawRig && version(rawRig, 'rig.json', false)) {
+ const problems = validateRig(rawRig);
+ errors.push(...problems.map(error => `rig.json: ${error}`));
+ if (!problems.length) rig = rawRig as unknown as Rig;
+ }
+ image('built/base.png'); image('built/hairmask.png');
+ const meta = json('built/layers.json');
+ if (meta && version(meta, 'built/layers.json')) {
+ build(meta, 'built/layers.json');
+ let size: number[] | undefined;
+ if (!numbers(meta.size, 2) || !meta.size.every(n => Number.isInteger(n) && n > 0)) {
+ errors.push('built/layers.json.size: expected [width, height] with positive integer dimensions');
+ } else {
+ size = meta.size;
+ if (rig && (size[0] !== rig.image.width || size[1] !== rig.image.height)) errors.push('built/layers.json.size: must match rig.json.image');
+ }
+ const rectangles = layers(meta.layers, 'built/layers.json', 'built', size);
+ if (rig && rectangles) {
+ const required = [...rig.eyes.flatMap((_, i) => ['ball', 'low', 'crease', 'lash'].map(part => `eye${i}_${part}`)),
+ ...(rig.hand ? ['hand'] : []), ...(rig.accessories ?? []).map(part => part.name)];
+ for (const name of required) if (!own(rectangles, name)) errors.push(`built/layers.json.layers.${name}: missing required layer`);
+ }
+ if (!Array.isArray(meta.eyes) || meta.eyes.length !== 2) {
+ errors.push('built/layers.json.eyes: expected two eye curves');
+ } else meta.eyes.forEach((eye: unknown, i: number) => {
+ const path = `built/layers.json.eyes[${i}]`;
+ if (!object(eye)) { errors.push(`${path}: expected an object`); return; }
+ const span = numbers([eye.x0, eye.x1], 2) && (eye.x0 as number) < (eye.x1 as number);
+ if (!span) errors.push(`${path}: expected finite x0 < x1`);
+ for (const key of ['top', 'bot'] as const) {
+ if (!numbers(eye[key], 24)) errors.push(`${path}.${key}: expected 24 finite numbers`);
+ }
+ if (numbers(eye.top, 24) && numbers(eye.bot, 24) && eye.top.some((y, k) => y > (eye.bot as number[])[k])) {
+ errors.push(`${path}.top: must not exceed bottom curve`);
+ }
+ if (rig) for (const key of ['x0', 'x1', 'top', 'bot'] as const) {
+ const a = eye[key], b = rig.eyes[i][key];
+ const same = Array.isArray(b) ? numbers(a, b.length) && a.every((n, k) => n === b[k]) : a === b;
+ if (!same) errors.push(`${path}.${key}: must match rig.json.eyes[${i}].${key}`);
+ }
+ });
+ }
+ const sprites = json('built/sprites/sprites.json', false);
+ if (sprites && version(sprites, 'built/sprites/sprites.json')) {
+ build(sprites, 'built/sprites/sprites.json');
+ layers(sprites.layers, 'built/sprites/sprites.json', 'built/sprites', rig ? [rig.image.width, rig.image.height] : undefined);
+ }
+ return errors;
+}
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 85564f1..0a53bd0 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -5,3 +5,6 @@ export { validateRig, parseRig } from './rig/validate';
export { PARAMS } from './engine/rig.js';
export type { LightingSettings } from './lighting/settings';
export { DEFAULT_LIGHTING, parseLighting, colorHex } from './lighting/settings';
+export type { AvatarManifest } from './format/manifest';
+export { parseManifest } from './format/manifest';
+export { validateAvatarFiles } from './format/validate';
diff --git a/packages/runtime/tests/format.test.ts b/packages/runtime/tests/format.test.ts
new file mode 100644
index 0000000..a46ec54
--- /dev/null
+++ b/packages/runtime/tests/format.test.ts
@@ -0,0 +1,126 @@
+import { readFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { expect, test } from 'vitest';
+import { validateAvatarFiles } from 'mesh-avatar';
+import rig from '../../../samples/miko-qipao/rig.json';
+import metadata from '../../../samples/miko-qipao/built/layers.json';
+import sprites from '../../../samples/miko-qipao/built/sprites/sprites.json';
+import manifest from '../../../samples/miko-qipao/avatar.json';
+
+const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));
+function fixture(): Parameters<typeof validateAvatarFiles>[0] {
+ const files: Parameters<typeof validateAvatarFiles>[0] = {
+ 'avatar.json': encode(manifest), 'rig.json': encode(rig),
+ 'built/layers.json': encode(metadata), 'built/sprites/sprites.json': encode(sprites),
+ 'built/base.png': { size: 1 }, 'built/hairmask.png': { size: 1 },
+ };
+ for (const name of Object.keys(metadata.layers)) files[`built/${name}.png`] = { size: 1 };
+ for (const name of Object.keys(sprites.layers)) files[`built/sprites/${name}.png`] = { size: 1 };
+ return files;
+}
+
+test('validates the actual sample files through the public API and the Node CLI', () => {
+ const root = new URL('../../../samples/miko-qipao/', import.meta.url);
+ const files = Object.fromEntries(Object.keys(fixture()).map(path => [path, readFileSync(new URL(path, root))]));
+ expect(validateAvatarFiles(files)).toEqual([]);
+ const cli = fileURLToPath(new URL('../../../tools/validate-avatar.mjs', import.meta.url));
+ const result = spawnSync(process.execPath, ['--experimental-strip-types', cli, fileURLToPath(root)], { encoding: 'utf8' });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Valid avatar folder: miko-qipao');
+});
+
+test('accepts legacy folders, optional sprites and unknown files and keys without mutating inputs', () => {
+ const files = fixture();
+ delete files['avatar.json'];
+ delete files['built/sprites/sprites.json'];
+ files['built/layers.json'] = encode({ ...metadata, future: { enabled: true } });
+ files['notes.txt'] = { size: 0 };
+ const before = structuredClone(files);
+ expect(validateAvatarFiles(files)).toEqual([]);
+ expect(files).toEqual(before);
+ files['built/layers.json'] = encode({ ...metadata, version: 1 });
+ files['built/sprites/sprites.json'] = encode({ ...sprites, version: 1 });
+ expect(validateAvatarFiles(files)).toEqual([]);
+});
+
+test.each(['rig.json', 'built/layers.json', 'built/base.png', 'built/hairmask.png',
+ 'built/eye0_ball.png', 'built/tassel_l.png', 'built/sprites/mouth_a.png'])('names missing file %s', path => {
+ const files = fixture(); delete files[path];
+ expect(validateAvatarFiles(files)).toContain(`${path}: missing file`);
+});
+
+test.each(['hand', 'eye0_crease', 'tassel_l'])('requires the rig-referenced rectangle %s', name => {
+ const files = fixture(), layers: Record<string, number[]> = { ...metadata.layers };
+ delete layers[name];
+ files['built/layers.json'] = encode({ ...metadata, layers });
+ expect(validateAvatarFiles(files)).toContain(`built/layers.json.layers.${name}: missing required layer`);
+});
+
+test('permits omitted hand and accessories when they are absent from the rig', () => {
+ const files = fixture(), optionalRig: Record<string, unknown> = { ...rig };
+ delete optionalRig.hand; delete optionalRig.accessories;
+ const layers: Record<string, number[]> = { ...metadata.layers };
+ for (const name of ['hand', ...rig.accessories.map(a => a.name)]) {
+ delete layers[name]; delete files[`built/${name}.png`];
+ }
+ files['rig.json'] = encode(optionalRig);
+ files['built/layers.json'] = encode({ ...metadata, layers });
+ expect(validateAvatarFiles(files)).toEqual([]);
+});
+
+test.each(['avatar.json', 'rig.json', 'built/layers.json', 'built/sprites/sprites.json'])('rejects future versions in %s', path => {
+ const files = fixture(), json = JSON.parse(new TextDecoder().decode(files[path] as Uint8Array));
+ files[path] = encode({ ...json, version: 2 });
+ expect(validateAvatarFiles(files)).toContain(`${path}.version: unsupported version 2 (expected 1)`);
+});
+
+test.each(['x0', 'x1', 'top', 'bot'] as const)('rejects a mismatched copied eye field %s', field => {
+ const files = fixture(), changed = structuredClone(metadata);
+ if (field === 'top' || field === 'bot') changed.eyes[1][field][5] += 0.01;
+ else changed.eyes[1][field] += 0.01;
+ files['built/layers.json'] = encode(changed);
+ expect(validateAvatarFiles(files)).toContain(`built/layers.json.eyes[1].${field}: must match rig.json.eyes[1].${field}`);
+});
+
+test('rejects a draft rig, inconsistent image dimensions and malformed metadata', () => {
+ const files = fixture();
+ files['rig.json'] = encode({ ...rig, eyes: rig.eyes.map(({ opening, roi }) => ({ opening, roi })) });
+ expect(validateAvatarFiles(files).join('\n')).toContain('rig.json: rig.eyes[0].top:');
+ files['rig.json'] = encode(rig);
+ files['built/layers.json'] = encode({ ...metadata, size: [2000, 2000] });
+ expect(validateAvatarFiles(files)).toContain('built/layers.json.size: must match rig.json.image');
+ files['built/layers.json'] = encode({ version: 1, size: [0, 1254], layers: [], eyes: [] });
+ const errors = validateAvatarFiles(files).join('\n');
+ for (const field of ['size', 'build', 'layers', 'eyes']) expect(errors).toContain(`built/layers.json.${field}:`);
+ files['built/sprites/sprites.json'] = encode({ version: 1, build: '', layers: [] });
+ expect(validateAvatarFiles(files).join('\n')).toContain('built/sprites/sprites.json.layers: expected a layer rectangle map');
+});
+
+test('checks rectangle coordinates and file names in layer and sprite maps', () => {
+ for (const [path, meta] of [['built/layers.json', metadata], ['built/sprites/sprites.json', sprites]] as const) {
+ for (const rect of [[-1, 0, 1, 1], [0, 0, 0, 1], [0.5, 0, 1, 1], [1253, 0, 2, 1]]) {
+ const files = fixture(), name = Object.keys(meta.layers)[0];
+ files[path] = encode({ ...meta, layers: { ...meta.layers, [name]: rect } });
+ expect(validateAvatarFiles(files).join('\n')).toContain(`${path}.layers.${name}:`);
+ }
+ const files = fixture();
+ files[path] = encode({ ...meta, layers: { ...meta.layers, '../escape': [0, 0, 1, 1] } });
+ expect(validateAvatarFiles(files).join('\n')).toContain(`${path}.layers.../escape: expected a safe layer name`);
+ }
+});
+
+test('requires bytes for JSON and non-empty bytes or size metadata for images', () => {
+ const files = fixture();
+ for (const data of [encode(null), new Uint8Array([0xff]), new TextEncoder().encode('{'), { size: 1 }]) {
+ files['avatar.json'] = data;
+ expect(validateAvatarFiles(files).join('\n')).toContain('avatar.json:');
+ }
+ delete files['avatar.json'];
+ for (const data of [new Uint8Array(), { size: 0 }, { size: -1 }, { size: 1.5 }]) {
+ files['built/base.png'] = data;
+ expect(validateAvatarFiles(files)).toContain('built/base.png: expected a non-empty file');
+ }
+ files['built/base.png'] = new Uint8Array([1]);
+ expect(validateAvatarFiles(files)).toEqual([]);
+});
diff --git a/packages/runtime/tests/manifest.test.ts b/packages/runtime/tests/manifest.test.ts
new file mode 100644
index 0000000..1e68942
--- /dev/null
+++ b/packages/runtime/tests/manifest.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from 'vitest';
+import { parseManifest } from 'mesh-avatar';
+import { defaultManifest } from '../src/format/manifest';
+
+const manifest = { format: 'mesh-avatar', version: 1, name: 'My avatar' };
+
+test('parses known manifest fields without retaining unknown data or shared objects', () => {
+ const input = { ...manifest, author: 'Artist', license: 'Artwork terms', source: 'source.png',
+ thumbnail: 'thumbnail.png', studio: { version: '0.1.0', extra: true }, extra: true };
+ const parsed = parseManifest(input);
+ expect(parsed).toEqual({ ...manifest, author: 'Artist', license: 'Artwork terms', source: 'source.png',
+ thumbnail: 'thumbnail.png', studio: { version: '0.1.0' } });
+ expect(parsed).not.toBe(input);
+ expect(parsed.studio).not.toBe(input.studio);
+ expect(input.studio.extra).toBe(true);
+ expect(defaultManifest('Old folder')).toEqual({ ...manifest, name: 'Old folder' });
+});
+
+test.each([null, [], 'avatar'])('rejects non-object manifest %j', input => {
+ expect(() => parseManifest(input)).toThrow('avatar.json: expected an object');
+});
+
+test.each([
+ [{ format: 'other' }, 'format'], [{ version: 2 }, 'version'],
+ [{ version: undefined }, 'version'], [{ name: ' ' }, 'name'],
+ [{ author: 1 }, 'author'], [{ license: false }, 'license'],
+ [{ source: null }, 'source'], [{ thumbnail: [] }, 'thumbnail'],
+ [{ studio: {} }, 'studio.version'], [{ studio: [] }, 'studio.version'],
+ [{ studio: { version: '' } }, 'studio.version'],
+])('names invalid manifest field in %j', (change, field) => {
+ expect(() => parseManifest({ ...manifest, ...change })).toThrow(`avatar.json.${field}:`);
+});
diff --git a/samples/miko-qipao/avatar.json b/samples/miko-qipao/avatar.json
new file mode 100644
index 0000000..364c41c
--- /dev/null
+++ b/samples/miko-qipao/avatar.json
@@ -0,0 +1,7 @@
+{
+ "format": "mesh-avatar",
+ "version": 1,
+ "name": "Miko (qipao)",
+ "author": "Yuki Shindo (AITuber OnAir)",
+ "license": "See MIKO_ASSET_TERMS.md"
+}
diff --git a/tools/build-layers.py b/tools/build-layers.py
index b8d86ed..3ef2883 100755
--- a/tools/build-layers.py
+++ b/tools/build-layers.py
@@ -575,6 +575,7 @@ def build(project, rig_path):
meta["eyes"] = [
{k: eye[k] for k in ("x0", "x1", "top", "bot")} for eye in rig["eyes"]
]
+ meta["version"] = 1
prefill, painted = (
hand_prefill(rgba, remove, hand) if hand else (rgba, np.zeros_like(remove))
diff --git a/tools/build-sprites.py b/tools/build-sprites.py
index 6184655..3de139b 100644
--- a/tools/build-sprites.py
+++ b/tools/build-sprites.py
@@ -128,7 +128,7 @@ def build(project, output=None, tolerance=8):
b"".join((stage / f"{name}.png").read_bytes() for name in sorted(meta))
).hexdigest()[:10]
(stage / "sprites.json").write_text(
- json.dumps({"build": build_id, "layers": meta}, indent=2) + "\n",
+ json.dumps({"build": build_id, "layers": meta, "version": 1}, indent=2) + "\n",
encoding="utf-8",
)
output.mkdir(exist_ok=True)
diff --git a/tools/new-project.py b/tools/new-project.py
index d337dcf..7a8e420 100644
--- a/tools/new-project.py
+++ b/tools/new-project.py
@@ -97,6 +97,8 @@ def create(source, name, force=False):
(project / "work").mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, project / "source.png")
save_json(rig, project / "rig.draft.json")
+ if not (project / "avatar.json").exists():
+ save_json({"format": "mesh-avatar", "version": 1, "name": name}, project / "avatar.json")
print(
f"Created projects/{name}/ ({w} x {h}). Trace the empty eyes and place every required region before building."
)
diff --git a/tools/test_agent_tools.py b/tools/test_agent_tools.py
index 0744db4..dc27ec8 100644
--- a/tools/test_agent_tools.py
+++ b/tools/test_agent_tools.py
@@ -99,9 +99,17 @@ class AgentToolsTest(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("no alpha", result.stderr)
self.assertIn("800", result.stderr)
+ manifest = created / "avatar.json"
+ self.assertEqual(json.loads(manifest.read_text()), {
+ "format": "mesh-avatar", "version": 1, "name": name,
+ })
before = (created / "rig.draft.json").read_bytes()
self.assertEqual(self.cli("new-project", rgb, name).returncode, 1)
self.assertEqual((created / "rig.draft.json").read_bytes(), before)
+ manifest.write_text(json.dumps({"format": "mesh-avatar", "version": 1, "name": "Custom name", "author": "Artist"}))
+ manifest_before = manifest.read_bytes()
+ self.assertEqual(self.cli("new-project", rgb, name, "--force").returncode, 0)
+ self.assertEqual(manifest.read_bytes(), manifest_before)
with self.assertRaises(ValueError):
new.create(rgb, "../escape")
wrong = self.project / "source.jpg"
@@ -137,6 +145,8 @@ class AgentToolsTest(unittest.TestCase):
sprites.build(self.project)
metadata = self.project / "built/sprites/sprites.json"
before = metadata.read_bytes()
+ self.assertEqual(json.loads(before)["version"], 1)
+ self.assertEqual(list(json.loads(before)), ["build", "layers", "version"])
self.assertEqual(json.loads(before)["layers"]["mouth_a"][2] > 0, True)
invalid = valid.copy()
invalid.putpixel((0, 0), (0, 0, 0, 255))
diff --git a/tools/test_build_layers.py b/tools/test_build_layers.py
index ee8f52e..73832ee 100644
--- a/tools/test_build_layers.py
+++ b/tools/test_build_layers.py
@@ -59,6 +59,8 @@ class BuildLayersTest(unittest.TestCase):
self.assertEqual(self.draft.read_bytes(), before)
self.assertEqual((sprites / "keep.txt").read_text(), "keep")
meta = json.loads((self.project / "built/layers.json").read_text())
+ self.assertEqual(meta["version"], 1)
+ self.assertEqual(list(meta), ["size", "build", "layers", "eyes", "version"])
rig = json.loads((self.project / "rig.json").read_text())
self.assertEqual(len(meta["layers"]), 8)
self.assertNotIn("hand", meta["layers"])
diff --git a/tools/validate-avatar.mjs b/tools/validate-avatar.mjs
new file mode 100644
index 0000000..50c3ed9
--- /dev/null
+++ b/tools/validate-avatar.mjs
@@ -0,0 +1,31 @@
+import { readdir, readFile, stat } from 'node:fs/promises';
+import { basename, resolve } from 'node:path';
+import { validateAvatarFiles } from '../packages/runtime/src/format/validate.ts';
+
+const args = process.argv.slice(2);
+if (args.length !== 1 || args.includes('--help')) {
+ console.log('Usage: npm run validate-avatar -- <project-folder>');
+ process.exit(args.includes('--help') ? 0 : 1);
+}
+try {
+ const root = resolve(args[0]);
+ if (!(await stat(root)).isDirectory()) throw new Error('Expected a project folder; .mavatar archives are not supported by this command yet.');
+ const files = Object.create(null);
+ async function readFolder(directory, prefix = '') {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const key = `${prefix}${entry.name}`, path = resolve(directory, entry.name);
+ if (entry.isDirectory()) await readFolder(path, `${key}/`);
+ else if (entry.isFile()) files[key] = await readFile(path);
+ // Symlinks and special files are not read; required assets must be regular files.
+ }
+ }
+ await readFolder(root);
+ const errors = validateAvatarFiles(files);
+ if (errors.length) {
+ errors.forEach(error => console.error(error));
+ process.exitCode = 1;
+ } else console.log(`Valid avatar folder: ${basename(root)}`);
+} catch (error) {
+ console.error(`validate-avatar: ${error.message}`);
+ process.exitCode = 1;
+}
diff --git a/tsconfig.json b/tsconfig.json
index 388274d..d1cbd2b 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -14,6 +14,7 @@
"jsx": "react-jsx",
"strict": true,
"allowJs": true,
+ "allowImportingTsExtensions": true,
"checkJs": false,
"resolveJsonModule": true,
"esModuleInterop": true,