Skip to content

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

Reorganize the native guide around embedding

shinshin86058605183eb2
diff --git a/native/README.ja.md b/native/README.ja.md
index b39f666..c327fc8 100644
--- a/native/README.ja.md
+++ b/native/README.ja.md
@@ -2,22 +2,96 @@
[English](README.md) · [简体中文](README.zh.md)
-> **実験的な機能です。** ネイティブ版のランタイムは開発中で、パッケージとしては公開していません。
+> **実験的な機能です。** ネイティブ版のランタイムは開発中で、クレートはcrates.ioに公開していません。
> API、操作方法、ファイルの保存場所は予告なく変わることがあります。基準となる実装は `packages/runtime` の JavaScript 版です。
Rust 版のランタイムは、JavaScript 版と同じ `.mavatar` ファイルとビルド済みプロジェクトフォルダを読み込みます。
-透明なデスクトップアバターと PNG レンダラーが入っています。デスクトップ版の主な対象は Metal を使う macOS です。
+透明なデスクトップアバター、PNGレンダラー、Rust/C向けの組み込みAPIが入っています。デスクトップ版の主な対象は Metal を使う macOS です。
## 必要なもの
- Rust 1.88 以降と Cargo。
-- macOS では Xcode Command Line Tools と、Metal に対応した GPU。
+- macOSではXcode Command Line Tools。描画にはMetal対応GPUも必要です。
+- Cのサンプルには `cc` と `make`(macOSで確認済み)。CPUのデータAPIにGPUは不要です。
- アバターのアーカイブ、または `rig.json`・`built/layers.json`・ビルド済み PNG を含むプロジェクト。
イラスト単体ではアバターとして動かせません。
以下のコマンドはリポジトリのルートで実行します。既定のアバターは `samples/miko-qipao` で、その画像がインストールされている必要があります。
サンプルには[素材の利用規約](../samples/miko-qipao/MIKO_ASSET_TERMS.md)が適用されます。
+## アプリに組み込む
+
+### Rust のクレート
+
+組み込み先のアプリの `Cargo.toml` に追加します。このリポジトリのルートではありません。
+
+```toml
+[dependencies]
+mesh-avatar-core = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-core" }
+mesh-avatar-wgpu = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-wgpu" }
+```
+
+これらのクレートは crates.io には公開していません。Git依存はリポジトリの既定ブランチを参照します。
+ビルドを再現できるよう、アプリの `Cargo.lock` をコミットするか、両方に `rev` を指定して同じコミットに固定してください。リビジョン間でAPIが変わることがあります。
+
+`mesh-avatar-core` はCPU上でアバターを読み込み、操作を反映してアニメーションを進めます。自前のレンダラーがあれば `mesh-avatar-wgpu` は不要です。
+`Avatar::tick` が返す `Frame` は、頂点座標・UV・三角形のインデックス・テクスチャ名・アルファを持つ描画順のレイヤーと、フレーム全体の顔用uniformを所有します。`Avatar::textures` からはデコード済みのストレートアルファのRGBA8画像を取得できます。
+`mesh-avatar-wgpu::Renderer` はそのフレームをホストが用意したwgpuのテクスチャビューへ描画し、RGBAへの読み戻しにも対応します。
+Rustのフレームはデータを所有します。以下のポインターの有効期間はC ABIだけの条件です。
+
+### C ABI
+
+このチェックアウトから `mesh-avatar-ffi` をビルドすると、`native/target/release/` に `libmesh_avatar_ffi.a` と共有ライブラリ(macOSでは `libmesh_avatar_ffi.dylib`)ができます。
+[`mesh_avatar.h`](include/mesh_avatar.h) をインクルードしてください。通常ビルドの依存先はcoreだけなので、自前のメッシュレンダラーを持つホストにwgpuは不要です。
+
+`mesh_avatar_tick` はフレームをキャッシュします。`mesh_avatar_get_frame` で、描画順のレイヤー(頂点座標・UV・三角形のインデックスと要素数・アルファ・テクスチャID)と、フレーム全体の顔用uniformを取得できます。
+テクスチャAPIからはサイズとデコード済みのストレートアルファのRGBA8画像を取得します。ホスト側でテクスチャを転送してメッシュを描画してください。CPUのデータAPIはウィンドウや画像を描画しません。
+
+ビルド済みフォルダやアーカイブは `mesh_avatar_open_path`、メモリ上のアーカイブは `mesh_avatar_open_bytes` で開きます。
+入力は呼び出し中に読み取り・コピーするため、開いた後はアーカイブのバッファを解放できます。ハンドルには `uint64_t` の識別子を使い、0は無効です。
+別のスレッドへ渡して使えます。同じハンドルへのAPI呼び出しは内部で直列化します。使い終わったら `mesh_avatar_destroy` を呼んでください。
+
+フレームとレイヤーには、ライブラリが所有する読み取り専用ポインターが入っています。有効期間は、そのハンドルの次のtickか破棄までです。設定だけを変更してもキャッシュしたフレームは変わりません。
+テクスチャ名とストレートアルファのRGBA8画像は、ハンドルの破棄まで有効です。これらのポインターは解放しないでください。
+tick後も必要なデータはコピーし、別スレッドからのtick・破棄とデータの読み取りが重ならないよう同期してください。
+各関数の `MaStatus` を確認し、失敗時は `mesh_avatar_last_error` を読みます。エラー文字列は同じスレッドで次のAPIを呼ぶまで有効です。
+Rustのpanicを検知したハンドルは、破棄して開き直します。ポインターと要素数、所有権の条件は生成ヘッダーにも記載しています。
+
+#### 任意機能のヘッドレス描画
+
+自前のメッシュレンダラーがないホストでは、`render` を有効にしてオフスクリーンの描画結果をコピーできます。
+
+描画用には [`mesh_avatar_render.h`](include/mesh_avatar_render.h) を読み込みます。このヘッダーはCPU用ヘッダーを含むため、マクロの指定は不要です。
+描画関数は `render` を有効にしたライブラリでのみ利用できます。
+
+アバターのハンドルと `MaRenderOptions` でレンダラーを作成します。物理ピクセルの幅・高さ、MSAAのサンプル数(1または4)、contain/cover、余白を指定します。余白の推奨値は `mesh_avatar_get_info` で取得できます。
+描画は現在のキャッシュ済みフレームを読み取り、呼び出し側のバッファへRGBA8を上の行から隙間なくコピーします。アニメーションは進みません。バッファは `幅*高さ*4` バイト以上必要で、ストレート/プリマルチプライドのアルファを選べます。
+描画はGPUからの読み戻しが完了するまで待ちます。バッファを保持せず、借用中のフレームデータも無効にしません。リサイズ後もfit・余白・サンプル数は維持されますが、呼び出し側のバッファもサイズに合わせて確保してください。不正なサイズやバッファはエラーとなり、出力バッファは変更されません。
+
+レンダラーはスレッド間で移動でき、同じレンダラー・アバターへの呼び出しは直列に処理されます。アバターを所有しないため、レンダラーを先に破棄してください。アバター破棄後の描画は `MA_INVALID_HANDLE` を返します。封じ込められたpanicの影響を受けたオブジェクトは破棄して作り直してください。
+対応するGPUアダプターがない場合は `MA_GPU_UNAVAILABLE`、それ以外のGPUエラーは `MA_RENDER_ERROR` を返します。サンプルとCIはアダプターがない場合だけ描画をスキップします。
+
+### C のサンプル
+
+サンプルは `cc` と `make` を使って静的ライブラリにリンクし、`samples/miko-qipao` を開きます。
+CPU版と `render` 版は同じライブラリのパスに出力するため、各サンプルの直前に対応するビルドを実行してください。
+
+[データ取得のサンプル](examples/c/main.c)はポーズを設定して時間を進め、メッシュとテクスチャの統計、不正な入力への応答を確認します。
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+[描画のサンプル](examples/c/render.c)はアルファの両形式、フレームのキャッシュが維持されること、リサイズを検証し、`native/target/ffi-render.ppm` に保存します。
+PPMはアルファを持たないため、ストレートRGBAを白背景に合成します。どちらのサンプルもウィンドウやマイクを起動しません。
+macOSでは、Makefileが描画に必要なMetalなどのフレームワークをリンクします。
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
## デスクトップアプリ
```sh
@@ -107,34 +181,35 @@ macOSでは、システムのステータスバーにある単色のアバター
```sh
cargo run --release --manifest-path native/Cargo.toml -p mesh-avatar-wgpu \
- --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o avatar.png
+ --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o native/target/avatar.png
```
`--pose` には `{"angleX":20,"mouthOpen":0.8}` のような JSON オブジェクトを渡します。
指定しなかったポーズのパラメータは既定値になります。`--seconds` を指定すると、書き出す前に毎秒 60 ステップでアバターの時間を進めます。
`--help` で、表示余白、fit、表情、マルチサンプリングのオプションを確認できます。
-## C ABIを使う
+## 開発時の確認
+
+ここでもシェルコマンドはリポジトリのルートで実行します。JavaScript版との比較にはNode.js 22.17以降とnpmの依存関係が必要です。
+まだインストールしていなければ `npm ci` を実行してください。
```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
-make -C native/examples/c run
+node --experimental-strip-types native/conformance/dump.mjs
+cargo test --manifest-path native/Cargo.toml --all-features
+cargo clippy --manifest-path native/Cargo.toml --all-targets --all-features -- -D warnings
+cargo fmt --manifest-path native/Cargo.toml --all --check
```
-CPU版ライブラリの `libmesh_avatar_ffi.a` と共有ライブラリ(macOSでは `libmesh_avatar_ffi.dylib`)が `native/target/release/` に生成されます。
-ホスト側では [`mesh_avatar.h`](include/mesh_avatar.h) をインクルードします。Cのサンプルは、アバターにポーズを設定して時間を進め、頂点・uniform・テクスチャと不正な入力への応答を確認します。ウィンドウやマイクは起動しません。
+dumpは、埋め込んだモーションデータの一致を確認し、数値の比較用データをGit管理外の `native/target/conformance/` に出力します。
+テストの前に生成してください。データがなければ比較テストはスキップした旨を表示します。対応GPUがない環境ではGPU読み戻しのテストもスキップします。
+coreはWASM向けにもビルドできます。JavaScriptバインディングは含みません。
-ビルド済みフォルダやアーカイブは `mesh_avatar_open_path`、メモリ上のアーカイブは `mesh_avatar_open_bytes` で開きます。
-入力は呼び出し中に読み取り・コピーするため、開いた後はアーカイブのバッファを解放できます。ハンドルには `uint64_t` の識別子を使い、0は無効です。
-別のスレッドへ渡して使えます。同じハンドルへのAPI呼び出しは内部で直列化します。使い終わったら `mesh_avatar_destroy` を呼んでください。
-
-フレームとレイヤーには、ライブラリが所有する読み取り専用ポインターが入っています。有効期間は、そのハンドルの次のtickか破棄までです。設定だけを変更してもキャッシュしたフレームは変わりません。
-テクスチャ名とストレートアルファのRGBA8画像は、ハンドルの破棄まで有効です。これらのポインターは解放しないでください。
-tick後も必要なデータはコピーし、別スレッドからのtick・破棄とデータの読み取りが重ならないよう同期してください。
-各関数の `MaStatus` を確認し、失敗時は `mesh_avatar_last_error` を読みます。エラー文字列は同じスレッドで次のAPIを呼ぶまで有効です。
-Rustのpanicを検知したハンドルは、破棄して開き直します。ポインターと要素数、所有権の条件は生成ヘッダーにも記載しています。
+```sh
+rustup target add wasm32-unknown-unknown
+cargo check --manifest-path native/Cargo.toml -p mesh-avatar-core --target wasm32-unknown-unknown
+```
-通常のライブラリビルドにヘッダー生成ツールは不要です。ヘッダーを更新するときは、バージョンを固定した開発用ツールをGit管理外のビルド先へ入れます。
+通常のライブラリビルドにcbindgenは不要です。ヘッダーを更新するときは、バージョンを固定したツールをGit管理外のビルド先へ入れ、両ヘッダーを再生成して差分を確認します。
```sh
cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
@@ -142,44 +217,21 @@ bash native/conformance/ffi-header.sh
bash native/conformance/ffi-header.sh --check
```
-CIも同じバージョンで両ヘッダーの差分を確認し、ライブラリとCサンプルをビルド・実行します。C ABIは実験的な段階です。
-
-### 任意機能のヘッドレス描画
+CIではWASM、フォーマット・lint・テスト、両ヘッダー、Cの両サンプルを確認します。描画サンプルは対応するGPUアダプターがない場合だけスキップします。
-```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
-make -C native/examples/c run-render
-```
+### 画素を比較する
-描画用には [`mesh_avatar_render.h`](include/mesh_avatar_render.h) を読み込みます。このヘッダーはCPU用ヘッダーを含むため、マクロの指定は不要です。
-描画関数は `render` を有効にしたライブラリでのみ利用できます。通常ビルドの依存先はcoreだけです。macOSでは、C用MakefileがMetalなどの必要なフレームワークをリンクします。
-
-アバターのハンドルと `MaRenderOptions` でレンダラーを作成します。物理ピクセルの幅・高さ、MSAAのサンプル数(1または4)、contain/cover、余白を指定します。余白の推奨値は `mesh_avatar_get_info` で取得できます。
-描画は現在のキャッシュ済みフレームを読み取り、呼び出し側のバッファへRGBA8を上の行から隙間なくコピーします。アニメーションは進みません。バッファは `幅*高さ*4` バイト以上必要で、ストレート/プリマルチプライドのアルファを選べます。
-描画はGPUからの読み戻しが完了するまで待ちます。バッファを保持せず、借用中のフレームデータも無効にしません。リサイズ後もfit・余白・サンプル数は維持されますが、呼び出し側のバッファもサイズに合わせて確保してください。不正なサイズやバッファはエラーとなり、出力バッファは変更されません。
-
-レンダラーはスレッド間で移動でき、同じレンダラー・アバターへの呼び出しは直列に処理されます。アバターを所有しないため、レンダラーを先に破棄してください。アバター破棄後の描画は `MA_INVALID_HANDLE` を返します。封じ込められたpanicの影響を受けたオブジェクトは破棄して作り直してください。
-対応するGPUアダプターがない場合は `MA_GPU_UNAVAILABLE`、それ以外のGPUエラーは `MA_RENDER_ERROR` を返します。サンプルとCIはアダプターがない場合だけ描画をスキップします。
-
-サンプルはアルファの両形式とリサイズを検証し、`native/target/ffi-render.ppm` に保存します。PPMはアルファを持たないため、ストレートRGBAを白背景に合成します。ウィンドウは開きません。
-CIではcoreの `wasm32-unknown-unknown` 向けビルドも確認します。JavaScriptバインディングは含みません。
-
-## チェックと見た目の比較
-
-Node.js 22.17 以降とリポジトリの npm 依存関係は、JavaScript 版との比較にだけ必要です。
+任意の比較コマンドです。ヘッドレスChromiumとオフスクリーンレンダラーを起動します。
+npmの依存関係、PlaywrightのChromium、対応するGPUが必要です。デバッグ版レンダラーはスクリプト内でビルドします。
```sh
-node --experimental-strip-types native/conformance/dump.mjs
-cargo test --manifest-path native/Cargo.toml
-cargo clippy --manifest-path native/Cargo.toml --all-targets -- -D warnings
-cargo fmt --manifest-path native/Cargo.toml --all --check
+npx playwright install chromium
node native/conformance/compare-pixels.mjs
```
-dump は、Rust 側に埋め込んだモーションデータが JavaScript のソースと一致しているかも確認します。
-意図して更新するときは `node --experimental-strip-types native/conformance/sync-motion-data.mjs` を実行します。
-数値の比較データ、PNG、レポートは git の管理外の `native/target/` に出力されます。生成データがない場合、比較テストはスキップした旨を表示します。
-画素の比較には Playwright がインストールした Chromium を使います。macOS では `--metal` で Metal バックエンドを選べ、`--dpr=2` で HiDPI 時に同じ物理サイズで比較します。
+PNGとレポートはGit管理外の `native/target/pixel-comparison*/` に保存します。
+macOSでは `--metal` でChromiumのMetalバックエンドを選べ、`--dpr=2` でHiDPIの物理サイズを揃えて比較できます。
+埋め込むモーションの定義を意図して更新するときは、`node --experimental-strip-types native/conformance/sync-motion-data.mjs` を実行してください。
## 制限事項
diff --git a/native/README.md b/native/README.md
index 0718fbf..b26f446 100644
--- a/native/README.md
+++ b/native/README.md
@@ -2,18 +2,19 @@
[日本語](README.ja.md) · [简体中文](README.zh.md)
-> **Experimental.** The native runtime is a work in progress. It is not published
-> as a package, and its API, controls and file locations may change without notice.
+> **Experimental.** The native runtime is a work in progress. The crates are not published
+> to crates.io. APIs, controls and file locations may change without notice.
> The JavaScript runtime in `packages/runtime` remains the reference implementation.
The Rust runtime loads the same `.mavatar` files and built project folders as the
-JavaScript runtime. It includes a transparent desktop avatar and a PNG renderer.
+JavaScript runtime. It includes a transparent desktop avatar, a PNG renderer and Rust/C embedding APIs.
The primary desktop target is macOS with Metal.
## Prerequisites
- Rust 1.88 or newer, with Cargo.
-- On macOS, the Xcode Command Line Tools and a Metal-capable GPU.
+- On macOS, the Xcode Command Line Tools; rendering also needs a Metal-capable GPU.
+- For the C examples, `cc` and `make` (verified on macOS). The CPU data API needs no GPU.
- An avatar archive, or a project containing `rig.json`, `built/layers.json` and
the built PNG assets. The illustration alone is not a playable avatar.
@@ -21,6 +22,107 @@ The commands below run from the repository root. The default avatar uses
`samples/miko-qipao`; its images must be installed. The sample's
[asset terms](../samples/miko-qipao/MIKO_ASSET_TERMS.md) apply.
+## Embedding
+
+### Rust crates
+
+Add these entries to your application's `Cargo.toml` (not this repository's root):
+
+```toml
+[dependencies]
+mesh-avatar-core = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-core" }
+mesh-avatar-wgpu = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-wgpu" }
+```
+
+These crates are not published to crates.io. Git dependencies use the repository's
+default branch; commit your application's `Cargo.lock`, or set `rev` on both entries
+to the same commit for reproducible builds. The API may change between revisions.
+
+`mesh-avatar-core` loads avatars, applies controls and advances animation on the CPU;
+omit `mesh-avatar-wgpu` if you already have a renderer. `Avatar::tick` returns an owned
+`Frame`: draw-ordered layers with vertex positions, UVs, triangle indices, texture
+names and alpha, plus frame-wide face uniforms. `Avatar::textures` supplies decoded
+straight RGBA8 textures. `mesh-avatar-wgpu::Renderer` draws that frame into a host-provided wgpu
+texture view, or reads it back to RGBA. Rust frame data is owned; the C pointer
+lifetimes below apply only to the C ABI.
+
+### C ABI
+
+Build `mesh-avatar-ffi` from this checkout for `libmesh_avatar_ffi.a` and a platform
+shared library (`libmesh_avatar_ffi.dylib` on macOS) in `native/target/release/`.
+Include [`mesh_avatar.h`](include/mesh_avatar.h). The default library depends only
+on core, so hosts with their own mesh renderer do not need wgpu.
+
+Each `mesh_avatar_tick` caches a frame. `mesh_avatar_get_frame` reads its draw-ordered
+layers (positions, UVs, triangle indices/counts, alpha and texture IDs) and frame-wide
+face uniforms. Texture access returns dimensions and decoded straight RGBA8 pixels.
+The host uploads textures and draws
+the meshes; the CPU data API does not draw a window or image.
+
+Open a built folder/archive with `mesh_avatar_open_path`, or an in-memory archive
+with `mesh_avatar_open_bytes`. Inputs are copied or consumed during the call;
+the archive buffer can be released after opening. Handles are opaque `uint64_t`
+tokens, with zero invalid. They can move between threads; calls on the same
+handle are serialized internally. Always call `mesh_avatar_destroy` when finished.
+
+Frame and layer descriptors contain borrowed, read-only pointers. They remain
+valid until the next tick or destroy on that handle; setters leave the cached
+frame intact. Texture names and straight RGBA8 pixels remain valid until destroy.
+Do not free these pointers. Copy data if it must outlive a tick, and synchronize
+borrowed reads against tick/destroy on other threads. Check every `MaStatus`;
+`mesh_avatar_last_error` returns a thread-local message until the next API call
+on that thread. A contained Rust panic requires destroying and reopening that
+handle. The generated header documents pointer/count and ownership requirements.
+
+#### Optional headless rendering
+
+For hosts without their own mesh renderer, enable `render` and copy offscreen pixels instead.
+
+Include [`mesh_avatar_render.h`](include/mesh_avatar_render.h) for this extension.
+It includes the CPU header and needs no macro; its functions are exported only
+when the library is built with `render`.
+
+Create a renderer with an avatar handle and `MaRenderOptions`: physical width/height,
+1 or 4 MSAA samples, contain/cover fit and explicit padding (available from
+`mesh_avatar_get_info`). Rendering reads the current cached frame without ticking
+and copies tightly packed, top-down RGBA8 into a caller-owned buffer of at least
+`width*height*4` bytes. Choose straight or premultiplied alpha. The synchronous
+readback does not retain the buffer or invalidate borrowed frame data. Resize
+keeps fit/padding/samples; resize the caller's buffer too. Invalid sizes/buffers
+return an error without changing the output buffer.
+
+Renderer calls may move between threads and are serialized per renderer and
+avatar. Renderers reference their avatar without owning it; destroy renderers
+before destroying the avatar. Rendering after avatar destruction returns
+`MA_INVALID_HANDLE`. Destroy/recreate objects affected by a contained panic.
+`MA_GPU_UNAVAILABLE` means no compatible adapter was found; other GPU errors use
+`MA_RENDER_ERROR`. The example/CI skip only the unavailable-adapter case.
+
+### C examples
+
+The examples use `cc` and `make`, link the static library and open
+`samples/miko-qipao`. Run the matching build before each example; CPU and `render`
+builds write the same library path.
+
+The [data example](examples/c/main.c) applies a pose, ticks, prints mesh/texture
+statistics and checks invalid-input behavior:
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+The [render example](examples/c/render.c) checks both alpha formats, frame-cache
+stability and resize, then writes `native/target/ffi-render.ppm`. PPM has no alpha,
+so it composites straight RGBA over white. Neither example opens a window or
+captures audio. On macOS, the Makefile links the required Metal/system frameworks
+for the render example:
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
## Desktop app
```sh
@@ -139,7 +241,7 @@ It does not restart automatically. Select an available input and enable it again
```sh
cargo run --release --manifest-path native/Cargo.toml -p mesh-avatar-wgpu \
- --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o avatar.png
+ --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o native/target/avatar.png
```
Supply a JSON object such as `{"angleX":20,"mouthOpen":0.8}` with `--pose`.
@@ -147,36 +249,33 @@ Unspecified pose parameters use their defaults. `--seconds` advances the avatar
at 60 simulation steps per second before rendering. `--help` lists options for
viewport padding, fit, expressions and multisampling.
-## Use the C ABI
+## Development checks
+
+All shell commands here also run from the repository root. Node.js 22.17 or newer
+and the npm dependencies are needed for comparison with the JavaScript runtime.
+Install those dependencies with `npm ci` if they are not already installed.
```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
-make -C native/examples/c run
+node --experimental-strip-types native/conformance/dump.mjs
+cargo test --manifest-path native/Cargo.toml --all-features
+cargo clippy --manifest-path native/Cargo.toml --all-targets --all-features -- -D warnings
+cargo fmt --manifest-path native/Cargo.toml --all --check
```
-The CPU-only library produces `libmesh_avatar_ffi.a` and a platform shared library
-(`libmesh_avatar_ffi.dylib` on macOS) in `native/target/release/`. Include
-[`mesh_avatar.h`](include/mesh_avatar.h) in your host. The C example opens the
-sample, applies a pose, ticks it, reads geometry/uniforms/textures and checks
-invalid-input behavior. It does not create a window or capture audio.
+The dump first checks the embedded motion data, then writes numeric reference data
+to ignored `native/target/conformance/`. Generate it before running the tests;
+comparison tests report a skip when it is absent. Tests without a compatible GPU
+skip GPU readback checks. Core also compiles for WASM; this does not provide
+JavaScript bindings:
-Open a built folder/archive with `mesh_avatar_open_path`, or an in-memory archive
-with `mesh_avatar_open_bytes`. Inputs are copied or consumed during the call;
-the archive buffer can be released after opening. Handles are opaque `uint64_t`
-tokens, with zero invalid. They can move between threads; calls on the same
-handle are serialized internally. Always call `mesh_avatar_destroy` when finished.
-
-Frame and layer descriptors contain borrowed, read-only pointers. They remain
-valid until the next tick or destroy on that handle; setters leave the cached
-frame intact. Texture names and straight RGBA8 pixels remain valid until destroy.
-Do not free these pointers. Copy data if it must outlive a tick, and synchronize
-borrowed reads against tick/destroy on other threads. Check every `MaStatus`;
-`mesh_avatar_last_error` returns a thread-local message until the next API call
-on that thread. A contained Rust panic requires destroying and reopening that
-handle. The generated header documents pointer/count and ownership requirements.
+```sh
+rustup target add wasm32-unknown-unknown
+cargo check --manifest-path native/Cargo.toml -p mesh-avatar-core --target wasm32-unknown-unknown
+```
-Normal library builds do not need a header generator. To regenerate the checked-in
-header, install the pinned development tool into the ignored build directory:
+Normal library builds do not need cbindgen. For header maintenance, install the
+pinned tool into the ignored build directory, regenerate both headers, then check
+for drift:
```sh
cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
@@ -184,62 +283,23 @@ bash native/conformance/ffi-header.sh
bash native/conformance/ffi-header.sh --check
```
-CI installs that version, verifies both headers have no drift, builds both library
-types, and builds/runs the C examples. The C ABI remains experimental.
-
-### Optional headless rendering
-
-```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
-make -C native/examples/c run-render
-```
-
-Include [`mesh_avatar_render.h`](include/mesh_avatar_render.h) for this extension.
-It includes the CPU header and needs no macro; its functions are exported only
-when the library is built with `render`. Default builds depend only on core.
-On macOS, the C Makefile links the required Metal/system frameworks separately.
+CI checks WASM, formatting/lints/tests, both generated headers and both C examples. The C render example skips only when no compatible GPU adapter is available.
-Create a renderer with an avatar handle and `MaRenderOptions`: physical width/height,
-1 or 4 MSAA samples, contain/cover fit and explicit padding (available from
-`mesh_avatar_get_info`). Rendering reads the current cached frame without ticking
-and copies tightly packed, top-down RGBA8 into a caller-owned buffer of at least
-`width*height*4` bytes. Choose straight or premultiplied alpha. The synchronous
-readback does not retain the buffer or invalidate borrowed frame data. Resize
-keeps fit/padding/samples; resize the caller's buffer too. Invalid sizes/buffers
-return an error without changing the output buffer.
+### Pixel comparison
-Renderer calls may move between threads and are serialized per renderer and
-avatar. Renderers reference their avatar without owning it; destroy renderers
-before destroying the avatar. Rendering after avatar destruction returns
-`MA_INVALID_HANDLE`. Destroy/recreate objects affected by a contained panic.
-`MA_GPU_UNAVAILABLE` means no compatible adapter was found; other GPU errors use
-`MA_RENDER_ERROR`. The example/CI skip only the unavailable-adapter case.
-
-The example checks both alpha formats and resize, then writes
-`native/target/ffi-render.ppm` (straight RGBA composited over white, since PPM has
-no alpha). It does not open a window. CI also checks the core library for
-`wasm32-unknown-unknown`; JavaScript bindings are not included.
-
-## Checks and visual comparison
-
-Node.js 22.17 or newer and the repository's npm dependencies are needed only for
-comparison with the JavaScript runtime:
+This optional command launches headless Chromium and the offscreen renderer. It
+requires the npm dependencies, a Playwright Chromium installation and a compatible
+GPU; the script builds the debug renderer itself:
```sh
-node --experimental-strip-types native/conformance/dump.mjs
-cargo test --manifest-path native/Cargo.toml
-cargo clippy --manifest-path native/Cargo.toml --all-targets -- -D warnings
-cargo fmt --manifest-path native/Cargo.toml --all --check
+npx playwright install chromium
node native/conformance/compare-pixels.mjs
```
-The dump checks that the embedded motion data matches the JavaScript source.
-To intentionally update it, run
-`node --experimental-strip-types native/conformance/sync-motion-data.mjs`.
-Numeric comparison data, PNGs and reports go into ignored `native/target/`.
-Comparison tests print a skip message when their generated data is absent.
-The pixel comparison uses Playwright's installed Chromium; `--metal` selects its
-Metal backend on macOS, and `--dpr=2` checks equal physical sizes at HiDPI.
+PNG images and reports stay in ignored `native/target/pixel-comparison*/`.
+On macOS, `--metal` selects Chromium's Metal backend; `--dpr=2` compares equal
+physical sizes at HiDPI. To intentionally update the embedded motion definitions,
+run `node --experimental-strip-types native/conformance/sync-motion-data.mjs`.
## Limitations
diff --git a/native/README.zh.md b/native/README.zh.md
index 88f65f3..208fa72 100644
--- a/native/README.zh.md
+++ b/native/README.zh.md
@@ -2,22 +2,91 @@
[English](README.md) · [日本語](README.ja.md)
-> **实验性功能。** 原生运行时仍在开发中,尚未作为软件包发布。
+> **实验性功能。** 原生运行时仍在开发中,crate尚未发布到crates.io。
> API、操作方式和文件保存位置可能会在不另行通知的情况下变更。参考实现仍是 `packages/runtime` 中的 JavaScript 运行时。
Rust 运行时可以加载与 JavaScript 运行时相同的 `.mavatar` 文件和已构建的项目文件夹。
-其中包含一个透明的桌面虚拟形象程序和一个 PNG 渲染器。桌面端的主要目标平台是使用 Metal 的 macOS。
+其中包含透明的桌面虚拟形象程序、PNG渲染器和Rust/C嵌入API。桌面端的主要目标平台是使用 Metal 的 macOS。
## 准备工作
- Rust 1.88 或更高版本,以及 Cargo。
-- 在 macOS 上需要 Xcode Command Line Tools 和支持 Metal 的 GPU。
+- macOS需要Xcode Command Line Tools;渲染还需要支持Metal的GPU。
+- C示例需要 `cc` 和 `make`(已在macOS验证)。CPU数据API不需要GPU。
- 一个虚拟形象归档文件,或包含 `rig.json`、`built/layers.json` 和已构建 PNG 资源的项目。
仅有插画本身无法作为虚拟形象运行。
以下命令均在仓库根目录执行。默认虚拟形象为 `samples/miko-qipao`,需要先安装其图片。
该示例适用[素材使用条款](../samples/miko-qipao/MIKO_ASSET_TERMS.md)。
+## 嵌入应用
+
+### Rust crate
+
+将以下依赖添加到宿主应用的 `Cargo.toml`,而不是本仓库的根目录:
+
+```toml
+[dependencies]
+mesh-avatar-core = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-core" }
+mesh-avatar-wgpu = { git = "https://github.com/shinshin86/mesh-avatar-studio.git", package = "mesh-avatar-wgpu" }
+```
+
+这些crate尚未发布到crates.io。Git依赖使用仓库的默认分支。为使构建可重现,请提交应用的 `Cargo.lock`,或在两个依赖中用 `rev` 固定到同一提交。不同修订之间的API可能发生变化。
+
+`mesh-avatar-core` 在CPU上加载虚拟形象、应用控制并推进动画;已有渲染器时可省略 `mesh-avatar-wgpu`。
+`Avatar::tick` 返回拥有其数据的 `Frame`,包含按绘制顺序排列的图层(顶点坐标、UV、三角形索引、纹理名称和Alpha)以及整帧的面部uniform。`Avatar::textures` 提供解码后的非预乘Alpha RGBA8纹理。
+`mesh-avatar-wgpu::Renderer` 将帧绘制到宿主提供的wgpu纹理视图,也支持RGBA读回。Rust帧拥有其数据;下述指针有效期仅适用于C ABI。
+
+### C ABI
+
+从此仓库检出构建 `mesh-avatar-ffi`,会在 `native/target/release/` 生成 `libmesh_avatar_ffi.a` 和平台共享库(macOS上为 `libmesh_avatar_ffi.dylib`)。
+包含 [`mesh_avatar.h`](include/mesh_avatar.h)。默认构建仅依赖core,已有网格渲染器的宿主无需引入wgpu。
+
+每次 `mesh_avatar_tick` 都会缓存一帧。`mesh_avatar_get_frame` 提供按绘制顺序排列的图层(顶点坐标、UV、三角形索引及数量、Alpha和纹理ID)以及整帧的面部uniform。
+纹理API提供尺寸与解码后的非预乘Alpha RGBA8像素。宿主负责上传纹理和绘制网格;CPU数据API本身不绘制窗口或图像。
+
+使用 `mesh_avatar_open_path` 打开已构建的文件夹或归档,使用 `mesh_avatar_open_bytes` 打开内存中的归档。
+输入在调用期间读取或复制,打开成功后即可释放归档缓冲区。句柄是不透明的 `uint64_t` 标识符,0无效。
+句柄可在线程间传递;同一句柄的API调用在内部串行执行。使用完毕后调用 `mesh_avatar_destroy`。
+
+帧和图层描述符包含由库持有的只读指针,有效期到该句柄的下一次tick或销毁为止;仅修改设置不会改变缓存帧。
+纹理名称和非预乘Alpha的RGBA8像素在销毁句柄前保持有效。不要释放这些指针;如需跨tick保留数据,请自行复制。
+读取借用数据时,必须与其他线程上的tick或销毁操作同步,避免并发访问。
+检查每个 `MaStatus`,失败时读取 `mesh_avatar_last_error`;错误字符串在同一线程下一次API调用前有效。
+遇到被捕获的Rust panic时,应销毁并重新打开该句柄。生成的头文件也记录了指针、长度和所有权要求。
+
+#### 可选的无窗口渲染
+
+没有自有网格渲染器的宿主可启用 `render`,直接复制离屏渲染的像素。
+
+扩展使用 [`mesh_avatar_render.h`](include/mesh_avatar_render.h),它包含CPU头文件,无需定义宏。只有用 `render` 功能构建的库才导出这些函数。
+
+用虚拟形象句柄和 `MaRenderOptions` 创建渲染器,指定物理像素宽高、MSAA采样数(1或4)、contain/cover以及显式留白。可从 `mesh_avatar_get_info` 取得建议的留白值。
+渲染读取当前缓存帧,不推进动画,将紧密排列、从顶行开始的RGBA8复制到调用方提供的缓冲区。缓冲区至少需要 `宽*高*4` 字节,可选择非预乘或预乘Alpha。
+同步调用会等待GPU读回完成,不保留调用方缓冲区,也不使借用的帧指针失效。调整大小会保留fit、留白和采样数;调用方也应按新尺寸分配缓冲区。无效尺寸或缓冲区返回错误,不修改输出缓冲区。
+
+渲染器可以跨线程使用,同一渲染器及虚拟形象上的调用会被串行化。渲染器只引用虚拟形象,不拥有它;请先销毁渲染器,再销毁虚拟形象。虚拟形象销毁后渲染返回 `MA_INVALID_HANDLE`。捕获panic后,应销毁并重建受影响的对象。
+没有兼容GPU适配器时返回 `MA_GPU_UNAVAILABLE`;其他GPU错误返回 `MA_RENDER_ERROR`。示例和CI只在没有适配器时跳过渲染。
+
+### C 示例
+
+示例使用 `cc` 和 `make` 链接静态库,并打开 `samples/miko-qipao`。CPU与 `render` 构建写入相同的库路径,请在运行各示例前执行对应的构建。
+
+[数据示例](examples/c/main.c)会设置姿势、推进动画、打印网格及纹理统计,并检查无效输入的返回值:
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+[渲染示例](examples/c/render.c)检查两种Alpha格式、帧缓存保持不变以及尺寸调整,然后写入 `native/target/ffi-render.ppm`。
+PPM不支持Alpha,因此会将非预乘RGBA合成到白色背景上。两个示例都不会打开窗口或启用麦克风。macOS的Makefile会链接渲染所需的Metal等系统框架:
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
## 桌面程序
```sh
@@ -107,34 +176,34 @@ native/target/release/mesh-avatar-desktop /path/to/project
```sh
cargo run --release --manifest-path native/Cargo.toml -p mesh-avatar-wgpu \
- --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o avatar.png
+ --bin mesh-avatar-render -- samples/miko-qipao --size 512x640 -o native/target/avatar.png
```
通过 `--pose` 传入类似 `{"angleX":20,"mouthOpen":0.8}` 的 JSON 对象。
未指定的姿势参数使用默认值。`--seconds` 会在渲染前以每秒 60 步推进虚拟形象的时间。
`--help` 会列出视图边距、fit、表情和多重采样等选项。
-## 使用C ABI
+## 开发检查
+
+这里的shell命令同样在仓库根目录运行。与JavaScript运行时对比需要Node.js 22.17或更高版本及npm依赖。尚未安装时,请先执行 `npm ci`。
```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
-make -C native/examples/c run
+node --experimental-strip-types native/conformance/dump.mjs
+cargo test --manifest-path native/Cargo.toml --all-features
+cargo clippy --manifest-path native/Cargo.toml --all-targets --all-features -- -D warnings
+cargo fmt --manifest-path native/Cargo.toml --all --check
```
-CPU库会在 `native/target/release/` 中生成 `libmesh_avatar_ffi.a` 和平台共享库(macOS上为 `libmesh_avatar_ffi.dylib`)。
-宿主程序需包含 [`mesh_avatar.h`](include/mesh_avatar.h)。C示例会加载示例虚拟形象、设置姿势、推进动画,读取几何数据、uniform和纹理,并检查无效输入的返回值,不会创建窗口或启用麦克风。
-
-使用 `mesh_avatar_open_path` 打开已构建的文件夹或归档,使用 `mesh_avatar_open_bytes` 打开内存中的归档。
-输入在调用期间读取或复制,打开成功后即可释放归档缓冲区。句柄是不透明的 `uint64_t` 标识符,0无效。
-句柄可在线程间传递;同一句柄的API调用在内部串行执行。使用完毕后调用 `mesh_avatar_destroy`。
+dump首先检查嵌入的动作数据是否一致,然后将数值参考数据写入Git忽略的 `native/target/conformance/`。
+请在测试前生成数据;缺少数据时,对比测试会输出跳过提示。没有兼容GPU时,GPU读回测试也会跳过。
+core也可编译为WASM,但不包含JavaScript绑定:
-帧和图层描述符包含由库持有的只读指针,有效期到该句柄的下一次tick或销毁为止;仅修改设置不会改变缓存帧。
-纹理名称和未预乘Alpha的RGBA8像素在销毁句柄前保持有效。不要释放这些指针;如需跨tick保留数据,请自行复制。
-读取借用数据时,必须与其他线程上的tick或销毁操作同步,避免并发访问。
-检查每个 `MaStatus`,失败时读取 `mesh_avatar_last_error`;错误字符串在同一线程下一次API调用前有效。
-遇到被捕获的Rust panic时,应销毁并重新打开该句柄。生成的头文件也记录了指针、长度和所有权要求。
+```sh
+rustup target add wasm32-unknown-unknown
+cargo check --manifest-path native/Cargo.toml -p mesh-avatar-core --target wasm32-unknown-unknown
+```
-普通库构建不需要头文件生成器。更新头文件时,将固定版本的开发工具安装到Git忽略的构建目录:
+普通库构建不需要cbindgen。维护头文件时,将固定版本工具安装到Git忽略的构建目录,重新生成两个头文件,再检查差异:
```sh
cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
@@ -142,43 +211,19 @@ bash native/conformance/ffi-header.sh
bash native/conformance/ffi-header.sh --check
```
-CI使用相同版本检查两个头文件的差异,并构建库、编译和运行C示例。C ABI仍为实验性功能。
+CI检查WASM、格式/lint/测试、两个生成头文件和两个C示例。渲染示例仅在没有兼容GPU适配器时跳过。
-### 可选的无窗口渲染
+### 像素对比
-```sh
-cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
-make -C native/examples/c run-render
-```
-
-扩展使用 [`mesh_avatar_render.h`](include/mesh_avatar_render.h),它包含CPU头文件,无需定义宏。只有用 `render` 功能构建的库才导出这些函数。默认构建仅依赖core。macOS的C Makefile会链接Metal等所需的系统框架。
-
-用头像句柄和 `MaRenderOptions` 创建渲染器,指定物理像素宽高、MSAA采样数(1或4)、contain/cover以及显式留白。可从 `mesh_avatar_get_info` 取得建议的留白值。
-渲染读取当前缓存帧,不推进动画,将紧密排列、从顶行开始的RGBA8复制到调用方提供的缓冲区。缓冲区至少需要 `宽*高*4` 字节,可选择非预乘或预乘Alpha。
-同步调用会等待GPU读回完成,不保留调用方缓冲区,也不使借用的帧指针失效。调整大小会保留fit、留白和采样数;调用方也应按新尺寸分配缓冲区。无效尺寸或缓冲区返回错误,不修改输出缓冲区。
-
-渲染器可以跨线程使用,同一渲染器及头像上的调用会被串行化。渲染器只引用头像,不拥有它;请先销毁渲染器,再销毁头像。头像销毁后渲染返回 `MA_INVALID_HANDLE`。捕获panic后,应销毁并重建受影响的对象。
-没有兼容GPU适配器时返回 `MA_GPU_UNAVAILABLE`;其他GPU错误返回 `MA_RENDER_ERROR`。示例和CI只在没有适配器时跳过渲染。
-
-示例验证两种Alpha格式和尺寸调整,并写入 `native/target/ffi-render.ppm`。PPM不支持Alpha,因此会将非预乘RGBA合成到白色背景上。不会打开窗口。
-CI还检查core的 `wasm32-unknown-unknown` 构建,不包含JavaScript绑定。
-
-## 检查与画面对比
-
-只有在与 JavaScript 运行时对比时,才需要 Node.js 22.17 或更高版本以及仓库的 npm 依赖:
+此可选命令会启动无窗口Chromium和离屏渲染器。需要npm依赖、Playwright的Chromium及兼容GPU;脚本会自行构建debug渲染器:
```sh
-node --experimental-strip-types native/conformance/dump.mjs
-cargo test --manifest-path native/Cargo.toml
-cargo clippy --manifest-path native/Cargo.toml --all-targets -- -D warnings
-cargo fmt --manifest-path native/Cargo.toml --all --check
+npx playwright install chromium
node native/conformance/compare-pixels.mjs
```
-dump 会检查嵌入的动作数据是否与 JavaScript 源码一致。
-如需有意更新,请运行 `node --experimental-strip-types native/conformance/sync-motion-data.mjs`。
-数值对比数据、PNG 和报告会输出到被 git 忽略的 `native/target/`。缺少生成数据时,对比测试会输出跳过提示。
-像素对比使用 Playwright 安装的 Chromium;在 macOS 上,`--metal` 选择其 Metal 后端,`--dpr=2` 在 HiDPI 下以相同物理尺寸进行对比。
+PNG及报告保存在Git忽略的 `native/target/pixel-comparison*/`。macOS上可用 `--metal` 选择Chromium的Metal后端,用 `--dpr=2` 在HiDPI下按相同物理尺寸比较。
+如需有意更新嵌入的动作定义,请执行 `node --experimental-strip-types native/conformance/sync-motion-data.mjs`。
## 限制