# VRM and glTF export

`sona_export_avatar` writes an avatar as one file: **VRM 1.0** (the default), **VRM 0.x** (for apps still on
UniVRM 0.x, such as VSeeFace) or a plain **binary glTF**. A VRM opens in VTubing apps, social VR and anything with a
VRM loader. It carries a humanoid skeleton, the expressions (visemes, moods, blinks, gaze), look-at and
first-person settings, and the licence fields the user chose. The bone names follow one of the skeleton maps
([Skeleton maps](skeleton-maps.md)).

![An exported VRM in three-vrm, showing its expressions](../img/vrm-three-vrm.webp)

```c
sona_export_options o;
sona_export_report rep = { sizeof rep };
uint8_t *file;
size_t len;
sona_export_defaults(&o);              /* VRM 1.0, Unity bone names, MToon, most restrictive licence */
o.name = "My avatar";
o.authors = "Ann";                     /* one per line */
o.licence_url = "https://vrm.dev/licenses/1.0/";
o.avatar_permission = SONA_VRM_EVERYONE;
if (sona_export_avatar(avatar, &o, &file, &len, &rep) == SONA_OK) {
  fwrite(file, 1, len, f);
  sona_free(ctx, file);
}
```

```cpp
sona_export_options o;
sona_export_defaults(&o);              // VRM 1.0, Unity bone names, MToon, most restrictive licence
o.name = "My avatar";
o.authors = "Ann";                     // one per line
o.licence_url = "https://vrm.dev/licenses/1.0/";
o.avatar_permission = SONA_VRM_EVERYONE;
sona_export_report rep = { (uint32_t)sizeof rep };
uint8_t *file = nullptr;
size_t len = 0;
if (sona_export_avatar(avatar.raw(), &o, &file, &len, &rep) == SONA_OK) {
  std::ofstream("avatar.vrm", std::ios::binary).write(reinterpret_cast<const char *>(file), (std::streamsize)len);
  sona_free(ctx.raw(), file);
}
```

```csharp
var o = new SonaExportOptions                    // VRM 1.0, Unity bone names, MToon, most restrictive licence
{
    Name = "My avatar",
    Authors = "Ann",                             // one per line
    LicenceUrl = "https://vrm.dev/licenses/1.0/",
    AvatarPermission = SonaVrmPermission.Everyone,
};
if (avatar.TryExport(o, out var file, out var rep))
    File.WriteAllBytes("avatar.vrm", file);
```

```rust
let o = ExportOptions {                          // VRM 1.0, Unity bone names, MToon, most restrictive licence
    name: Some("My avatar".into()),
    authors: Some("Ann".into()),                 // one per line
    licence_url: Some("https://vrm.dev/licenses/1.0/".into()),
    avatar_permission: sona_sys::SONA_VRM_EVERYONE,
    ..Default::default()
};
let (file, rep) = avatar.export(&o)?;
std::fs::write("avatar.vrm", file).ok();
```

```python
data, rep = avatar.export(name="My avatar", authors="Ann",   # VRM 1.0, Unity bone names, MToon
                          licence_url="https://vrm.dev/licenses/1.0/")
with open("avatar.vrm", "wb") as f:
    f.write(data)
```

The sample `samples/c/vrm_export.c` does this for any manifest: `vrm_export --b64 <manifest>
[--format vrm|vrm0|glb] [--bones unity|vrm|ue4|ue5] [--pbr] [--no-expressions] [--name..]
[--author..] --out avatar.vrm`.

## What the file holds

