Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Remember desktop avatar placement and add motion/expression menus
shinshin86f6759928c059
diff --git a/README.ja.md b/README.ja.mdindex 5d671db..ad01f5a 100644--- a/README.ja.md+++ b/README.ja.md@@ -110,6 +110,13 @@ npm run dev[Player](https://shinshin86.github.io/mesh-avatar-studio/ja/play/) では、顔の追従、マイクでの口パク、表情、ライティングをすべてブラウザ内で動かせます。サンプルか自分の `.mavatar` ファイルを開いて使い、ファイルはアップロードされません。OBS用URLはないため、「アバターウィンドウを開く」(Chrome か Edge)を押し、そのウィンドウを緑の背景にして OBS の「ウィンドウキャプチャ」で取り込み、クロマキーで抜いてください。透明な背景、OBS の「ブラウザ」ソース、他のアプリからの表情の切り替えを使うときは、Studio の配信画面を使います。+## 実験的なネイティブ版++Rust版のランタイム、PNGレンダラー、macOS向けの透明なデスクトップアバターを開発しています。+JavaScript版と同じ `.mavatar` ファイルとビルド済みプロジェクトフォルダを読み込めます。+ビルド方法と操作は[ネイティブ版のガイド](native/README.ja.md)を参照してください。+実験的な機能のため、APIや操作方法は変更されることがあります。+## リリース`mesh-avatar` を変更するときは `npm run changeset` を実行し、生成されたファイルをPRに含めてください。`main` に変更が入ると、GitHub Actionsが次のバージョンと変更履歴を含む `chore: version packages` PRを作成・更新します。そのPRをマージすると、`mesh-avatar` がprovenance付きでnpmに公開されます。Studioのルートパッケージは非公開のままです。公開にはnpmのtrusted publishingを使います。npmjs.comの `mesh-avatar` の設定で、このリポジトリと `release.yml` ワークフローをtrusted publisherとして登録してください。npmのトークンをリポジトリに保存する必要はありません。trusted publisherに一致しない公開は、メンテナーが2FAで承認するまでStaged Packagesタブで待機します。ワークフローがバージョン更新のPRを作成できるよう、リポジトリの Settings → Actions → General で **Allow GitHub Actions to create and approve pull requests** を有効にしてください。PRを作る前に、手元で `npm run e2e` を実行してください。CIはその他の検証を実行し、Playwrightのブラウザはインストールしません。diff --git a/README.md b/README.mdindex 0bdaa44..3cd23cd 100644--- a/README.md+++ b/README.md@@ -174,6 +174,13 @@ window** (Chrome or Edge) and add that window to OBS with **Window Capture** onbackground and a Chroma Key filter. Transparency, the OBS Browser Source and switchingexpressions from other apps need Studio's Live page.+## Experimental native runtime++A Rust runtime, PNG renderer and transparent macOS desktop avatar are available in+[the native guide](native/README.md). They load the same `.mavatar` files and built+project folders as the JavaScript runtime. The native version is experimental;+its APIs and controls may change.+## ReleasesFor changes to `mesh-avatar`, run `npm run changeset` and include the generated file in yourdiff --git a/README.zh.md b/README.zh.mdindex 881cf02..96bd0d2 100644--- a/README.zh.md+++ b/README.zh.md@@ -108,6 +108,12 @@ npm run dev[Player](https://shinshin86.github.io/mesh-avatar-studio/play/) 完全在浏览器内运行面部追踪、麦克风口型同步、表情和光照。打开示例或你自己的 `.mavatar` 文件即可,不会上传任何内容。它没有直播地址:选择**打开虚拟形象窗口**(Chrome 或 Edge),在 OBS 里用**窗口采集**配合绿色背景和色度键滤镜添加该窗口。透明背景、OBS 浏览器来源和从其他应用切换表情需要使用 Studio 的直播页面。+## 实验性原生运行时++仓库提供 Rust 运行时、PNG 渲染器和适用于 macOS 的透明桌面虚拟形象程序,+可加载与 JavaScript 运行时相同的 `.mavatar` 文件和已构建的项目文件夹。+构建方法和操作说明见[原生版指南](native/README.zh.md)。原生版仍为实验性功能,API 和操作方式可能变更。+## 发布要修改 `mesh-avatar`,运行 `npm run changeset` 并把生成的文件包含在你的 PR 里。在 `main` 分支上,GitHub Actions 会打开或更新一个 `chore: version packages` PR,其中包含下一个版本号和更新日志;合并后会把 `mesh-avatar` 发布到 npm 并附带 provenance。Studio 根包保持私有。发布使用 npm 的 trusted publishing:在 npmjs.com 上为 `mesh-avatar` 添加一个 trusted publisher,指定本仓库和 `release.yml` 工作流,无需在仓库中保存 npm token。npm 无法匹配到 trusted publisher 的发布会停在 Staged Packages 标签页,等待维护者用 2FA 审批。在仓库 Settings → Actions → General 中,启用 **Allow GitHub Actions to create and approve pull requests**,工作流才能打开版本 PR。提交 PR 前请先本地运行 `npm run e2e`;CI 会运行其他检查,但不安装 Playwright 浏览器。diff --git a/native/Cargo.lock b/native/Cargo.lockindex b7f041b..f5f0e3e 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -971,8 +971,12 @@ dependencies = ["mesh-avatar-core","mesh-avatar-wgpu","muda",+ "objc2 0.6.5",+ "objc2-app-kit 0.3.2",+ "objc2-foundation 0.3.2","pollster","rfd",+ "serde","serde_json","wgpu","winit",diff --git a/native/README.ja.md b/native/README.ja.mdindex 69d3278..43bd109 100644--- a/native/README.ja.md+++ b/native/README.ja.md@@ -43,12 +43,20 @@ macOS では、ウィンドウは透明・枠なし・通常のウィンドウmacOS では、**File → Open Avatar…** で標準のダイアログが開き、`.mavatar` アーカイブか、`rig.json` と `built/` を含むプロジェクトフォルダを選べます。どちらもアバターのウィンドウにドロップして開くこともできます。読み込みはバックグラウンドで行い、読み込めないアバターを選んだ場合は今のアバターを表示したままエラーを出します。-切り替えに成功すると、GPU リソースと表示領域を作り直します。拡大率は新しいサイズの上限の範囲で保ち、ウィンドウ左上の位置とクリック透過の状態も維持します。新しいモーションの一覧はターミナルに表示されます。+切り替えに成功すると、GPU リソースと表示領域を作り直し、保存した位置と拡大率を新しいサイズの上限の範囲で復元します。クリック透過の状態は維持し、新しいモーションの一覧はターミナルに表示されます。**File → Open Recent** には、正常に開けたパスが最新 8 件まで残ります。保存先は OS のユーザー設定ディレクトリ(macOS では `~/Library/Application Support/`)の `mesh-avatar-desktop/recent.json` です。存在しなくなったパスは、起動時とアプリが再びフォーカスされたときに一覧から外れます。**File → Reload** は、編集後に今のアバターを読み込み直します。新しいアバターを読み込むと、表情とアニメーションの状態はリセットされます。+ウィンドウ左上の位置(論理座標)と拡大率は、同じ設定ディレクトリの `mesh-avatar-desktop/settings.json` にアバターのパスごとに保存します。+起動時とアバターの切り替え時に復元し、そのアバターの設定がなければ最後に使ったウィンドウの位置と拡大率を使います。+保存先のモニターが外れている場合も、接続中のモニター内に収まるように補正します。macOSではDockとメニューバーを除く範囲に収めます。+移動や拡大縮小が止まってから0.5秒後と、通常の終了時に保存します。設定ファイルがない場合や壊れている場合は、既定の位置から始めます。++macOSでは **Avatar → Motion** からすべてのモーションを名前で選べます。**Avatar → Expression** ではライブ表情を選べます。+アバターを切り替えるとメニューも更新されます。下記のキーボード操作も引き続き使えます。+| 操作 | 動作 ||---|---|| Command + `O` | アバターのアーカイブかビルド済みプロジェクトフォルダを開く(macOS) |@@ -106,5 +114,4 @@ dump は、Rust 側に埋め込んだモーションデータが JavaScript のmacOS がほかの場所で表示する名前は、起動のしかたによって変わることがあります。- デスクトップでの入力は上の操作に限られます。カメラトラッキング、マイク入力、音声再生、ライティングには対応していません。- デスクトップ版は Cargo でビルドする実行ファイルで、インストーラー、署名済みアプリバンドル、グローバルショートカットはありません。- ウィンドウの位置と拡大率は起動のたびにリセットされます。- GPU のラスタライズとアンチエイリアスは Chromium とわずかに異なることがあります。ほぼ透明な画像の縁を調べるときは、プリマルチプライド済みの色で比較してください。diff --git a/native/README.md b/native/README.mdindex 4803e65..fe0ea7b 100644--- a/native/README.md+++ b/native/README.md@@ -52,8 +52,8 @@ On macOS, **File → Open Avatar…** opens a native dialog for either a `.mavatarchive or a project folder containing `rig.json` and `built/`. You can also dropeither onto the avatar window. Loading runs in the background; an invalid avatarleaves the current one displayed and shows an error. A successful switch rebuilds-its GPU resources and viewport, keeps the current zoom within the new size limits,-preserves the window's top-left position and click-through state, and prints the+its GPU resources and viewport, restores the saved placement within the new size limits,+preserves the click-through state, and prints thenew motion list in the terminal.**File → Open Recent** keeps the last eight successfully opened paths. They are@@ -62,6 +62,18 @@ directory (`~/Library/Application Support/` on macOS). Missing paths are removedat startup and when the app regains focus. **File → Reload** reopens the currentavatar after edits. Loading a new avatar resets expressions and animation state.+Window position (the outer top-left in logical coordinates) and zoom are saved+per avatar path in `mesh-avatar-desktop/settings.json` in the same configuration+directory. On launch and avatar switches, the app restores that avatar's settings,+or uses the last window placement if that avatar has no saved settings. Restored+windows are fitted to a connected monitor; on macOS this excludes the Dock and+menu bar. Changes are saved after 0.5 seconds without further movement or scaling,+and on normal quit. Missing or corrupt settings use the default placement.++On macOS, **Avatar → Motion** lists every motion by label, and+**Avatar → Expression** selects a live expression. These menus are rebuilt when+switching avatars; the keyboard controls below continue to work.+| Control | Action ||---|---|| Command + `O` | Open an avatar archive or built project folder on macOS |@@ -131,6 +143,6 @@ Metal backend on macOS, and `--dpr=2` checks equal physical sizes at HiDPI.- Desktop input is limited to the controls above. Camera tracking, microphoneinput, audio playback and lighting are not included.- The desktop is a Cargo-built executable, without an installer, signed app- bundle or global keyboard shortcuts. Window position and scale reset on launch.+ bundle or global keyboard shortcuts.- GPU rasterization and antialiasing can differ slightly from Chromium. Comparepremultiplied colors when inspecting nearly transparent image edges.diff --git a/native/README.zh.md b/native/README.zh.mdindex fd52d08..ed38f43 100644--- a/native/README.zh.md+++ b/native/README.zh.md@@ -43,12 +43,20 @@ native/target/release/mesh-avatar-desktop /path/to/project在 macOS 上,**File → Open Avatar…** 会打开系统对话框,可选择 `.mavatar` 归档文件,或包含 `rig.json` 和 `built/` 的项目文件夹。也可以把它们直接拖放到虚拟形象窗口上。加载在后台进行;如果虚拟形象无效,会继续显示当前虚拟形象并提示错误。-切换成功后,程序会重建 GPU 资源和视图,在新尺寸限制内保留当前缩放比例,保持窗口左上角位置和点击穿透状态,并在终端输出新的动作列表。+切换成功后,程序会重建 GPU 资源和视图,在新尺寸限制内恢复保存的位置和缩放比例,保持点击穿透状态,并在终端输出新的动作列表。**File → Open Recent** 会保留最近 8 个成功打开的路径,保存在操作系统用户配置目录(macOS 上为 `~/Library/Application Support/`)下的 `mesh-avatar-desktop/recent.json`。已不存在的路径会在启动时以及程序重新获得焦点时被移除。**File → Reload** 用于在编辑后重新加载当前虚拟形象。加载新的虚拟形象时,表情和动画状态会被重置。+窗口左上角位置(逻辑坐标)和缩放比例会按虚拟形象路径保存在同一配置目录的 `mesh-avatar-desktop/settings.json` 中。+启动和切换虚拟形象时会恢复对应设置;如果该虚拟形象尚无设置,则使用最近的窗口位置和缩放比例。+恢复时会将窗口限制在当前连接的显示器内,即使原来的显示器已经断开;在 macOS 上会避开 Dock 和菜单栏。+移动或缩放停止0.5秒后,以及正常退出时会保存设置。设置文件缺失或损坏时使用默认位置。++在 macOS 上,**Avatar → Motion** 按名称列出所有动作,**Avatar → Expression** 用于选择实时表情。+切换虚拟形象后会重建这些菜单;以下键盘操作仍然有效。+| 操作 | 作用 ||---|---|| Command + `O` | 打开虚拟形象归档文件或已构建的项目文件夹(macOS) |@@ -106,5 +114,4 @@ dump 会检查嵌入的动作数据是否与 JavaScript 源码一致。macOS 在其他位置显示的名称可能取决于启动方式。- 桌面端的输入仅限上述操作。不包含摄像头追踪、麦克风输入、音频播放和光照。- 桌面程序是用 Cargo 构建的可执行文件,没有安装程序、已签名的应用包或全局快捷键。- 每次启动时窗口位置和缩放比例都会重置。- GPU 光栅化和抗锯齿可能与 Chromium 略有差异。检查接近透明的图像边缘时,请比较预乘后的颜色。diff --git a/native/apps/mesh-avatar-desktop/Cargo.toml b/native/apps/mesh-avatar-desktop/Cargo.tomlindex de7cc72..b666bb1 100644--- a/native/apps/mesh-avatar-desktop/Cargo.toml+++ b/native/apps/mesh-avatar-desktop/Cargo.toml@@ -13,8 +13,12 @@ wgpu.workspace = truepollster.workspace = trueanyhow.workspace = trueserde_json.workspace = true+serde.workspace = truedirs = "6"[target.'cfg(target_os = "macos")'.dependencies]muda = { version = "0.19.3", default-features = false }rfd = { version = "0.17", default-features = false }+objc2 = "0.6"+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSScreen"] }+objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] }diff --git a/native/apps/mesh-avatar-desktop/src/main.rs b/native/apps/mesh-avatar-desktop/src/main.rsindex 8ce3d38..0ef1d74 100644--- a/native/apps/mesh-avatar-desktop/src/main.rs+++ b/native/apps/mesh-avatar-desktop/src/main.rs@@ -1,11 +1,15 @@mod geometry;mod loading;mod menu;+mod menu_model;mod presentation;mod scaling;+mod screens;+mod settings;use anyhow::{bail, ensure, Context, Result};use geometry::{fit_base, switch_layout};use loading::{Loaded, Loader, Recent};+use menu_model::AvatarMenu;use mesh_avatar_core::{engine::{expression::OVERLAY_EXPRESSIONS, motion::SpeakOptions},format::AvatarPackage,@@ -14,6 +18,7 @@ use mesh_avatar_core::{use mesh_avatar_wgpu::{Fit, Renderer, ViewOptions};use presentation::StraightAlpha;use scaling::{render_size, ScaleBounds, Scaling};+use settings::{Placement, Settings};use std::{env,panic::{catch_unwind, AssertUnwindSafe},@@ -26,7 +31,7 @@ use std::{};use winit::{application::ApplicationHandler,- dpi::{PhysicalPosition, PhysicalSize},+ dpi::{LogicalPosition, PhysicalPosition, PhysicalSize, Position},event::{ElementState, MouseButton, WindowEvent},event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy},keyboard::{KeyCode, ModifiersState, PhysicalKey},@@ -146,7 +151,7 @@ struct Scene {top_edge: TopEdgeGuard,last_frame: Instant,scaling: Scaling,- pending_position: Option<PhysicalPosition<i32>>,+ pending_position: Option<Position>,pending_surface_size: Option<PhysicalSize<u32>>,redraw_requested: bool,gpu_failed: Arc<AtomicBool>,@@ -271,9 +276,6 @@ impl Scene {);eprintln!("Drag to move · scroll or Cmd +/- to scale · E expression · K kana · C click-through · Esc quit");print_motions(&avatar);- window.set_visible(true);- window.focus_window();- window.request_redraw();Ok(Self {surface,window,@@ -368,24 +370,21 @@ impl Scene {self.view = view;self.top_edge = top_edge;self.scaling = layout.scaling;- self.pending_position = Some(layout.position);+ self.pending_position = Some(layout.position.into());self.expression_index = 0;self.last_frame = Instant::now();self.redraw_requested = true;print_motions(&self.avatar);Ok(())}- /// Run native resize and GPU work after input/drawRect callbacks return.- fn service(&mut self) -> Result<()> {- ensure!(- !self.gpu_failed.load(Ordering::Relaxed),- "graphics device reported an error"- );+ fn apply_window_changes(&mut self) {if let Some(desired) = self.scaling.take_request() {- if desired != self.window.inner_size() {+ if desired != self.window.inner_size() || self.pending_position.is_some() {// macOS returns None and queues Resized. Synchronous platforms may return// the accepted size without sending a notification; treat it identically.- if let Some(accepted) = self.window.request_inner_size(desired) {+ // Logical sizes remain correct when a restore also crosses pixel ratios.+ if let Some(accepted) = self.window.request_inner_size(self.scaling.logical_size())+ {self.pending_surface_size = Some(accepted);}}@@ -393,6 +392,14 @@ impl Scene {if let Some(position) = self.pending_position.take() {self.window.set_outer_position(position);}+ }+ /// Run native resize and GPU work after input/drawRect callbacks return.+ fn service(&mut self) -> Result<()> {+ ensure!(+ !self.gpu_failed.load(Ordering::Relaxed),+ "graphics device reported an error"+ );+ self.apply_window_changes();if let Some(size) = self.pending_surface_size.take() {// Several notifications can be queued during a trackpad input burst.if size == self.window.inner_size() {@@ -479,10 +486,8 @@ impl Scene {}_ if repeat => {}KeyCode::KeyE => {- self.expression_index = (self.expression_index + 1) % OVERLAY_EXPRESSIONS.len();- let name = OVERLAY_EXPRESSIONS[self.expression_index].0;- self.avatar.set_expression(name);- eprintln!("Expression: {name}");+ let next = (self.expression_index + 1) % OVERLAY_EXPRESSIONS.len();+ self.select_expression(OVERLAY_EXPRESSIONS[next].0);}KeyCode::KeyK => self.avatar.speak_kana("こんにちは。きょうも、いっしょにあいうえおをれんしゅうしましょう。",@@ -522,6 +527,36 @@ impl Scene {_ => {}}}+ fn select_expression(&mut self, name: &str) {+ if let Some(index) = OVERLAY_EXPRESSIONS.iter().position(|(n, _)| *n == name) {+ self.expression_index = index;+ self.avatar.set_expression(name);+ eprintln!("Expression: {name}");+ }+ }+ fn placement(&self, include_pending: bool) -> Option<Placement> {+ if !include_pending+ && (self.scaling.has_request()+ || self.pending_position.is_some()+ || self.pending_surface_size.is_some()+ || self.window.inner_size()+ != PhysicalSize::new(self.config.width, self.config.height))+ {+ return None;+ }+ let position = match self.pending_position {+ Some(position) => position.to_logical::<f64>(self.window.scale_factor()),+ None => self+ .window+ .outer_position()+ .ok()?+ .to_logical::<f64>(self.window.scale_factor()),+ };+ Some(Placement {+ position: [position.x, position.y],+ zoom: self.scaling.zoom(),+ })+ }}enum UserEvent {@@ -542,8 +577,45 @@ struct App {menu: Option<menu::AppMenu>,commands: Vec<menu::Command>,dialog_open: bool,+ settings: Settings,}impl App {+ fn observe_settings(&mut self, now: Instant, include_pending: bool) {+ if let Some(placement) = self+ .scene+ .as_ref()+ .and_then(|scene| scene.placement(include_pending))+ {+ self.settings.record(&self.current_path, placement, now);+ }+ }+ fn restore_settings(&mut self, event_loop: &ActiveEventLoop) {+ if let Some(scene) = &mut self.scene {+ let placement = self+ .settings+ .placement(&self.current_path)+ .or_else(|| scene.placement(false));+ if let Some(restored) = placement.and_then(|placement| {+ settings::restore(+ &scene.view,+ placement,+ &screens::visible_areas(event_loop),+ scene.device.limits().max_texture_dimension_2d,+ )+ }) {+ scene.scaling = restored.scaling;+ scene.pending_position =+ Some(LogicalPosition::new(restored.position[0], restored.position[1]).into());+ }+ }+ }+ fn refresh_avatar_menu(&mut self) {+ if let (Some(menu), Some(scene)) = (&mut self.menu, &self.scene) {+ if let Err(error) = menu.set_avatar(AvatarMenu::new(scene.avatar.motions())) {+ eprintln!("Could not update avatar menu: {error:#}");+ }+ }+ }fn refresh_recent(&mut self) {if self.recent.prune() {if let Err(error) = self.recent.save() {@@ -573,6 +645,7 @@ impl App {}}fn service(&mut self, event_loop: &ActiveEventLoop) -> Result<()> {+ self.observe_settings(Instant::now(), false);for command in std::mem::take(&mut self.commands) {match command {menu::Command::Quit => {@@ -597,6 +670,16 @@ impl App {self.request_load(path);}menu::Command::Reload => self.request_load(self.current_path.clone()),+ menu::Command::Play(id) => {+ if let Some(scene) = &mut self.scene {+ scene.avatar.play(&id);+ }+ }+ menu::Command::Expression(name) => {+ if let Some(scene) = &mut self.scene {+ scene.select_expression(&name);+ }+ }_ => {}}}@@ -619,6 +702,8 @@ impl App {}) {Ok(()) => {self.current_path = loaded.path;+ self.restore_settings(event_loop);+ self.refresh_avatar_menu();if let Err(error) = self.recent.record(&self.current_path) {eprintln!("Could not save recent avatars: {error:#}");}@@ -630,6 +715,11 @@ impl App {if let Some(scene) = &mut self.scene {scene.service()?;}+ let now = Instant::now();+ self.observe_settings(now, false);+ if let Err(error) = self.settings.flush(now, false) {+ eprintln!("Could not save window settings: {error:#}");+ }Ok(())}}@@ -645,6 +735,7 @@ impl ApplicationHandler<UserEvent> for App {match pollster::block_on(Scene::new(event_loop, avatar)) {Ok(scene) => {self.scene = Some(scene);+ self.restore_settings(event_loop);if let Err(error) = self.recent.record(&self.current_path) {eprintln!("Could not save recent avatars: {error:#}");}@@ -652,6 +743,14 @@ impl ApplicationHandler<UserEvent> for App {Ok(menu) => self.menu = Some(menu),Err(error) => eprintln!("Could not install avatar menu: {error:#}"),}+ self.refresh_avatar_menu();+ if let Some(scene) = &mut self.scene {+ // Apply the restored layout while hidden to avoid a startup position flash.+ scene.apply_window_changes();+ scene.window.set_visible(true);+ scene.window.focus_window();+ scene.window.request_redraw();+ }}Err(error) => {self.error = Some(error);@@ -749,6 +848,13 @@ impl ApplicationHandler<UserEvent> for App {}}}+ fn exiting(&mut self, _: &ActiveEventLoop) {+ let now = Instant::now();+ self.observe_settings(now, true);+ if let Err(error) = self.settings.flush(now, true) {+ eprintln!("Could not save window settings on exit: {error:#}");+ }+ }}fn run() -> Result<()> {let mut args = env::args_os().skip(1);@@ -794,6 +900,7 @@ fn run() -> Result<()> {menu: None,commands: Vec::new(),dialog_open: false,+ settings: Settings::load(Settings::config_file()),};event_loop.run_app(&mut app)?;if let Some(error) = app.error {diff --git a/native/apps/mesh-avatar-desktop/src/menu.rs b/native/apps/mesh-avatar-desktop/src/menu.rsindex 950e1ab..4b5865e 100644--- a/native/apps/mesh-avatar-desktop/src/menu.rs+++ b/native/apps/mesh-avatar-desktop/src/menu.rs@@ -1,4 +1,5 @@//! Native macOS menus and dialogs. All AppKit entry points stay on the main thread.+use crate::menu_model::AvatarMenu;use crate::UserEvent;use anyhow::Result;use std::path::{Path, PathBuf};@@ -9,6 +10,8 @@ pub enum Command {Recent(PathBuf),Reload,Quit,+ Play(String),+ Expression(String),}#[cfg(target_os = "macos")]@@ -29,6 +32,9 @@ mod platform {_root: Menu,recent: Submenu,entries: Vec<(MenuItem, PathBuf)>,+ motions: Submenu,+ expressions: Submenu,+ avatar_model: AvatarMenu,}impl AppMenu {pub fn install(proxy: EventLoopProxy<UserEvent>, paths: &[PathBuf]) -> Result<Self> {@@ -75,11 +81,17 @@ mod platform {&PredefinedMenuItem::select_all(None),],)?;- root.append_items(&[&app, &file, &edit])?;+ let motions = Submenu::new("Motion", true);+ let expressions = Submenu::new("Expression", true);+ let avatar = Submenu::with_items("Avatar", true, &[&motions, &expressions])?;+ root.append_items(&[&app, &file, &avatar, &edit])?;let mut menu = Self {_root: root,recent,entries: Vec::new(),+ motions,+ expressions,+ avatar_model: AvatarMenu::new(&[]),};menu.set_recent(paths)?;MenuEvent::set_event_handler(Some(move |event: MenuEvent| {@@ -116,9 +128,31 @@ mod platform {.entries.iter().find(|(item, _)| item.id().as_ref() == id)- .map(|(_, path)| Command::Recent(path.clone())),+ .map(|(_, path)| Command::Recent(path.clone()))+ .or_else(|| self.avatar_model.command(id)),}}+ pub fn set_avatar(&mut self, model: AvatarMenu) -> Result<()> {+ for (submenu, entries) in [+ (&self.motions, &model.motions),+ (&self.expressions, &model.expressions),+ ] {+ while submenu.remove_at(0).is_some() {}+ for entry in entries {+ submenu.append(&MenuItem::with_id(+ entry.id.clone(),+ entry.label.replace('&', "&&"),+ true,+ None,+ ))?;+ }+ if entries.is_empty() {+ submenu.append(&MenuItem::new("No Motions", false, None))?;+ }+ }+ self.avatar_model = model;+ Ok(())+ }}pub fn open(@@ -175,6 +209,9 @@ mod platform {pub fn command(&self, _: &str) -> Option<Command> {None}+ pub fn set_avatar(&mut self, _: AvatarMenu) -> Result<()> {+ Ok(())+ }}pub fn open(_: EventLoopProxy<UserEvent>, _: &Window, _: Option<&Path>) -> Result<()> {anyhow::bail!("the native Open Avatar dialog is currently available only on macOS")diff --git a/native/apps/mesh-avatar-desktop/src/menu_model.rs b/native/apps/mesh-avatar-desktop/src/menu_model.rsnew file mode 100644index 0000000..3e8c648--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/menu_model.rs@@ -0,0 +1,87 @@+//! Menu contents and command routing independent of AppKit.+use crate::menu::Command;+use mesh_avatar_core::engine::{expression::OVERLAY_EXPRESSIONS, motions::MotionDefinition};++pub struct Entry {+ pub id: String,+ pub label: String,+}+pub struct AvatarMenu {+ pub motions: Vec<Entry>,+ pub expressions: Vec<Entry>,+}+impl AvatarMenu {+ pub fn new(motions: &[MotionDefinition]) -> Self {+ Self {+ motions: motions+ .iter()+ .map(|m| Entry {+ id: format!("motion:{}", m.id),+ label: m.label.clone(),+ })+ .collect(),+ expressions: OVERLAY_EXPRESSIONS+ .iter()+ .map(|(name, _)| Entry {+ id: format!("expression:{name}"),+ label: match *name {+ "neutral" => "Neutral",+ "smile" => "Smile",+ "shy" => "Shy",+ "surprise" => "Surprise",+ "halfLidded" => "Half-lidded",+ "angry" => "Angry",+ "sad" => "Sad",+ "wink" => "Wink",+ _ => name,+ }+ .to_string(),+ })+ .collect(),+ }+ }+ pub fn command(&self, id: &str) -> Option<Command> {+ if self.motions.iter().any(|e| e.id == id) {+ return id+ .strip_prefix("motion:")+ .map(|id| Command::Play(id.to_string()));+ }+ if self.expressions.iter().any(|e| e.id == id) {+ return id+ .strip_prefix("expression:")+ .map(|id| Command::Expression(id.to_string()));+ }+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn every_motion_label_and_live_expression_is_routed_and_rebuild_discards_old_ids() {+ let motions: Vec<_> = (0..15)+ .map(|i| MotionDefinition {+ id: format!("m{i}"),+ label: format!("Motion {i} & more"),+ dur: 1.0,+ idle: false,+ tracks: vec![],+ })+ .collect();+ let menu = AvatarMenu::new(&motions);+ assert_eq!(menu.motions.len(), 15);+ assert_eq!(menu.motions[14].label, "Motion 14 & more");+ assert!(matches!(menu.command("motion:m14"),Some(Command::Play(id)) if id == "m14"));+ assert_eq!(menu.expressions.len(), OVERLAY_EXPRESSIONS.len());+ for (name, _) in OVERLAY_EXPRESSIONS {+ assert!(+ matches!(menu.command(&format!("expression:{name}")),Some(Command::Expression(id)) if &id == name)+ );+ }+ assert!(menu.command("expression:unknown").is_none());+ let rebuilt = AvatarMenu::new(&[]);+ assert!(rebuilt.command("motion:m14").is_none());+ assert_eq!(rebuilt.expressions.len(), OVERLAY_EXPRESSIONS.len());+ }+}diff --git a/native/apps/mesh-avatar-desktop/src/scaling.rs b/native/apps/mesh-avatar-desktop/src/scaling.rsindex 349fcdb..584e696 100644--- a/native/apps/mesh-avatar-desktop/src/scaling.rs+++ b/native/apps/mesh-avatar-desktop/src/scaling.rs@@ -57,6 +57,24 @@ impl Scaling {self.change(0.0, bounds);}+ pub fn zoom(&self) -> f64 {+ self.zoom+ }+ pub fn logical_size(&self) -> LogicalSize<f64> {+ LogicalSize::new(self.base.width * self.zoom, self.base.height * self.zoom)+ }+ pub fn has_request(&self) -> bool {+ self.pending.is_some()+ }+ pub fn from_zoom(base: LogicalSize<f64>, zoom: f64, bounds: ScaleBounds) -> Result<Self> {+ ensure!(zoom.is_finite() && zoom > 0.0, "invalid saved zoom");+ let mut scaling = Self::new(base)?;+ scaling.zoom = zoom;+ scaling.refresh(bounds);+ ensure!(scaling.pending.is_some(), "invalid monitor bounds");+ Ok(scaling)+ }+/// Prepare a different avatar's aspect without changing the live scaling state.pub fn rebase(&self, base: LogicalSize<f64>, bounds: ScaleBounds) -> Result<Self> {let mut replacement = Self::new(base)?;diff --git a/native/apps/mesh-avatar-desktop/src/screens.rs b/native/apps/mesh-avatar-desktop/src/screens.rsnew file mode 100644index 0000000..eb08acc--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/screens.rs@@ -0,0 +1,49 @@+//! Safe logical work areas; no native objects escape this module.+use crate::settings::Area;+use winit::event_loop::ActiveEventLoop;++pub fn visible_areas(event_loop: &ActiveEventLoop) -> Vec<Area> {+ #[cfg(target_os = "macos")]+ if let Some(areas) = macos_areas() {+ return areas;+ }+ event_loop+ .available_monitors()+ .filter_map(|monitor| {+ let dpi = monitor.scale_factor();+ let position = monitor.position().to_logical::<f64>(dpi);+ let size = monitor.size().to_logical::<f64>(dpi);+ let area = Area {+ position: [position.x, position.y],+ size: [size.width, size.height],+ dpi,+ };+ area.valid().then_some(area)+ })+ .collect()+}++#[cfg(target_os = "macos")]+fn macos_areas() -> Option<Vec<Area>> {+ use objc2::MainThreadMarker;+ use objc2_app_kit::NSScreen;+ let screens = NSScreen::screens(MainThreadMarker::new()?);+ // Cocoa's first screen defines the origin used by winit's screen coordinates.+ let primary_height = screens.firstObject()?.frame().size.height;+ let areas: Vec<_> = screens+ .iter()+ .filter_map(|screen| {+ let frame = screen.visibleFrame();+ let area = Area {+ position: [+ frame.origin.x,+ primary_height - frame.origin.y - frame.size.height,+ ],+ size: [frame.size.width, frame.size.height],+ dpi: screen.backingScaleFactor(),+ };+ area.valid().then_some(area)+ })+ .collect();+ (!areas.is_empty()).then_some(areas)+}diff --git a/native/apps/mesh-avatar-desktop/src/settings.rs b/native/apps/mesh-avatar-desktop/src/settings.rsnew file mode 100644index 0000000..6b8176b--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/settings.rs@@ -0,0 +1,355 @@+//! Logical window placement, monitor clamping and debounced atomic persistence.+use crate::{+ geometry::fit_base,+ scaling::{ScaleBounds, Scaling},+};+use anyhow::Result;+use mesh_avatar_wgpu::ViewOptions;+use serde::{Deserialize, Serialize};+use std::{+ collections::BTreeMap,+ fs,+ io::Read,+ path::{Path, PathBuf},+ time::{Duration, Instant},+};+use winit::dpi::LogicalSize;++const SAVE_DELAY: Duration = Duration::from_millis(500);+#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)]+pub struct Placement {+ pub position: [f64; 2],+ pub zoom: f64,+}+impl Placement {+ fn valid(&self) -> bool {+ self.position.iter().all(|n| n.is_finite()) && self.zoom.is_finite() && self.zoom > 0.0+ }+}+#[derive(Clone, Copy, Debug)]+pub struct Area {+ pub position: [f64; 2],+ pub size: [f64; 2],+ pub dpi: f64,+}+impl Area {+ pub fn valid(&self) -> bool {+ self.position.iter().all(|n| n.is_finite())+ && self.size.iter().all(|n| n.is_finite() && *n > 0.0)+ && self.dpi.is_finite()+ && self.dpi > 0.0+ }+}+pub struct Restored {+ pub position: [f64; 2],+ pub scaling: Scaling,+}+pub fn restore(+ view: &ViewOptions,+ placement: Placement,+ areas: &[Area],+ limit: u32,+) -> Option<Restored> {+ if !placement.valid() {+ return None;+ }+ let distance = |area: &Area| {+ let delta: [f64; 2] = std::array::from_fn(|i| {+ placement.position[i]+ - placement.position[i].clamp(area.position[i], area.position[i] + area.size[i])+ });+ delta[0].hypot(delta[1])+ };+ let area = areas+ .iter()+ .filter(|area| area.valid())+ .min_by(|a, b| distance(a).total_cmp(&distance(b)))?;+ let screen = LogicalSize::new(area.size[0], area.size[1]);+ let base = fit_base(view, Some(screen)).ok()?;+ let mut scaling = Scaling::from_zoom(+ base,+ placement.zoom,+ ScaleBounds {+ dpi: area.dpi,+ screen: Some(screen),+ texture_limit: limit,+ },+ )+ .ok()?;+ // Match the rounded physical size that will actually be requested from the OS.+ let size = scaling.clone().take_request()?;+ let dimensions = [+ f64::from(size.width) / area.dpi,+ f64::from(size.height) / area.dpi,+ ];+ let position = std::array::from_fn(|i| {+ placement.position[i].clamp(+ area.position[i],+ area.position[i] + (area.size[i] - dimensions[i]).max(0.0),+ )+ });+ // Keep the request queued for the normal resize path.+ scaling.refresh(ScaleBounds {+ dpi: area.dpi,+ screen: Some(screen),+ texture_limit: limit,+ });+ Some(Restored { position, scaling })+}++#[derive(Default, Deserialize, Serialize)]+#[serde(default)]+struct Data {+ global: Option<Placement>,+ avatars: BTreeMap<PathBuf, Placement>,+}+pub struct Settings {+ file: Option<PathBuf>,+ data: Data,+ dirty_at: Option<Instant>,+}+impl Settings {+ pub fn config_file() -> Option<PathBuf> {+ dirs::config_dir().map(|dir| dir.join("mesh-avatar-desktop/settings.json"))+ }+ pub fn load(file: Option<PathBuf>) -> Self {+ let read = |file: &Path| -> Result<Data> {+ let mut bytes = Vec::new();+ fs::File::open(file)?+ .take(1024 * 1024 + 1)+ .read_to_end(&mut bytes)?;+ anyhow::ensure!(bytes.len() <= 1024 * 1024, "window settings are too large");+ Ok(serde_json::from_slice(&bytes)?)+ };+ let mut data = file+ .as_ref()+ .filter(|p| p.exists())+ .and_then(|file| match read(file) {+ Ok(data) => Some(data),+ Err(error) => {+ eprintln!("Ignoring invalid window settings: {error:#}");+ None+ }+ })+ .unwrap_or_default();+ data.global = data.global.filter(Placement::valid);+ data.avatars.retain(|_, p| p.valid());+ Self {+ file,+ data,+ dirty_at: None,+ }+ }+ pub fn placement(&self, path: &Path) -> Option<Placement> {+ self.data.avatars.get(path).copied().or(self.data.global)+ }+ pub fn record(&mut self, path: &Path, placement: Placement, now: Instant) {+ if !placement.valid() {+ return;+ }+ if self.data.avatars.get(path) == Some(&placement) && self.data.global == Some(placement) {+ return;+ }+ self.data.avatars.insert(path.to_path_buf(), placement);+ self.data.global = Some(placement);+ self.dirty_at = Some(now);+ }+ pub fn flush(&mut self, now: Instant, force: bool) -> Result<()> {+ let Some(dirty) = self.dirty_at else {+ return Ok(());+ };+ if !force && now.saturating_duration_since(dirty) < SAVE_DELAY {+ return Ok(());+ }+ self.dirty_at = Some(now); // Back off after a filesystem error instead of logging each frame.+ if let Some(file) = &self.file {+ if let Some(parent) = file.parent() {+ fs::create_dir_all(parent)?;+ }+ let temporary = file.with_extension(format!("json.{}.tmp", std::process::id()));+ let result = fs::write(&temporary, serde_json::to_vec_pretty(&self.data)?)+ .and_then(|_| fs::rename(&temporary, file));+ if result.is_err() {+ let _ = fs::remove_file(temporary);+ }+ result?;+ }+ self.dirty_at = None;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use mesh_avatar_wgpu::Fit;+ use std::sync::atomic::{AtomicU64, Ordering};+ static NEXT: AtomicU64 = AtomicU64::new(0);+ struct Fixture(PathBuf);+ impl Fixture {+ fn new() -> Self {+ let path = std::env::temp_dir().join(format!(+ "mesh-avatar-settings-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ ));+ fs::create_dir_all(&path).unwrap();+ Self(path)+ }+ }+ impl Drop for Fixture {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.0);+ }+ }+ #[test]+ fn roundtrip_per_avatar_fallback_debounce_and_forced_quit_save() {+ let fixture = Fixture::new();+ let file = fixture.0.join("settings.json");+ let mut settings = Settings::load(Some(file.clone()));+ let now = Instant::now();+ let a = Placement {+ position: [-1200.5, 40.25],+ zoom: 1.5,+ };+ let b = Placement {+ position: [100.0, 200.0],+ zoom: 0.5,+ };+ settings.record(Path::new("first.mavatar"), a, now);+ settings+ .flush(now + Duration::from_millis(499), false)+ .unwrap();+ assert!(!file.exists());+ settings.record(+ Path::new("second.mavatar"),+ b,+ now + Duration::from_millis(400),+ );+ settings+ .flush(now + Duration::from_millis(600), false)+ .unwrap();+ assert!(!file.exists());+ settings+ .flush(now + Duration::from_millis(901), false)+ .unwrap();+ let restored = Settings::load(Some(file.clone()));+ assert_eq!(restored.placement(Path::new("first.mavatar")), Some(a));+ assert_eq!(restored.placement(Path::new("unknown.mavatar")), Some(b));+ settings.record(Path::new("first.mavatar"), b, now + Duration::from_secs(1));+ settings.flush(now + Duration::from_secs(1), true).unwrap();+ assert_eq!(+ Settings::load(Some(file)).placement(Path::new("first.mavatar")),+ Some(b)+ );+ }+ #[test]+ fn corrupt_missing_and_invalid_settings_do_not_prevent_startup() {+ let fixture = Fixture::new();+ let file = fixture.0.join("settings.json");+ assert!(Settings::load(Some(file.clone()))+ .placement(Path::new("avatar"))+ .is_none());+ for bytes in ["broken", r#"{"global":{"position":[0,0],"zoom":-2}}"#] {+ fs::write(&file, bytes).unwrap();+ assert!(Settings::load(Some(file.clone()))+ .placement(Path::new("avatar"))+ .is_none());+ }+ }+ #[test]+ fn failed_atomic_write_keeps_previous_file_and_can_retry() {+ let fixture = Fixture::new();+ let file = fixture.0.join("settings.json");+ fs::create_dir(&file).unwrap();+ let mut settings = Settings::load(Some(file.clone()));+ let now = Instant::now();+ let p = Placement {+ position: [10.0, 20.0],+ zoom: 1.0,+ };+ settings.record(Path::new("avatar"), p, now);+ assert!(settings.flush(now, true).is_err());+ assert!(file.is_dir());+ fs::remove_dir(&file).unwrap();+ settings.flush(now, true).unwrap();+ assert_eq!(+ Settings::load(Some(file)).placement(Path::new("avatar")),+ Some(p)+ );+ }+ #[test]+ fn removed_monitor_negative_coordinates_and_mixed_dpi_stay_visible() {+ let view = ViewOptions {+ image_size: [1254, 1254],+ pad_top: -0.07,+ pad_side: 0.0,+ fit: Fit::Contain,+ };+ let areas = [+ Area {+ position: [0.0, 25.0],+ size: [1440.0, 820.0],+ dpi: 2.0,+ },+ Area {+ position: [-1920.0, 0.0],+ size: [1920.0, 1040.0],+ dpi: 1.0,+ },+ ];+ for point in [[-1800.0, 50.0], [7000.0, -4000.0], [1439.0, 819.0]] {+ let restored = restore(+ &view,+ Placement {+ position: point,+ zoom: 4.0,+ },+ &areas,+ 8192,+ )+ .unwrap();+ let mut scaling = restored.scaling;+ let size = scaling.take_request().unwrap();+ assert!(areas.iter().any(|a| restored.position[0] >= a.position[0]+ && restored.position[1] >= a.position[1]+ && restored.position[0] + f64::from(size.width) / a.dpi+ <= a.position[0] + a.size[0] + 1e-8+ && restored.position[1] + f64::from(size.height) / a.dpi+ <= a.position[1] + a.size[1] + 1e-8));+ }+ let restored = restore(+ &view,+ Placement {+ position: [-1800.0, 50.0],+ zoom: 1.5,+ },+ &areas,+ 8192,+ )+ .unwrap();+ assert_eq!(restored.position, [-1800.0, 50.0]);+ assert_eq!(restored.scaling.zoom(), 1.5);+ let restored = restore(+ &view,+ Placement {+ position: [-1800.0, 50.0],+ zoom: 1.5,+ },+ &areas[..1],+ 8192,+ )+ .unwrap();+ assert_eq!(restored.position[0], 0.0);+ assert!(restore(+ &view,+ Placement {+ position: [0.0, 0.0],+ zoom: 1.0+ },+ &[],+ 8192+ )+ .is_none());+ }+}