@mochiya/avatar-composition 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Mochiya
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mochiya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,258 +1,268 @@
1
- # Mochiya Avatar Composition
2
-
3
- Compose a base avatar with clothing, hair and other **attachments** in Three.js, with reversible rig binding, fit settings and controls. This package is the maintenance home of the **`MOCHIYA_avatar_composition` glTF extension**, its schema and runtime behavior.
4
-
5
- Source: [mochiya-labs/avatar-composition](https://github.com/mochiya-labs/avatar-composition). Export avatars and attachments from Unity with [Mochiya Avatar Tools](https://github.com/mochiya-labs/unity-avatar-tools).
6
-
7
- ```mermaid
8
- flowchart LR
9
- Unity["Mochiya Unity exporter"] --> File["Avatar or attachment<br/>VRM / GLB + Mochiya data"]
10
- File --> Loader["GLTFLoader + Mochiya plugin"]
11
- Loader --> Session["AvatarCompositionSession<br/>one base + attachments"]
12
- VRM["three-vrm<br/>standard VRM behavior"] --> Session
13
- Session --> View["Host scene and animation loop"]
14
- LilToon["Any material library<br/>host-owned rendering"] --> View
15
- ```
16
-
17
- ## Avatar or attachment
18
-
19
- The runtime follows the Unity exporter's declared kind, including when an attachment contains a humanoid rig.
20
-
21
- | `assetKind` | Unity export rule | Runtime role |
22
- | ------------ | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
23
- | `avatar` | Own VRM-compatible humanoid and no external Modular Avatar (MA) dependency. May include clothing and child armatures. | Session base; included content stays together. |
24
- | `attachment` | Needs its direct parent's humanoid or has external MA dependencies/effects. That parent must be a valid avatar. | Added with `session.attach()`. |
25
-
26
- Both converted kinds carry the extension when exported through Mochiya. Conversion preserves separate armatures; MA owns Unity-side merging. Files without the extension can use host-selected roles and bone-name attachment, without recovered MA actions.
27
-
28
- ## Extension capabilities
29
-
30
- `MOCHIYA_avatar_composition` **0.1** stores MA-style component instructions at the glTF document root. The runtime resolves them against a selected base when an attachment is added. Standard skinning, VRM expressions/physics and material rendering keep their own formats and owners.
31
-
32
- | Component | Converted Unity source | Runtime capability and limit |
33
- | ---------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
- | `mergeArmature` | **MA Merge Armature**; generated parent reference rig | Store roots, prefix/suffix and settings; discover matching bones at attachment time. Unidirectional following with retained skins/rest offsets. Other lock modes warn and use that direction. |
35
- | `boneProxy` | **MA Bone Proxy**; generated external VRC collider anchors | Follow a base target with Keep World Pose or At Root. Partial-pose/scale modes warn and keep world pose. |
36
- | `shapeChanger` | **MA Shape Changer** | Set blendshape weights or reversibly remove triangles affected by a blendshape. Preserves MA's distance threshold (default `0.01`). |
37
- | `blendshapeSync` | **MA Blendshape Sync** | Grouped driver/driven references and linear remap points. No sync chains/cycles. |
38
- | `objectToggle` | **MA Object Toggle** | Grouped Boolean visibility changes with logical ancestor conditions. No visibility cycles. |
39
- | `materialSetter` | **MA Material Setter** | Grouped slot replacements using file-local materials; shader-independent. |
40
- | `menuItem` | **MA Menu Item** | Toggle or momentary Button; parameter/value/default metadata. Automatic source-object activation; named parameters remain local, without arbitrary Animator effects. |
41
-
42
- Unity conversion preserves component boundaries and separate armatures. Generated reference rigs/collider anchors are labeled by `origin`. The runtime follows external base targets without collapsing skeletons; local merge requests remain unapplied with warnings. Each VRM owns its springs and colliders; cross-asset collider linking is outside the extension.
43
-
44
- ### Data and matching
45
-
46
- Delete uses the loaded base mesh's position deltas and restores polygons when disabled or detached. It keeps vertex buffers and morph weights intact. Missing geometry uses weight `0` with a warning; multi-frame Unity shapes and scale baking can affect parity. See the [deletion rules](https://github.com/mochiya-labs/avatar-composition/blob/main/specification/README.md#shape-changer-deletion) for thresholds and precedence.
47
-
48
- | Data | Purpose |
49
- | ------------------------------- | ------------------------------------------------------------------------------------------ |
50
- | `specVersion`, `assetKind` | Required `0.1` and `avatar`/`attachment`. |
51
- | `components` | Ordered records with unique ID, type, source node, supported settings and grouped entries. |
52
- | `asset: "self"` | Final file-local node/morph indices; material indices also stay local. |
53
- | `asset: "base"` | Hierarchy paths and bone/mesh/blendshape keywords; optional humanoid fallback. |
54
- | `matching`, `nodes`, `rig.role` | Name hints/aliases, initial visibility and avatar/reference-rig role. |
55
- | `requiredCapabilities` | Component types required by the file. |
56
-
57
- **Matching is best effort:** unresolved or ambiguous names warn and skip only affected entries. There is no base identity/checksum gate or automatic adaptation to another body shape. Malformed records, invalid local indices and unsupported required capabilities are errors.
58
-
59
- ```json
60
- {
61
- "id": "coat-rig",
62
- "type": "mergeArmature",
63
- "sourceNode": 12,
64
- "target": {
65
- "asset": "base",
66
- "path": ["Armature"],
67
- "boneKeywords": ["Armature"]
68
- },
69
- "prefix": "Coat_",
70
- "lockMode": "unidirectional"
71
- }
72
- ```
73
-
74
- This record belongs in `components` and assumes node 12 exists in the file. Bone pairs are computed at runtime. See the [behavior specification](https://github.com/mochiya-labs/avatar-composition/blob/main/specification/README.md) for defaults, conditions, matching and evaluation order, and the [JSON Schema](https://github.com/mochiya-labs/avatar-composition/blob/main/schema/MOCHIYA_avatar_composition.schema.json) for structure. The schema is also exported as `@mochiya/avatar-composition/schema`. The current draft replaces the old action/joint-mapping format: **re-export older assets**.
75
-
76
- ## Install
77
-
78
- Install the built tarball in your application with compatible peers; these versions are a reproducible example:
79
-
80
- ```sh
81
- npm install /path/to/mochiya-avatar-composition-0.1.0.tgz three@0.185.1 @pixiv/three-vrm@3.5.5
82
- ```
83
-
84
- After publication, the tarball path can be replaced with `@mochiya/avatar-composition@0.1.0`. Commit the application's package manifest and lockfile so deployment installs the same release. No source checkout or package build is needed on the deployment server. Keep one shared copy of Three.js and three-vrm in the host application.
85
-
86
- The package includes compiled ESM JavaScript, TypeScript declarations and the extension contract in `dist/`, plus npm's README, LICENSE and package metadata. Implementation source, source maps, development tools, tests, viewer files and model assets are excluded. Compiled JavaScript remains inspectable by consumers.
87
-
88
- ## Try the example viewer (source checkout)
89
-
90
- Use Node.js 20.19+ for the viewer. A normal install uses the published `@mochiya/three-liltoon` package:
91
-
92
- ```sh
93
- git clone https://github.com/mochiya-labs/avatar-composition.git
94
- cd avatar-composition/examples/viewer
95
- npm install
96
- npm run dev
97
- ```
98
-
99
- Run `npm run build` from `examples/viewer` to create the production site in that directory's `dist/`, then `npm run preview` to serve it locally. npm uses the repository's workspace and root lockfile when installing from the viewer directory. The viewer compiles Avatar Composition's source directly; it does not need the library's ignored `dist/` or a separate library build. The repository-root `viewer:dev` and `viewer:build` scripts remain convenient alternatives.
100
-
101
- To test unpublished changes from a sibling `three-liltoon/` checkout, run these commands from the Avatar Composition repository root. They build that package and apply a local install without changing the committed manifest or lockfile:
102
-
103
- ```sh
104
- npm --prefix ../three-liltoon run build:package
105
- npm run viewer:use-local-liltoon
106
- npm run viewer:dev
107
- ```
108
-
109
- Run `npm install` again to restore the published dependency recorded in the lockfile. Clean npm and Vercel installs always use the registry package.
110
-
111
- Open Vite's URL (normally `http://127.0.0.1:5175`). **Load avatar**, then **Add attachment** using your VRM/GLB files. Select an asset to inspect its controls and matching results; hide or remove attachments to undo their effects. For any selected VRM, **Show debug visualizers** displays its available humanoid, look-at, constraint, spring-joint and collider helpers. This setting is independent for each asset and starts off. Optional base animations use VRMA files. All files stay in the browser.
112
-
113
- The viewer starts empty, with Assets, Preview and Inspector always available. The Inspector groups lilToon and composition warnings into collapsed accordions, provides per-mesh visibility and blendshape inspection, and shows a collapsed bone hierarchy for the selected asset. When the selected file contains `MOCHIYA_avatar_composition`, its extension debugger shows authored component instructions separately from resolved links, modified targets and skipped entries, with the complete manifest available. Panels stack below the preview on small screens. Lighting and the ground grid use fixed defaults; no demo models or stage settings are included.
114
-
115
- The navigation matches the lilToon viewer and Mochiya website, with the Mochiya mascot and wordmark, a [GitHub source link](https://github.com/mochiya-labs/avatar-composition), an English/日本語 menu, and Light/Dark/System appearance choices. Language and appearance preferences are saved in the browser. Changing them preserves the current avatar composition.
116
-
117
- ### Deploy the viewer to Vercel
118
-
119
- Import `mochiya-labs/avatar-composition` and use these project settings:
120
-
121
- | Setting | Value |
122
- | -------------------------------------------------------------------- | -------------------------------------------------- |
123
- | Root Directory | `examples/viewer` |
124
- | Framework Preset | Vite |
125
- | Install Command | Default (automatic npm installation) |
126
- | Build Command | Default (`npm run build`) |
127
- | Output Directory | Default (`dist`, relative to the viewer directory) |
128
- | Include source files outside of the Root Directory in the Build Step | Enabled |
129
-
130
- Leave the install, build and output override switches off. The repository root must be included because it contains the workspace lockfile and the Avatar Composition source. This uses the same viewer-directory/default-command deployment flow as the three-liltoon example, with Vite providing this viewer's framework defaults. No custom Vercel configuration file or library build step is required.
131
-
132
- ## Use in Three.js
133
-
134
- The host supplies `scene`, retargeted animation clips and the render loop. The session can own the base animation mixer and frame ordering. Await loading before preparing assets. The core has no material-library dependency.
135
-
136
- ```ts
137
- import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
138
- import { VRMLoaderPlugin, VRMUtils } from "@pixiv/three-vrm";
139
- import {
140
- MochiyaAvatarCompositionLoaderPlugin,
141
- prepareAvatarAsset,
142
- AvatarCompositionSession,
143
- disposeAvatarAsset,
144
- } from "@mochiya/avatar-composition";
145
-
146
- const loader = new GLTFLoader()
147
- .register((p) => new VRMLoaderPlugin(p))
148
- .register((p) => new MochiyaAvatarCompositionLoaderPlugin(p));
149
-
150
- async function load(url: string) {
151
- const gltf = await loader.loadAsync(url);
152
- if (gltf.userData.vrm) VRMUtils.rotateVRM0(gltf.userData.vrm);
153
- return prepareAvatarAsset(gltf);
154
- }
155
-
156
- const base = await load("/avatar.vrm");
157
- const attachment = await load("/attachment.vrm");
158
- scene.add(base.scene, attachment.scene);
159
- const session = new AvatarCompositionSession({ base });
160
- const result = session.attach(attachment, { id: "coat", layerOrder: 0 });
161
- console.log(result.status, result.warnings, result.resolved); // attached | partial | unbound
162
-
163
- function update(delta: number) {
164
- // Call once per rendered frame.
165
- session.update(delta);
166
- const updated = new Set(base.vrm?.materials ?? []);
167
- for (const material of attachment.vrm?.materials ?? []) {
168
- if (!attachment.scene.visible || updated.has(material)) continue;
169
- updated.add(material);
170
- (
171
- material as typeof material & { update?: (delta: number) => void }
172
- ).update?.(delta);
173
- }
174
- }
175
-
176
- function hideAttachment() {
177
- session.setItemState("coat", { visible: false });
178
- }
179
- function cleanup() {
180
- session.detach("coat");
181
- disposeAvatarAsset(attachment);
182
- session.dispose();
183
- disposeAvatarAsset(base);
184
- }
185
- ```
186
-
187
- Controls use the menu parameter or component ID: `setItemState(id, { controls: { controlId: value } })`, `setBaseControl()` and `setBaseMorph()`. Use `menuItems(asset.manifest)` to build a control UI; buttons send their value while held and 0 on release/cancel. The session advances attachment expressions/constraints/springs; update the whole VRM only on the base. Plain GLB has no VRM physics.
188
-
189
- For editable mesh morphs, call `session.isMorphControlled(mesh, index)` before enabling a slider and `session.setMorph(mesh, index, value)` to apply a user weight. The latter returns false for a currently composition-controlled target and throws for non-finite values or targets outside the session. Accepted weights survive VRM expression updates; active composition writes still take precedence. Recheck controls after attachment visibility, menu or membership changes.
190
-
191
- Hosts that already call `session.update()` each frame can use `session.setMorph(mesh, index, value, { deferEvaluation: true })`. It records the weight immediately without restoring unrelated composition layers or evaluating the entire composition; the next `update()` applies the normal composition lifecycle. Coalesce pointer events to the latest value per mesh/weight before that update, and persist the final edit when the gesture finishes. Ownership and morph-writer lookups are indexed when session membership changes; control conditions remain live.
192
-
193
- Pass a clip retargeted to `base.vrm` to `session.setAnimation(clip, time)`. The session creates one mixer on the base scene; use `session.update(delta, paused)` for playback and `animationTime` for serialization. Passing `null` stops playback and resets the normalized humanoid pose. `session.update(delta)` restores overlays, advances the mixer and base VRM, updates world matrices, then evaluates attachment behavior. Hosts that already own animation may instead retain `beforeVrmUpdate()` / `afterVrmUpdate(delta)` around their own base update; use only one frame-update approach.
194
-
195
- Use independent loaded instances per attachment. Detach before disposal; session disposal restores overlays without freeing assets. Changing bases requires a new session and renewed matching.
196
-
197
- ### Materials and ownership
198
-
199
- | Concern | Responsibility |
200
- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
201
- | Material swaps | Core assigns file-local materials and restores the original binding. No shader-specific bridge. |
202
- | glTF primitive | Replaces its entire material binding, including loader-expanded arrays; undo restores the original array and geometry groups. |
203
- | Procedural meshes | Swaps only the selected material slot. Pass `authoredObjects` when the scene includes generated helpers. |
204
- | Rendering and material animation | Host and chosen material library. `base.vrm.update()` advances base materials; advance visible attachment materials once in the host loop. |
205
- | Disposal | `prepareAvatarAsset()` captures owned parser resources. Detach before disposal. Procedural assets accept explicit `resources`; omit shared resources managed by another owner. |
206
-
207
- The core never inspects shader uniforms or custom texture caches. `disposeAvatarAsset()` releases its resource snapshot once, so later material swaps cannot make it dispose a borrowed material. Procedural default ownership includes geometry, skeletons and materials; declare textures explicitly with `resources` when the asset owns them.
208
-
209
- ### Optional lilToon rendering
210
-
211
- Install [`@mochiya/three-liltoon`](https://github.com/mochiya-labs/three-liltoon) in the **application** and configure it independently. The sample viewer demonstrates this setup; the core works without the material package.
212
-
213
- ```ts
214
- import { enableLilToon } from "@mochiya/three-liltoon";
215
- import { VRMLoaderPlugin } from "@pixiv/three-vrm";
216
- import { enableLilToonVRM } from "@mochiya/three-liltoon/vrm";
217
-
218
- const releaseRendering = enableLilToon(renderer); // Once per renderer owner.
219
- const loader = new GLTFLoader()
220
- .register((p) => enableLilToonVRM(new VRMLoaderPlugin(p)))
221
- .register((p) => new MochiyaAvatarCompositionLoaderPlugin(p));
222
- // Use this loader with the load(), session and frame loop above.
223
- // On teardown: dispose the session and assets, then releaseRendering().
224
- ```
225
-
226
- The material plugin reads only `MOCHIYA_materials_liltoon`; the Mochiya plugin reads only `MOCHIYA_avatar_composition`. The helper enhances the standard VRM plugin with material loading and expression bindings; it also loads ordinary glTF/GLB without requiring VRM data. Outlines and casters follow ordinary material assignments automatically. Omitting lilToon leaves ordinary glTF fallback materials and attachment behavior available. The source checkout's `examples/viewer/src/engine.ts` demonstrates the complete lifecycle.
227
-
228
- ## Contributing
229
-
230
- Run `npm run format` after code changes and `npm run format:check` before submitting them. VS Code uses the same Prettier settings on save; generated files and local Unity assets are excluded.
231
-
232
- Browser tests generate minimal VRM/GLB inputs in memory. The optional Unity integration test reads the companion exporter's Editor-test outputs from `MOCHIYA_UNITY_FIXTURES` (or `test/unity-project/MochiyaTests`); run Unity first, then the browser suite. Model binaries remain outside Git and the package.
233
-
234
- Update `specification/README.md` and `src/schema.ts`, regenerate the JSON Schema with `build`, and align exporter mappings. General mesh cutters, arbitrary MA/VRC controllers and automatic body-shape adaptation are outside this package's scope.
235
-
236
- ```sh
237
- npm run build
238
- npm run typecheck
239
- npm test
240
- npm run viewer:build
241
- npm run test:browser
242
- ```
243
-
244
- ### npm distribution (maintainers)
245
-
246
- `npm run build` uses tsup and the existing schema generator to produce the runtime, schema and behavior guide under `dist`. The entire `dist/` directory is ignored by Git; do not commit generated distribution files. Source maps are disabled. There are no separate staging or package-check scripts.
247
-
248
- Before distributing a tarball:
249
-
250
- ```sh
251
- npm run build
252
- npm pack --dry-run
253
- npm pack
254
- ```
255
-
256
- Inspect the standard `npm pack --dry-run` output before release: it should contain only `dist/`, README, LICENSE and package metadata. Build before packing; there is no `prepare` or `prepack` hook. Consumers install the compiled package without running build or install lifecycle scripts.
257
-
258
- Publishing with `npm publish` runs formatting, TypeScript, build and runtime tests through npm's standard `prepublishOnly` hook and uses the public npm registry. Choose a new package version for later releases. The local viewer workspace is never included in the runtime archive.
1
+ # Mochiya Avatar Composition
2
+
3
+ Compose a base avatar with clothing, hair and other **attachments** in Three.js, with reversible rig binding, fit settings and controls. This package is the maintenance home of the **`MOCHIYA_avatar_composition` glTF extension**, its schema and runtime behavior.
4
+
5
+ Source: [mochiya-labs/avatar-composition](https://github.com/mochiya-labs/avatar-composition). Export avatars and attachments from Unity with [Mochiya Avatar Tools](https://github.com/mochiya-labs/unity-avatar-tools).
6
+
7
+ ```mermaid
8
+ flowchart LR
9
+ Unity["Mochiya Unity exporter"] --> File["Avatar or attachment<br/>VRM / GLB + Mochiya data"]
10
+ File --> Loader["GLTFLoader + AvatarCompositionLoaderPlugin"]
11
+ Loader --> Session["AvatarComposition<br/>one base + attachments"]
12
+ VRM["three-vrm<br/>standard VRM behavior"] --> Session
13
+ Session --> View["Host scene and animation loop"]
14
+ LilToon["Any material library<br/>host-owned rendering"] --> View
15
+ ```
16
+
17
+ ## Avatar or attachment
18
+
19
+ The runtime follows the Unity exporter's declared kind, including when an attachment contains a humanoid rig.
20
+
21
+ | `assetKind` | Unity export rule | Runtime role |
22
+ | ------------ | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
23
+ | `avatar` | Own VRM-compatible humanoid and no external Modular Avatar (MA) dependency. May include clothing and child armatures. | Session base; included content stays together. |
24
+ | `attachment` | Needs its direct parent's humanoid or has external MA dependencies/effects. That parent must be a valid avatar. | Added with `composition.add()`. |
25
+
26
+ Both converted kinds carry the extension when exported through Mochiya. Conversion preserves separate armatures; MA owns Unity-side merging. Files without the extension can use host-selected roles and bone-name attachment, without recovered MA actions.
27
+
28
+ ## Extension capabilities
29
+
30
+ `MOCHIYA_avatar_composition` stores MA-style component instructions at the glTF document root. The runtime resolves them against a selected base when an attachment is added. Supported older assets can be imported without re-exporting; the runtime validates them into its current internal representation without modifying the source data. New exports use the current marker. Standard skinning, VRM expressions/physics and material rendering keep their own formats and owners.
31
+
32
+ | Component | Converted Unity source | Runtime capability and limit |
33
+ | ---------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | `mergeArmature` | **MA Merge Armature**; generated parent reference rig | Store roots, prefix/suffix and settings; discover matching bones at attachment time. Unidirectional following with retained skins/rest offsets. Other lock modes warn and use that direction. |
35
+ | `boneProxy` | **MA Bone Proxy**; generated external VRC collider anchors | Follow a base target with Keep World Pose or At Root. Partial-pose/scale modes warn and keep world pose. |
36
+ | `shapeChanger` | **MA Shape Changer** | Set blendshape weights or reversibly remove triangles affected by a blendshape. Preserves MA's distance threshold (default `0.01`). |
37
+ | `blendshapeSync` | **MA Blendshape Sync** | Grouped driver/driven references and linear remap points. No sync chains/cycles. |
38
+ | `objectToggle` | **MA Object Toggle** | Grouped Boolean visibility changes with logical ancestor conditions. No visibility cycles. |
39
+ | `materialSetter` | **MA Material Setter** | Grouped slot replacements using file-local materials; shader-independent. |
40
+ | `menuItem` | **MA Menu Item** | Toggle or momentary Button; parameter/value/default metadata. Automatic source-object activation; named parameters remain local, without arbitrary Animator effects. |
41
+
42
+ Unity conversion preserves component boundaries and separate armatures. Generated reference rigs/collider anchors are labeled by `origin`. The runtime follows external base targets without collapsing skeletons; local merge requests remain unapplied with warnings. Each VRM owns its springs and colliders; cross-asset collider linking is outside the extension.
43
+
44
+ ### Data and matching
45
+
46
+ Delete uses the loaded base mesh's position deltas and restores polygons when disabled or detached. It keeps vertex buffers and morph weights intact. Missing geometry uses weight `0` with a warning; multi-frame Unity shapes and scale baking can affect parity. See the [deletion rules](https://github.com/mochiya-labs/avatar-composition/blob/main/specification/README.md#shape-changer-deletion) for thresholds and precedence.
47
+
48
+ | Data | Purpose |
49
+ | ------------------------------- | ------------------------------------------------------------------------------------------ |
50
+ | `specVersion`, `assetKind` | Required extension marker and `avatar`/`attachment`. |
51
+ | `components` | Ordered records with unique ID, type, source node, supported settings and grouped entries. |
52
+ | `asset: "self"` | Final file-local node/morph indices; material indices also stay local. |
53
+ | `asset: "base"` | Hierarchy paths and bone/mesh/blendshape keywords; optional humanoid fallback. |
54
+ | `matching`, `nodes`, `rig.role` | Name hints/aliases, initial visibility and avatar/reference-rig role. |
55
+ | `requiredCapabilities` | Component types required by the file. |
56
+
57
+ **Matching is best effort:** unresolved or ambiguous names warn and skip only affected entries. There is no base identity/checksum gate or automatic adaptation to another body shape. Malformed records, invalid local indices and unsupported required capabilities are errors.
58
+
59
+ ```json
60
+ {
61
+ "id": "coat-rig",
62
+ "type": "mergeArmature",
63
+ "sourceNode": 12,
64
+ "target": {
65
+ "asset": "base",
66
+ "path": ["Armature"],
67
+ "boneKeywords": ["Armature"]
68
+ },
69
+ "prefix": "Coat_",
70
+ "lockMode": "unidirectional"
71
+ }
72
+ ```
73
+
74
+ This record belongs in `components` and assumes node 12 exists in the file. Bone pairs are computed at runtime. See the [behavior specification](https://github.com/mochiya-labs/avatar-composition/blob/main/specification/README.md) for defaults, conditions, matching and evaluation order, and the [JSON Schema](https://github.com/mochiya-labs/avatar-composition/blob/main/schema/MOCHIYA_avatar_composition.schema.json) for structure. The JSON Schema is included in `dist/`.
75
+
76
+ ## Install
77
+
78
+ Install the published package in your application with compatible peer dependencies:
79
+
80
+ ```sh
81
+ npm install @mochiya/avatar-composition three @pixiv/three-vrm
82
+ ```
83
+
84
+ For local package development, replace the package name with a path to a built tarball. Commit the application's package manifest and lockfile so deployment installs the intended release. No source checkout or package build is needed on the deployment server. Keep one shared copy of Three.js and three-vrm in the host application.
85
+
86
+ The package includes compiled ESM JavaScript, TypeScript declarations and the extension contract in `dist/`, plus npm's README, LICENSE and package metadata. Implementation source, source maps, development tools, tests, viewer files and model assets are excluded. Compiled JavaScript remains inspectable by consumers.
87
+
88
+ ## Try the example viewer (source checkout)
89
+
90
+ Use a currently supported Node.js release for the viewer. A normal install uses the published `@mochiya/three-liltoon` package:
91
+
92
+ ```sh
93
+ git clone https://github.com/mochiya-labs/avatar-composition.git
94
+ cd avatar-composition/examples/viewer
95
+ npm install
96
+ npm run dev
97
+ ```
98
+
99
+ Run `npm run build` from `examples/viewer` to create the production site in that directory's `dist/`, then `npm run preview` to serve it locally. npm uses the repository's workspace and root lockfile when installing from the viewer directory. The viewer compiles Avatar Composition's source directly; it does not need the library's ignored `dist/` or a separate library build. The repository-root `viewer:dev` and `viewer:build` scripts remain convenient alternatives.
100
+
101
+ Open Vite's URL (normally `http://127.0.0.1:5175`). **Load avatar**, then **Add attachment** using your VRM/GLB files. Select an asset to inspect its controls and matching results; hide or remove attachments to undo their effects. For any selected VRM, **Show debug visualizers** displays its available humanoid, look-at, constraint, spring-joint and collider helpers. This setting is independent for each asset and starts off. Optional base animations use VRMA files. All files stay in the browser.
102
+
103
+ The viewer starts empty, with Assets, Preview and Inspector always available. The Inspector groups lilToon and composition warnings into collapsed accordions, provides authored-object activation and grouped blendshape inspection, and shows a collapsed bone hierarchy for the selected asset. When the selected file contains `MOCHIYA_avatar_composition`, its extension debugger shows authored component instructions separately from resolved links, modified targets and skipped entries, with the complete manifest available. Panels stack below the preview on small screens. Lighting and the ground grid use fixed defaults; no demo models or stage settings are included.
104
+
105
+ The navigation matches the lilToon viewer and Mochiya website, with the Mochiya mascot and wordmark, a [GitHub source link](https://github.com/mochiya-labs/avatar-composition), an English/日本語 menu, and Light/Dark/System appearance choices. Language and appearance preferences are saved in the browser. Changing them preserves the current avatar composition.
106
+
107
+ ### Deploy the viewer to Vercel
108
+
109
+ Import `mochiya-labs/avatar-composition` and use these project settings:
110
+
111
+ | Setting | Value |
112
+ | -------------------------------------------------------------------- | -------------------------------------------------- |
113
+ | Root Directory | `examples/viewer` |
114
+ | Framework Preset | Vite |
115
+ | Install Command | Default (automatic npm installation) |
116
+ | Build Command | Default (`npm run build`) |
117
+ | Output Directory | Default (`dist`, relative to the viewer directory) |
118
+ | Include source files outside of the Root Directory in the Build Step | Enabled |
119
+
120
+ Leave the install, build and output override switches off. The repository root must be included because it contains the workspace lockfile and the Avatar Composition source. This uses the same viewer-directory/default-command deployment flow as the three-liltoon example, with Vite providing this viewer's framework defaults. No custom Vercel configuration file or library build step is required.
121
+
122
+ ## Tutorial: compose and edit an avatar
123
+
124
+ ### Load and compose
125
+
126
+ Register the plugin on a normal Three.js loader alongside your VRM, material or decoder plugins. This example assumes you already have a `scene`, `camera` and `renderer`.
127
+
128
+ ```ts
129
+ import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
130
+ import { VRMLoaderPlugin, VRMUtils } from "@pixiv/three-vrm";
131
+ import {
132
+ AvatarCompositionLoaderPlugin,
133
+ AvatarComposition,
134
+ type AvatarAsset,
135
+ type AvatarItem,
136
+ } from "@mochiya/avatar-composition";
137
+
138
+ const loader = new GLTFLoader()
139
+ .register((p) => new AvatarCompositionLoaderPlugin(p))
140
+ .register((p) => new VRMLoaderPlugin(p));
141
+
142
+ const baseGLTF = await loader.loadAsync("/avatar.vrm");
143
+ const coatGLTF = await loader.loadAsync("/coat.vrm");
144
+ // Normalize VRM 0.x orientation before the composition takes its snapshot.
145
+ for (const gltf of [baseGLTF, coatGLTF]) {
146
+ if (gltf.userData.vrm) VRMUtils.rotateVRM0(gltf.userData.vrm);
147
+ }
148
+ const base: AvatarAsset = baseGLTF.userData.avatar;
149
+ const coat: AvatarAsset = coatGLTF.userData.avatar;
150
+ scene.add(base.scene, coat.scene);
151
+ const composition = new AvatarComposition(base);
152
+ composition.add(coat);
153
+ console.log(composition.inspect(coat)); // Attachment status and matching warnings.
154
+
155
+ let previous = 0;
156
+ renderer.setAnimationLoop((time: number) => {
157
+ const delta = previous ? (time - previous) / 1000 : 0;
158
+ previous = time;
159
+ composition.update(delta);
160
+ renderer.render(scene, camera);
161
+ });
162
+ ```
163
+
164
+ Read `userData.avatar` **after loading completes**, never inside another plugin's loader hooks. First access captures the finished scene and resources; later reads return the same asset. Standard `load`, `loadAsync`, `parse` and `parseAsync` work. No subclass or explicit preparation step is needed. TypeScript callers can annotate the result as `AvatarAsset`; ordinary GLTFLoader results are not globally retyped.
165
+
166
+ The composition updates the base VRM. The host remains responsible for attachment material animation: update each active attachment's VRM material once per frame, excluding shared/base materials. Do not separately update the base VRM. See the viewer for the complete material lifecycle.
167
+
168
+ ### Discover and edit items
169
+
170
+ Base, attachment and child objects share the same methods. IDs are generated automatically.
171
+
172
+ ```ts
173
+ const meshItems: AvatarItem[] = [];
174
+ coat.traverse((item) => {
175
+ if (item.three.renderMeshes.length) meshItems.push(item);
176
+ });
177
+
178
+ coat.setActive(false); // Hide the entire coat and withdraw its composition effects.
179
+ coat.setActive(true);
180
+ const item = meshItems[0];
181
+ if (item) {
182
+ item.setActive(false); // All material primitives of this authored object.
183
+ item.setActive(true);
184
+ const morph = item.morphs.find((m) => !m.controlled);
185
+ if (morph) item.setMorph(morph.id, 0.5); // Normalized 0–1 weight.
186
+ const control = item.controls.find((c) => c.type === "toggle");
187
+ if (control) item.setControl(control.id, true);
188
+ }
189
+ ```
190
+
191
+ Each mesh item represents an authored Unity object, including all its material primitives. Its blendshapes follow source order and stay scoped to that item, even when other items have identical blendshape names. `three.object3D` and `three.renderMeshes` provide low-level access.
192
+
193
+ ### Clean up
194
+
195
+ ```ts
196
+ renderer.setAnimationLoop(null);
197
+ composition.dispose(); // Releases membership and restores composition changes.
198
+ base.dispose();
199
+ coat.dispose(); // Removes its scene and frees its owned resources.
200
+ ```
201
+
202
+ To detach without freeing an attachment, call `composition.remove(coat)` and remove its scene from your host scene. Assets remain caller-owned. Handle loading errors and first-access initialization errors in your loading UI; as with GLTFLoader, the host owns cleanup of partially loaded resources on failure.
203
+
204
+ ## API reference
205
+
206
+ ### One editing interface
207
+
208
+ The base, attachment roots and authored child objects all implement `AvatarItem`. Each retains its authored parent/children even when rig binding reparents Three.js objects. A Unity object with multiple material primitives is one item. Empty objects remain available as activation scopes.
209
+
210
+ | Member | Meaning |
211
+ | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
212
+ | `id`, `name`, `source` | Generated runtime identity, display name and file-local node/path. Persist source identity, not runtime IDs. |
213
+ | `children`, `parent`, `traverse(visitor)` | Authored object hierarchy. |
214
+ | `activeSelf`, `activeInHierarchy`, `setActive(bool)` | Local activation and evaluated hierarchy activation; no independent renderer-enabled state. |
215
+ | `controls`, `setControl(id, value)` | Owned menu descriptors and input. Buttons send `activeValue` while held and zero on release/cancel. |
216
+ | `morphs`, `setMorph(id, value)` | Named blendshapes grouped across primitives. `controlled` disables edits; `value: null` reports inconsistent primitive values. Writes return `{applied: true}` or a `controlled`/`missing` refusal. |
217
+ | `three.object3D`, `three.renderMeshes` | Low-level Three.js access. Raw `.visible` writes do not change logical activation and are replaced during evaluation. |
218
+
219
+ Find a child through `children` or `traverse`, then call its editing methods directly. `setMorph(id, value, {deferEvaluation: true})` batches UI edits until the next `update()`. Check its result before persisting an edit. Composition-controlled morphs become editable when the owning contribution is withdrawn. Competing effects are recomputed rather than restoring a stale cached value.
220
+
221
+ `setActive(false)` preserves child local settings while disabling the subtree's ordinary effects, including Blendshape Sync. Explicitly inverted reactive conditions remain supported inside an active asset root; disabling the asset root is a hard gate. Serialized child-node `active` means `gameObject.activeSelf && renderer.enabled` (or `activeSelf` without a renderer). The selected Unity export root is always initialized active, ignoring its source GameObject/renderer state. Use runtime root `setActive` to activate or deactivate a loaded asset.
222
+
223
+ `composition.setOrder(asset, number)` changes attachment priority. Equal priorities follow insertion order. `inspect(asset)` returns resolved operations and warnings; `issues` aggregates warnings. `setAnimation(clip, time)` accepts a clip retargeted to the base VRM; `update(delta, paused)` and `animationTime` support playback. Do not also update the base VRM separately.
224
+
225
+ ### Materials and ownership
226
+
227
+ Load independent asset instances for independent attachments. An asset can belong to one composition at a time. Removing an attachment restores its structural bindings; disposing a composition restores overlays and releases membership without freeing assets. Remove assets before calling `asset.dispose()`. Changing the base requires a new composition.
228
+
229
+ On first completed-load access, the plugin snapshots owned geometry, skeletons, materials, resolved textures and decoded images. Disposal releases those original resources once, never borrowed materials introduced by composition. Shared images close after the final owning asset. Do not close active images after their first upload: context restoration can need them again. `asset.resources` is a read-only resource inventory for profiling.
230
+
231
+ Material swaps use file-local slots across all primitives of the authored node. Shader-specific rendering stays with the host's chosen material library. The public API consists of the loader, composition and item interfaces described above.
232
+
233
+ Triangle deletion uses independently disposable attribute wrappers sharing the source vertex and morph typed arrays. Filtering allocates indices without copying every blendshape. Three.js may still allocate separate GPU buffers and morph textures for the geometry view. As with ordinary Three attributes, mark source attributes as needing an update after changing their data so the deletion view is rebuilt.
234
+
235
+ ### Optional lilToon rendering
236
+
237
+ Install [`@mochiya/three-liltoon`](https://github.com/mochiya-labs/three-liltoon) in the **application** and configure it independently. The sample viewer demonstrates this setup; the core works without the material package.
238
+
239
+ ```ts
240
+ import { enableLilToon } from "@mochiya/three-liltoon";
241
+ import { VRMLoaderPlugin } from "@pixiv/three-vrm";
242
+ import { enableLilToonVRM } from "@mochiya/three-liltoon/vrm";
243
+
244
+ const releaseRendering = enableLilToon(renderer); // Once per renderer owner.
245
+ const loader = new GLTFLoader()
246
+ .register((p) => new AvatarCompositionLoaderPlugin(p))
247
+ .register((p) => enableLilToonVRM(new VRMLoaderPlugin(p)));
248
+ // Use this loader with the composition and frame loop above.
249
+ // On teardown: dispose the composition and assets, then releaseRendering().
250
+ ```
251
+
252
+ The material plugin reads only `MOCHIYA_materials_liltoon`; AvatarCompositionLoaderPlugin reads only `MOCHIYA_avatar_composition`. The helper enhances the standard VRM plugin with material loading and expression bindings; it also loads ordinary glTF/GLB without requiring VRM data. Outlines and casters follow ordinary material assignments automatically. Omitting lilToon leaves ordinary glTF fallback materials and attachment behavior available. The source checkout's `examples/viewer/src/engine.ts` demonstrates the complete lifecycle.
253
+
254
+ ## Contributing
255
+
256
+ Run `npm run format` after code changes and `npm run format:check` before submitting them. VS Code uses the same Prettier settings on save; generated files and local Unity assets are excluded.
257
+
258
+ Browser tests generate minimal VRM/GLB inputs in memory. The optional Unity integration test reads the companion exporter's Editor-test outputs from `MOCHIYA_UNITY_FIXTURES` (or `test/unity-project/MochiyaTests`); run Unity first, then the browser suite. Model binaries remain outside Git and the package.
259
+
260
+ Update `specification/README.md` and `src/schema.ts`, regenerate the JSON Schema with `build`, and align exporter mappings. General mesh cutters, arbitrary MA/VRC controllers and automatic body-shape adaptation are outside this package's scope.
261
+
262
+ ```sh
263
+ npm run build
264
+ npm run typecheck
265
+ npm test
266
+ npm run viewer:build
267
+ npm run test:browser
268
+ ```