- **The figure as the editor draws it, in the rig's T-pose with its body shape.** Every part the build made (the
  body, the head, each worn item) is one mesh, skinned to one skin of 71 joints. The bones have no rotation or
  scale (the VRM convention; UniVRM writes the same), stand where the rig's joints stand in the T-pose, and the
  vertices are the editor's own vertices skinned into that pose. A clip's own held prop is left out: a VRM is a
  humanoid, and a prop's own skeleton and clip have no place in one. Props attached with `sona_avatar_prop_attach`
  are in, each a rigid node under its bone ([Props](props.md#in-gltf-and-vrm-files); `SONA_EXPORT_NO_PROPS`
  leaves them out).
- **Handedness.** The editor works in a left-handed space with avatars facing -Z. glTF is right-handed, so z is
  negated and each triangle turned round, and the figure faces +Z with its left hand at +X, as VRM 1.0 wants
  (the editor's own export does the same). VRM 0.x files face -Z, so there x is negated instead.
- **Triangles with no area** in the T-pose are left out (the build collapses body triangles under clothes);
  `report.degenerate` counts them.
- **One picture per part.** The shaders combine up to three textures, each through its own uv set:
  `c = colour(uv0) * intensity(uv1).a + intensity(uv1).rgb`, then `c = c * decal(uv2).a + decal(uv2).rgb` for the
  families whose third texture is a decal (on a reflective part it is a matcap). glTF has one base colour
  texture, so the chain is flattened, in linear light, exactly as the editor's own export does it: the colour map
  as it is when the other two change nothing; else the chain rasterised into the uv set whose picture reads back
  closest to it; else a fresh chart atlas; and when two surfaces share texels and disagree, a unique layout where
  every triangle owns its texels. `report.baked` counts the parts flattened and `report.bake_error` is the worst
  one's readback error. The vertex colour (baked occlusion) is glTF's `COLOR_0`.
- **Materials.** VRM files use MToon (`VRMC_materials_mtoon` for 1.0, `VRM/MToon` material properties for 0.x),
  a soft toon shade close to the editor's flat irradiance light; `SONA_EXPORT_PBR` writes glTF metal-rough
  instead. Plain glTF is metal-rough. Cut-out parts are `MASK` at 0.5 (the shader discards below half), the
  transparent families `BLEND`, every material single-sided like the editor.
- **The humanoid**: the 51 joints of the VRM map, every required bone among them.
- **First person**: meshes skinned only to the head are `thirdPersonOnly`; the rest are `auto`, which lets the
  VRM runtime cut the head's triangles out of them.
- **Look-at**: `expression` type, from a point between the eyes measured on the face's own triangles; up to 20
  degrees maps onto the gaze expressions.
- **Meta**: name, version, authors, copyright, contact, references, third-party licences, the licence URL, the
  avatar permission, commercial use, modification, redistribution, the violence, sexual, political and
  antisocial flags, the credit notation, and an optional thumbnail PNG (`sona_snapshot` plus `sona_png_encode`
  make one). VRM 0.x takes the nearest of its fields. The defaults are the most restrictive: only the author,
  personal non-profit use, no modification or redistribution, credit required. `asset.copyright` carries the
  user's copyright, else the credit "Powered by 360sona, https://360sona.com".

## Expressions

A face here is a picture, not a shape: the head's face sheet is baked from the mouth, eyebrow and eye shapes of
the face items (14 mouths, 5 brows, 14 eyes; `sona_avatar_expression`). So an expression cannot be a morph target.
It is a texture offset, VRM's `textureTransformBinds` (VRM 0.x: `_MainTex_ST` material values), which every VRM
runtime applies.

- The face sheet's triangles are sorted by the face parts their texels belong to, found by baking every shape
  each expression asks for and comparing with the neutral face. The mouth, each brow and each eye come out as
  separate groups of triangles (on the cast no triangle touches both the mouth and an eye).
- Each group gets its own material and an **atlas**: a crop of the face sheet around its triangles, once per face
  that group can show, baked with the same code `sona_avatar_expression` uses. Each cell is baked from the
  group's own triangles only, so an export bakes about 130 small sheets instead of 130 full ones.
- An expression moves its groups' texture offset to its cell. Overlapping expressions add their offsets, so the
  cells sit on **axes**, each a digit of a mixed-radix number along x or y: visemes (aa ih ou ee oh, one at a
  time), moods (happy angry sad relaxed surprised, one at a time), gaze (left or right plus up or down: diagonals
  have their own cells) and lids (blink plus the side's own blink). Any mix of one viseme, one mood, a gaze and
  the blinks lands on a cell baked for exactly that mix. What a cell shows is decided in this order: the mood,
  then the gaze, then the viseme, then the lids, so a blink closes a sad eye and a viseme speaks through a smile.
  Two moods at once, or two visemes at once, land on another expression's cell: drive one of each.
- Every expression is `isBinary` (a weight over 0.5 is on): half an offset is a smeared face.
- The default faces (`sona_vrm_face_default`): aa AI, ih EE, ou W, ee L, oh O; happy is the happy mouth and eyes
  with raised brows; angry and sad their own three shapes; relaxed a smile with the laughing (closed) eyes;
  surprised the shocked mouth and eyes with raised brows; blink the blink eye on both sides, blinkLeft and
  blinkRight on the avatar's own left or right eye; lookUp and lookDown both eyes; lookLeft the left eye looking
  out and the right one in (the avatar looks to its own left). `sona_export_options.faces` replaces any of them,
  in the same part order as `sona_avatar_expression` (mouth, left brow, right brow, left eye, right eye), 255 for
  a part the expression leaves alone. Which of the face's two eye slots is the avatar's left is measured on the
  triangles; on every cast avatar the face's "left" slot is the avatar's left.
- A face behind a helmet has fewer parts on its sheet: the expressions that touch none of them have no binds.
- Each face material's `extras` give its crop, cell size and pad (`faceParts`, `faceCrop`, `faceCell`, `facePad`,
  `faceSheet`), for tools that read the faces back. Each mesh gets its own copy of a group's material, because
  three-vrm binds a material once for every mesh that uses it.

## Cost

The parts' flattening, the face plan, each group's atlas and every PNG run on the ctx's workers
(`sona_config.worker_threads`); call it from the thread that calls `sona_update`. With no workers it runs on the
calling thread. Nothing in the frame changes: `sona_update` and `sona_draw` do no export work.

## Limits

- **Spring bones.** The rig has no hair or cloth joints, so there is nothing for `VRMC_springBone` to move and none
  is written. Hair and cloth sway is its own feature: [sway](sway.md).
- **Clips.** The file has no animations; VRM carries motion separately (VRMA), and a host retargets clips through
  the humanoid.
- **The matcap** of reflective parts and the editor's exact light have no glTF form; MToon's toon shade stands in.
- **Other VRM apps.** The files are read by three-vrm and pass the glTF validator; Unity, Unreal, VSeeFace and
  VRChat are untried.
