# Custom items

A custom item is a garment or prop a creator makes: their own textures painted onto a blank template (format 1.0), or
their own skinned mesh on the avatar rig (format 1.1). It is one file, `.sonaitem`, with an id of its own that a
manifest wears like any item id. The web SDK and the native SDK load the same file and draw it the same. Nothing is
hosted or moderated by 360sona: the app that loads a file decides what it shows. Award items ([Award items from your own game](#award-items-from-your-own-game)) are the
exception: a developer defines them for an app and its signed-in players unlock them into their 360sona wardrobe.

Make one from a template, pack it and look at it, with the `sona` tool ([installing the tools](installer.md)):

```sh
sona item new night-sky --template "Blank tee" --body man --name "Night Sky Tee" --dir "<asset folder>"
cp night-sky/blank.png night-sky/color.png      # your painting goes here: paint color.png over blank.png
sona item pack night-sky --key creator.key      # writes night-sky.sonaitem, signed
sona item check night-sky.sonaitem
sona item preview night-sky.sonaitem -o night-sky.png --dir "<asset folder>" --licence sona-licence.json
```

Load it and wear it. In C, add the file's bytes to the context and put its id in a manifest:

```c
sona_guid id;
sona_manifest m;
uint8_t worn[SONA_MANIFEST_BYTES];
if (sona_custom_item_add(ctx, file, file_len, &id) == SONA_OK &&     /* the bytes of night-sky.sonaitem */
    sona_manifest_parse(manifest, &m) == SONA_OK &&                  /* an avatar's 1,000 bytes */
    sona_manifest_wear(&m, &id, NULL, 0) == SONA_OK &&
    sona_manifest_write(&m, worn) == SONA_OK)
  sona_avatar_add(ctx, worn, NULL, &avatar);                         /* an avatar wearing it */
```

```cpp
const void *file = nullptr; size_t file_len = 0;   // the bytes of night-sky.sonaitem
sona_guid id;
sona::Manifest m;
if (sona_custom_item_add(ctx.raw(), file, file_len, &id) == SONA_OK &&   // sona.hpp has no wrapper: the C call
    sona::Manifest::parse(manifest, m) == SONA_OK &&                    // an avatar's 1,000 bytes
    m.wear(id, nullptr) == SONA_OK) {
  sona::Avatar wearing = ctx.add(m);                                     // an avatar wearing it
}
```

```csharp
var file = File.ReadAllBytes("night-sky.sonaitem");
var id = new Native.sona_guid();
fixed (byte* p = file)
    Native.sona_custom_item_add(ctx.Handle, p, (UIntPtr)file.Length, &id);   // the binding's raw call: no wrapper
var m = SonaManifests.Parse(manifest);                                         // an avatar's 1,000 bytes
SonaManifests.Wear(ref m, id, 0xffffffff, 0xffffffff, 0xffffffff);
var wearing = ctx.Add(SonaManifests.Write(m));                                 // an avatar wearing it
```

```rust
let file = std::fs::read("night-sky.sonaitem").unwrap_or_default();
let mut id: Guid = unsafe { std::mem::zeroed() };
// the crate has no wrapper: the C call through sona_sys
unsafe { sona_sys::sona_custom_item_add(ctx.raw(), file.as_ptr() as *const _, file.len(), &mut id) };
let mut m = Manifest::parse(manifest)?;   // an avatar's 1,000 bytes
m.wear(&id, [0xffffffff; 3], 0)?;
let wearing = ctx.add(&m.to_bytes()?, &AddOptions::default())?;   // an avatar wearing it
```

```python
import ctypes
from sona import _lib   # the package's ctypes layer: it has no wrapper for this call

data = open("night-sky.sonaitem", "rb").read()
item = sona.Guid()
_lib.sona_custom_item_add(ctx._ctx(), data, len(data), ctypes.byref(item))
m = sona.Manifest(manifest)               # an avatar's 1,000 bytes
m.wear(item, colours=(0xffffffff, 0xffffffff, 0xffffffff))
wearing = ctx.add(m.to_bytes())           # an avatar wearing it
```

On the web:

```js
const bytes = await (await fetch('night-sky.sonaitem')).arrayBuffer();
const info = await scene.items.add(bytes);
await avatar.wear(info.id);
```

## At a glance

| Question | Answer |
|---|---|
| Format | A small container of its own, `.sonaitem` |
| What a format 1.0 file holds | A JSON chunk and texture chunks. The template mesh is **referenced**, never copied |
| Texture chunks | The stock texture record, byte for byte (BC1/BC3, word-swapped). Both renderers already read it |
| Id | `MMMMMMMM-xxxx-xxxG-Vxxx-xxxxxxxxxxxx`: the template's slot mask, a body nibble G, a custom marker V in 8..b, 90 random bits |
| Why the id never collides | Every one of the 23,948 known real ids has `c` in that place |
| Slot | The template's mask, always. Wear and eviction rules are the stock ones |
| Fit | Height and weight come from joint scaling. Body hiding comes from the **template's** fit |
| Colour | An optional regions texture plus up to 32 colourways, the stock tint chain |
| UV layout | Stock layouts are mirrored left to right, so text would read backwards on one side. The default `split` layout gives each side its own half of the texture ([textures](#textures)) |
| Manifest | A custom id sits in a worn slot like any item id. The 1,000 bytes do not change |
| API | Web: `scene.items.add/remove/get/list/pack`, `avatar.wear`. Native: `sona_custom_item_*` |
| Templates | 28 blanks from stock and simple DLC meshes ([the 28 templates](#the-28-templates)) |

---

## The file format

### Layout

Binary, little-endian. Extension `.sonaitem`.

| Offset | Size | Field |
|---|---|---|
| 0 | 8 | magic, ASCII `SONAITEM` |
| 8 | 2 | major version, 1 |
| 10 | 2 | minor version, 0 |
| 12 | 4 | file length in bytes |
| 16 | 4 | end of the hashed part (the file length when there is no SIGN chunk) |
| 20 | 4 | chunk count in the hashed part |
| 24 | 8 | zero |
| 32 | 32 | SHA-256 of bytes 64 to the end of the hashed part |
| 64 | to the end | chunks |

A chunk is a four-byte ASCII type, a u32 payload length, the payload, then zero bytes up
to a multiple of 4. The type is four ASCII letters. The chunk count at 20 counts the hashed
part only (SIGN chunks are not in it). Writers put zeros at 24; readers ignore those bytes
and warn.

| Type | Count | Payload |
|---|---|---|
| `JSON` | exactly 1, first | `item.json`, UTF-8 ([item.json](#itemjson)) |
| `TEXR` | 0 to 8 | one texture record ([textures](#textures)) |
| `MESH` | 0 or 1 | a glb, format 1.1 only ([Your own mesh (format 1.1)](#your-own-mesh-format-11)) |
| `SIGN` | 0 to 2, after the hashed part only | u8 kind (1 creator, 2 site), 3 zero bytes, a 32-byte ed25519 public key, a 64-byte signature over the 32-byte hash |
| first letter lowercase, e.g. `thmb` | any | optional. A loader that does not know it skips it |

An unknown type whose first letter is uppercase is critical: the loader rejects the file.
That is the PNG rule, and it is what lets a minor version add things safely.

### item.json

```json
{
  "format": "sona-item/1",
  "id": "00000008-5d1e-4a71-9b3c-2f8e6a0c4d17",
  "version": 3,
  "name": "Night Sky Tee",
  "description": "Stars on the front, a moon on the back.",
  "creator": "kai",
  "created": "2026-11-08",
  "licence": "wear",
  "template": { "id": "00000008-006e-0001-c1c8-f109a19cb2e0", "sha256": "…64 hex…" },
  "surfaces": [ { "layout": "split", "color": 0, "regions": 1, "decal": null } ],
  "colourways": [ ["#1b2a4a", "#e8e8e8", "#c03030"], ["#2b5a1b", "#e8e8e8", "#f0c020"] ]
}
```

| Key | Required | Rule |
|---|---|---|
| `format` | yes | `"sona-item/1"` |
| `id` | yes | [the id](#the-id). Slot and body are read from it; they are not stored twice |
| `version` | yes | integer, 1 or more. Goes up by one each time the creator changes the item |
| `name` | yes | 1 to 48 characters |
| `description` | no | up to 280 characters |
| `creator` | no | a display name, up to 48 characters. Not an account |
| `created` | no | `YYYY-MM-DD` |
| `licence` | no | up to 64 characters. Default `"wear"`: anyone may wear, show and share it; nobody may sell it |
| `template.id` | yes | a real item id (marker `c`), [templates](#templates) |
| `template.sha256` | yes | SHA-256 of the template's STRB bytes, after the YTGR wrapper is taken off |
| `surfaces` | yes | one entry per template surface ([textures](#textures)). `layout` is `"split"` or `"template"`. `color` is a TEXR index; `regions` and `decal` are a TEXR index or null |
| `colourways` | when any surface has regions | 1 to 32 entries, each three `#rrggbb` |
| `mesh` | format 1.1 | [Your own mesh (format 1.1)](#your-own-mesh-format-11) |

Loaders keep unknown keys and ignore them. Writers emit canonical JSON: keys in the table's
order, no whitespace, lowercase hex, so the web and native packers write the same bytes.
Exactly: absent optional keys are left out; `template`
is `{"id","sha256"}`; every surface is written with all four keys in the order `layout`,
`color`, `regions`, `decal` (null when absent); `colourways` is written only when it has
entries; unknown keys follow the known ones, sorted by UTF-16 code unit, and objects inside
them are sorted the same way; strings are escaped as `JSON.stringify` does (`\"`, `\\`, `\b
\f \n \r \t`, other controls as lowercase `\u00xx`, everything else raw UTF-8).

Reading is strict RFC 8259 JSON with two additions every loader shares: a duplicate key is
invalid, and nesting deeper than 32 is invalid. A byte order mark is invalid. Integer keys
(`version`, TEXR indices) are numbers whose value is a whole number (`1.0` reads as 1).
Strings are counted in Unicode code points. `name`, `creator` and `licence` may not hold
control characters (U+0000 to U+001F, U+007F); `description` may hold line feeds.
`version` is at most 2147483647. Colours are lowercase `#rrggbb`.

### The id

An item id is a GUID whose first group is the item-type mask. A custom id keeps that, so every rule that reads a mask works
unchanged. Text form:

```text
MMMMMMMM-RRRR-RRRG-VRRR-RRRRRRRRRRRR
00000008-5d1e-4a71-9b3c-2f8e6a0c4d17     a man's tee
00000008-5d1e-4a72-9b3c-2f8e6a0c4d17     its pair, the woman's tee
```

| Part | Bits | Meaning |
|---|---|---|
| `M` | 32 | the template's mask, e.g. `00000008` shirt |
| `G` | 4 | the body, as in real ids: 1 man, 2 woman, 3 both. Equal to the template's |
| `V` | 4 | 8, 9, a or b. This marks a custom item |
| `R` | 90 | random, from a CSPRNG, made once when the item is created |

Measured on the known ids (the wardrobe, the DLC archive, the catalogue, awards, stock
lists: 23,948 distinct ids):

- the first digit of group 4 is `c` in every one;
- the last digit of group 3 is 1, 2 or 3 in all of them, and it agrees with the wardrobe's gender.

`c` is the GUID variant Microsoft reserved; 8..b is the standard variant. The two cannot
meet. The marketplace is closed, so no new real ids appear. On the 16 wire bytes
(`sona_guid.b`, big-endian order) a custom id has `(b[8] & 0xC0) == 0x80`. A loader rejects any custom
file whose id fails it, so a custom file can never stand in for a real item.

**The pair.** The same id with G swapped between 1 and 2 is the other body's version.
Nothing else links them; no lookup table is needed. Body 3 has no pair.

**Revisions keep the id.** Fixing a typo or repainting a star keeps the id and raises
`version`. "Save as new" makes a new id. A manifest names an id, never a version.

**No account in the id.** The same file works offline and in every SDK.

### Slot and mask

The mask is the template's, always. A long-sleeved top (`0x208`, shirt and wristwear)
evicts wristwear exactly as the stock one does, because `wear()` and `sona_manifest_wear`
read the mask from the id.

| Masks | In format 1.0 |
|---|---|
| shirt 0x8, long-sleeved top 0x208, trousers 0x10, shoes 0x20, headwear 0x40, gloves 0x80 and 0x880, glasses 0x100, wristwear 0x200, earrings 0x400, ring 0x800, prop 0x1000, costumes 0x8000xx | yes |
| hair 0x4 | no. Hair swaps to a different asset under a hat (the dependency table's hair substitution), which would drop the paint. Later |
| face parts 0x2000 to 0x40000 | format 1.1 ([textures](#textures), expressions) |
| nose, chin, ears 0x80000 to 0x200000 | never: they are shapes, with no texture |
| head 0x1, body 0x2, animation 0x400000, shape 0x1000000 | never |

"Costumes 0x8000xx" means the costume bit 0x800000 plus one or more of the garment bits
0x8 to 0x800 (`mask & ~0xff8 == 0x800000`), e.g. 0x800018, 0x800218. Garment bits combined
without the costume bit (0x18, 0x238 ...) are not in format 1.0. `CustomItemInfo.slot` names
the mask: `shirt` (0x8 and 0x208), `trousers`, `shoes`, `headwear`, `gloves` (0x80 and 0x880),
`glasses`, `wristwear`, `earrings`, `ring`, `carryable` (0x1000, the prop) and `costume`,
the names `src/avatar-description.js` already uses.

### Body and fit

A painted item keeps its template's mesh, so it fits every body the template fits.

- **Height and weight** are joint scaling, not mesh edits. The template's skinned vertices follow the
  scaled joints. Nothing to do.
- **Body hiding** is the template's. A garment hides the body triangles under it through
  a ShapeOverride: stock items find theirs in `bin/tocassetdependencies.bin` by the
  garment's own GUID, DLC items carry tag-4 blocks. The loader does those lookups with the
  **template's** id. Measured for the format 1.0 set: the man's long-sleeved tee resolves to
  `01000000-0399-0001-…`, the woman's tee to `01000000-0437-0002-…`, the man's jeans to
  `01000000-03af-0001-…`, each conditioned on the matching body, as for the stock item.
- **Hair under a hat** is keyed on the worn masks (`test dil, 0x40`), so a custom hat
  lowers the hair with no extra work.
- **Gender.** One body per item, from the id. `setGender` already removes items made for
  the other body by reading the nibble. An app that knows which items are loaded can wear
  the pair instead (`pairOf`).
- Every other lookup by id also goes to the template: prop clips and prop skeletons (tag 1
  and tag 5), the disc bind-pose test, aliases. Only the textures and the colour table come
  from the item.

### Colour regions

The stock tint chain, unchanged:
`colour = lerp(color, r*C1 + g*C2 + b*C3, a)`, with r, g, b, a from the regions texture.

- **Regions texture**: red, green and blue say how much of colour 1, 2 and 3 a texel takes;
  alpha says how much tint replaces the painted colour. Optional, per surface.
- **Colourways**: up to 32 triples. The loader turns them into a ColorTable in the same
  order (entry 0 is the default). Note that `Data/ColorSets.json` runs the other way round;
  ours does not.
- **The manifest** stores the chosen colourway in the worn slot's three colours, as for
  stock items. A manifest whose colours match no entry gets entry 0, the stock rule
  (`selectColorway`).
- No regions: no tint. The item looks exactly as painted, and colourways are ignored.

### Textures

A template has **surfaces**: the distinct textures its batches bind as colour (usage 1), in
the order the batches first bind them. Every format 1.0 template has one surface. The glasses' frame
and lens share one. A two-surface template (a guitar) would need two colour textures.

Each surface gets these textures from the item:

| Role | Format, size | Becomes |
|---|---|---|
| `color` | BC1 (DXT1), opaque, 64 to 512 | usage 1, colorTex |
| `regions` | BC3 (DXT5), 32 to 512 | usage 2, intensityTex. Removed when null |
| `decal` | BC3 (DXT5), 32 to 512 | usage 3, decalTex, drawn over the tinted colour (`lerp(c, decal, decal.a)`). Removed when null. Not on reflective surfaces, whose third texture is the env map |

Sizes are powers of two, and width and height may differ (stock shoes are 128x64). Stock
colour textures are 64x32 to 256x256; 512 gives sixteen times the stock texels. There are
no mips in the file; the renderers make them, as for stock. A renderer may downsample a
custom texture to its budget: a side of 512 for scenes of up to 32 avatars, 256 up to 256 avatars, 128 beyond.

**One UV layout per surface.** Stock garments sample colour on UV layer 0, the tint mask on
layer 1 and the decal on layer 2. On printed items the three differ (the football tee's
decal layer runs from u -0.24 to 2.05). In format 1.0 every custom texture of a surface uses
one layout, built from the template's colour layer. A painter works on one picture.

**Stock layouts are mirrored.** Measured on all 28 templates: on the 26 garments, half or more of the triangles share texels with a triangle on
the other side of the body (twins, or a tiled layout repeating across both sides, as on the
beanie and the knit hat). Paint "HELLO" on the chest of the stock layout and one side reads
backwards. The flag and the banner are not mirrored; the two props' back faces
share the front's texels instead, as a real flag does. So a surface picks one of two layouts:

| `layout` | What it is | Texture shape |
|---|---|---|
| `split` | Each side of the body gets its own half of the texture. Asymmetric designs and text work. The tools' default for mirrored templates | twice the template colour texture's aspect, so texels stay square on the body: 512x256 for a 128x128 template, 512x128 for 128x64 |
| `template` | The template's own colour layout, as it is. The default for the two props, and fine for symmetric designs and patterns | any |

The split layout is a fixed function of the decoded template asset, computed the same way by
the kit and by both loaders. All
arithmetic is in double on the decoded float32 positions and half-float UVs, and the results
are stored as float32, so a port doing the same gets the same bits.

1. A triangle's side is the sign of x0 + x1 + x2 in the template's bind pose: below 0 is side
   0 (the avatar's right, the texture's left half), else side 1. x = 0 is the avatar's mirror
   plane, and every template is symmetric about it.
2. The colour layer is shifted by one offset per axis, k/64 for the k in 0..63 that leaves the
   fewest triangles crossing a whole-number line (ties: the smallest k). Each triangle then
   loses its whole-number cell, the floor of its smallest corner. A triangle that still crosses
   a line (a tiled layout) uses the cell of its centroid and has its corners clamped to 0..1.
3. With h = 0.5 - 1/64, side 0 goes to u * h, side 1 to 1 - u * h; v is kept. The halves keep a
   gutter of 1/32 of the width between them (16 texels at 512 wide, clamped straddlers
   included), so one side's bleed and filtering never reach the other. Where the template
   mirrors one side onto the other, both sides then run the same way on the body.
4. Each side on its own, judged on its front-facing triangles (mean vertex normal z below
   -0.5; the avatar faces -z), area-weighted in the front view: if a design would read
   mirrored, u is replaced by 1 - u before step 3; if it would then read upside down, u and v
   are both replaced by 1 - value (a half turn). Each choice is a signed sum of triangle
   weights (the triangle's front-view area); it flips only when the sum is below -2^-10 times
   the side's total weight, so a near-tie gives the same answer in any port (no flip). Lengths
   use sqrt, not hypot. Per side, because some templates mirror only part of the garment (the
   long-sleeved tee's front panels are not twins). Quarter turns are not corrected: on the
   man's tee the chest islands lie sideways in the texture, so the guide draws an up arrow on
   each island ([the template kit](#the-template-kit)).
5. A vertex used with two different results (both sides, two wrap cells) is duplicated; new
   vertices are numbered in the order the triangles first use them, walking the surface's
   batches, triangles and corners in order. This only touches the garment's own vertices;
   ShapeOverrides patch the body, not the garment.
6. Split textures are sampled with clamp addressing, and the kit gives 4 pixels of bleed, so the two sides never
   touch.

The loader writes the layout's UV into all six UV pairs of the runtime vertex (`applyLayout`),
so every binding of the surface samples it whatever layer its param names.

The loader rewrites the bindings:

| Template binding | In the custom item |
|---|---|
| usage 1 colour | the surface's `color`, on the surface's layout |
| usage 2 tint mask | `regions` on the same layout, or no binding |
| usage 3 decal | `decal` on the same layout, or no binding |
| usage 4 env map | the template's |
| constants (usages 13 to 27) | the template's. 22, 23 and 24 are set from the colourway, as for stock |
| ColorTable | built from `colourways`, or none |

Removing a binding is safe: the shader variant is chosen from the bindings present. Stock garments' tint
masks are nearly transparent, but not all fully (the man's tee and both gloves have some); the flag's tint mask is
its colour texture. Where the mask is fully transparent, removing it changes no pixel; on the other templates it
may shift colours slightly.

**The TEXR chunk is the stock record.** The 33-byte bit header that `readTextureRecord` and `sona_read_tex_record` already parse: format tag
(`0x1a200052` BC1 or `0x1a200054` BC3), width, height, two u32 written as 0 (the stock
reader discards them), slice count, stub bit 0, one zero bit, pitch, rows. Then the blocks,
every 16-bit word swapped (the Xbox order). The odd layout is deliberate: the readers need
no new texture code.

**Expression textures.** Face parts (eyes, mouth, eyebrows) are one texture with a slice per
expression: 14 for eyes and mouth, 5 for eyebrows. The record already has a slice count. Format 1.1 adds face
templates and allows those masks; nothing else changes.

### Versions

- **Container.** Major 1 changes only by breaking. A loader accepts every minor of its
  major. Minors add optional chunks, optional keys, or critical chunks a newer feature needs
  (`MESH` is the first). A 1.0 loader rejects a file with `MESH` ("needs a newer SDK"), which
  is right: drawing the template instead would be wrong. A 1.1 loader reads it under rule 13 ([Your own mesh (format 1.1)](#your-own-mesh-format-11)).
- **Item.** `version` plus the file hash identify one revision. When two files with the same
  id are loaded, the higher version wins. The same version with a different hash is refused.
- **Template.** Pinned by id and SHA-256. Stock items do not change, so a mismatch means a
  wrong or damaged template file. Loaders warn and still build; the Studio shows it.

### Integrity and signatures

- The header hash covers every chunk before the SIGN chunks. A loader checks it before it
  reads anything else. It catches damage, not tampering.
- A `SIGN` chunk of kind 1 is the **creator's** ed25519 signature over that hash. The CLI
  makes a creator key on first use (`~/.sona/creator.key`) and signs by default.
- A `SIGN` chunk of kind 2 is **360sona's**, for items the site itself publishes.
- Signatures sit outside the hashed part, so adding one never changes the hash.
- Native already verifies ed25519 for licences. The web
  uses WebCrypto Ed25519. An unsigned file is valid.

### Limits of format 1.0

| Thing | Limit |
|---|---|
| File | 4 MiB |
| JSON chunk | 64 KiB |
| TEXR chunks | 8 |
| Texture side | 32 to 512 (colour at least 64), power of two |
| Slices | 1 (faces in 1.1: 14 or 5) |
| Colourways | 32 |
| Surfaces | as many as the template has, at most 8 |
| `name` / `creator` / `description` / `licence` | 48 / 48 / 280 / 64 characters |

A paint item has a limit of 4 MiB and is typically far under it: its size is its textures', and a BC3 texture is
twice a BC1 texture of the same pixels.

### What a loader must reject

Checked in this order, before any allocation sized by the file:

1. Under 64 bytes, wrong magic, major not 1, length field not the file length, a file over the
   4 MiB limit.
2. Hash mismatch.
3. A chunk running past the hashed end, a chunk length that is not padded to 4, a chunk
   count that disagrees, anything but SIGN chunks after the hashed end.
4. No JSON chunk, JSON not first, a second JSON chunk, JSON over the 64 KiB limit, invalid UTF-8,
   invalid JSON, `format` not `sona-item/1`.
5. An unknown critical chunk type.
6. An id that is not a lowercase 8-4-4-4-12 GUID, or whose marker is not 8..b.
7. A mask outside the 1.0 list, or a body nibble not 1, 2 or 3.
8. A template id that is itself custom (no chains), or has a different mask or body
   nibble than the item.
9. A texture record that `readTextureRecord` refuses; a format other than BC1 for
   `color` or BC3 for `regions` and `decal`; a size outside the limits; more than one slice;
   the stub bit set; a record that does not end exactly at the chunk's end.
10. A `surfaces` entry pointing at a missing TEXR, a TEXR used twice or not at all,
    regions without colourways, more than 32 colourways, a colour that is not `#rrggbb`.
11. A SIGN chunk that does not verify.
12. After the template has loaded: a surface count that differs from the template's, or a
    decal on a reflective surface. The item is then kept but cannot be built; avatars treat
    it as missing ([Threads, memory and errors](#threads-memory-and-errors)).

Not reasons to reject, but reported as warnings: a template hash mismatch, a texture smaller
than the template's own, unknown optional chunks and keys.

What each rule covers exactly. Within a rule the
checks run in the order listed; the first failure is the answer. The result family is the
native code: corrupt unless marked *limit* or *unsupported*.

| Rule | Also covers |
|---|---|
| 1 | major above 1 is *unsupported*, 0 is corrupt; over the 4 MiB limit is *limit*; the hashed end (16) below 64 or past the file |
| 3 | a chunk header that does not fit; a type that is not four ASCII letters; a non-zero padding byte; a SIGN chunk inside the hashed part; more than 2 SIGN chunks |
| 4 | JSON over the 64 KiB limit is *limit*; a byte order mark; not an object; then, after `format`: `id` not a string, `version` not an integer 1 to 2147483647, `name` missing or empty, a string key over its length (*limit*) or holding a control character, `created` not a `YYYY-MM-DD` date, `template` not an object with `id` and `sha256` strings, `surfaces` not an array, `colourways` present and not an array |
| 5 | an unknown critical chunk: *unsupported* ("needs a newer SDK"). From format 1.1 `MESH` and the `mesh` key are known and checked under rule 13 |
| 13 | after rule 11, the item's own mesh ([the glb profile](#the-glb-profile)): a second `MESH` chunk, `MESH` without `mesh` or `mesh` without `MESH`, `mesh` not an object, `chunk` not 0, `rig` not a string, a `rig` this SDK does not know (*unsupported*), a carryable not on `sona-prop/1` or another slot not on `sona-rig/1`, `fit` not `template` or `none`, `primitives` empty or not an array, over 16 (*limit*), an entry without a batch 0 to 31 or a surface index, a surface whose layout is not `template`; then the glb profile |
| 7 | a mask outside the list is *unsupported* |
| 8 | in order: a template id that is not a lowercase GUID, is custom, has a marker other than `c`, has another mask, has another body; `template.sha256` not 64 lowercase hex digits |
| 9 | more than 8 TEXR (*limit*); per TEXR in order: under 33 bytes or refused by `readTextureRecord`; a tag other than exactly `0x1a200052` or `0x1a200054` (*unsupported*; the `0x1a2001xx` variants too); the stub bit; slices not 1 (*unsupported*); a record that does not end at the chunk's end; a side not a power of two in 32 to 512 (*limit*). Then per surface, for each index that names an existing TEXR: the wrong format for the role, and a colour side under 64 (*limit*) |
| 10 | no surfaces; more than 8 (*limit*); a surface that is not an object; `layout` missing or not `split`/`template`; `color` not an integer index of a TEXR; `regions`/`decal` present, not null and not an index; a TEXR used twice or not at all; regions with no or empty colourways; `colourways` present and empty; more than 32 (*limit*); an entry that is not three lowercase `#rrggbb` strings |
| 11 | a SIGN payload whose size is not the set 100 bytes; a kind other than 1 or 2; non-zero bytes 1 to 3; a second signature of the same kind; a signature that does not verify over the header hash |

---

## Templates

### The 28 templates

Measured from the STRBs (stock items from `pack/` on the NAS, props from `dlc/`). "Colour" is
the stock texture's size; a split texture of the same detail is twice as wide. "Fit" is the
dependency-table Shape the template brings; "none" means it hides no body.

- Blank tee (shirt, man): item `00000008-006e-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-042a-0001`.
- Blank long-sleeved tee (shirt, man): item `00000008-0060-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0399-0001`.
- Blank vest (shirt, man): item `00000008-0065-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-041a-0001`.
- Blank sweater (long-sleeved top, man): item `00000208-0046-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0373-0001`.
- Blank hoodie (long-sleeved top, man): item `00000208-0045-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0397-0001`.
- Blank jeans (trousers, man): item `00000010-00a0-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-03af-0001`.
- Blank shorts (trousers, man): item `00000010-009a-0001-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-03a5-0001`.
- Blank sneakers (shoes, man): item `00000020-0037-0001-c1c8-f109a19cb2e0`, colour 128x64, fit `01000000-03b5-0001`.
- Blank cap (headwear, man): item `00000040-00e4-0001-c1c8-f109a19cb2e0`, colour 128x64, fit none.
- Blank beanie (headwear, man): item `00000040-00e9-0001-c1c8-f109a19cb2e0`, colour 128x64, fit none.
- Blank gloves (gloves, man): item `00000880-04ef-0001-c1c8-f109a19cb2e0`, colour 128x64, fit `01000000-0412-0001`.
- Blank glasses (glasses, man): item `00000100-00ca-0001-c1c8-f109a19cb2e0`, colour 64x32, fit none.
- Blank tee (shirt, woman): item `00000008-011f-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0437-0002`.
- Blank V-neck tee (shirt, woman): item `00000008-0123-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-041e-0002`.
- Blank sweater (long-sleeved top, woman): item `00000208-0124-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0389-0002`.
- Blank turtleneck (long-sleeved top, woman): item `00000208-0126-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0388-0002`.
- Blank jeans (trousers, woman): item `00000010-0158-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-035c-0002`.
- Blank skirt (trousers, woman): item `00000010-016a-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-0352-0002`.
- Blank shorts (trousers, woman): item `00000010-0162-0002-c1c8-f109a19cb2e0`, colour 128x128, fit `01000000-03fb-0002`.
- Blank trainers (shoes, woman): item `00000020-00fc-0002-c1c8-f109a19cb2e0`, colour 128x64, fit none.
- Blank boots (shoes, woman): item `00000020-0106-0002-c1c8-f109a19cb2e0`, colour 128x64, fit `01000000-03ee-0002`.
- Blank cap (headwear, woman): item `00000040-0197-0002-c1c8-f109a19cb2e0`, colour 128x64, fit none.
- Blank knit hat (headwear, woman): item `00000040-0199-0002-c1c8-f109a19cb2e0`, colour 128x64, fit none.
- Blank gloves (gloves, woman): item `00000880-03d7-0002-c1c8-f109a19cb2e0`, colour 128x64, fit `01000000-0408-0002`.
- Blank glasses (glasses, woman): item `00000100-00da-0002-c1c8-f109a19cb2e0`, colour 32x32, fit none.
- Blank dress (costume (shirt and trousers), woman): item `00800018-0171-0002-c1c8-f109a19cb2e0`, colour 256x128, fit `01000000-0377-0002`.
- Blank flag (prop, both): item `00001000-504c-c233-cb47-f3fe444d07d7`, colour 256x256, fit none.
- Blank banner (prop, both): item `00001000-04f9-3213-cc06-5fab4b4e0824`, colour 128x64, fit none.

Each fit is the template's own, for the matching body (all shown with the `-c1c8-f109a19cb2e0` suffix dropped).
Headwear, glasses, the woman's trainers and the props have none. Some templates are poor to paint and say so in
their notes: both caps, the beanie and the knit hat have tiled layouts, shoes share texels between inner and outer
sides, and the glasses fold inner and outer frame. The flag binds one texture as both colour and tint mask
with the identity colour table, so removing the tint binding leaves its look unchanged; its
second batch is confetti and shares the texture. Both props keep their template's clip and
skeleton.

An item with its own mesh (format 1.1) draws only that mesh, never its template's, so any template of the right slot
serves; the flag and the banner are the prop templates.

### The template kit

`sona item kit <template> <dir>` makes the kit on the creator's machine. It reads
the template through the developer's own SDK access (the gate, or an asset folder with
`--dir`). No kit file is hosted by 360sona, so nothing derived from Microsoft's meshes is
distributed by us.

| File | What it is |
|---|---|
| `uv.png` | The UV guide, split layout, twice the recommended split texture (1024x512 for a 512x256 texture, 1024x256 for 512x128), so lines stay sharp. Islands in light grey, triangle edges in dark grey, seams in magenta (an island edge that continues into another island on the body, so paint does not flow across it), the garment's own borders (hems, cuffs) near-black, a blue 4-pixel bleed outline, and each island labelled by where it sits on the body (front left, back right, left sleeve, inside...), worked out from its area-weighted normal and position, with an arrow before the label pointing to body up in the texture (left out where up lies under 0.35 along the island's surface, as on a hat's crown); a label that does not fit its island is left out. Paint text along the arrow: on some templates (the man's tee) an island lies sideways. Texels two triangles still share (inner and outer faces, tiled layouts) are hatched |
| `uv-template.png` | The same for the `template` layout (wrap kept), with the texels both sides share hatched |
| `blank.png` | as above, same size as `uv.png` |
| `blank-template.png` | the blank on the `template` layout, same size as `uv-template.png` |
| `preview.png` | with `--preview`: the blank on the default layout, worn on the default body, front and back (1024x512; needs a headless Chromium) |
| `template.json` | id, SHA-256, slot, body, surfaces (UV layer, size, batches, decal allowed, recommended split and template sizes), the default layout, the fit, the split layout's gutter, offset and flips, and the joints the mesh uses (for format 1.1) |
| `template.glb` | format 1.1: the template alone on the rig (`sona-item template-glb <template> <out.glb> --dir "<asset folder>"`; `glb.js templateGlb`): the 71 joints with their names and inverse binds (a carryable: its own skeleton, `prop_NN`), one primitive per batch with a colour texture, a plain image per surface to paint over. Blender 4.5 imports and exports it as it is ([How a mesh item loads](#how-a-mesh-item-loads)) |

`sona item templates` lists every template: id, name, slot, body, colour size, split size and default layout. The
default layout is a rule: `split` for every garment, `template` for the props. The kit refuses a template whose
SHA-256 is not the pinned one, since its guide would not match what the loaders compute; `--force` draws it
anyway.

---

## Painting an item

What a creator does:

1. **Pick a template and get the kit.** `sona item new night-sky --template "Blank tee"
   --body man --name "Night Sky Tee"`. This makes a fresh id, writes
   `night-sky/item.json` and the kit beside it. `--pair` also makes the woman's version, with
   the paired id and her template.
2. **Paint.** Open `blank.png` in any paint program, paint over it with `uv.png` as a layer
   on top, save as `color.png`. Optionally paint `regions.png` (red, green and blue areas
   for the three colours) and `decal.png` (a print with transparency).
3. **Preview live** (below).
4. **Pack.** `sona item pack night-sky` checks everything, encodes the
   textures, signs with the creator key, and writes `night-sky.sonaitem`.
5. **Use it.** A developer loads the file with `scene.items.add(bytes)` or
   `sona_custom_item_add`, and wears the id.

The source folder:

```text
night-sky/
  item.json       as 1.3, but surfaces name files: { "color": "color.png", "regions": "regions.png" }
  color.png       per surface; color-2.png for a second surface
  regions.png     optional
  decal.png       optional
  uv.png  blank.png  preview.png  template.json    the kit
```

The CLI, `sona item`:

| Command | Does |
|---|---|
| `new --template <id or name> --body <man/woman/both> --name <text> [--pair] <dir>` | a fresh id, `item.json` and the kit. `--pair` writes the other body's folder as `<dir>-woman` (or `-man`) |
| `kit <template> <dir>` | only the kit |
| `pack <dir> [-o file] [--no-sign] [--key file]` | check, encode, sign, write (default `<dir>.sonaitem`). Raises `version` if the folder was packed before with different content (pixels or item.json); the last pack is remembered in `<dir>/.sonaitem-pack.json` |
| `check <file> [--deep] [--json]` | the loader's verdict and every warning. `--deep` loads the template too: its hash, rule 12, textures smaller than the template's. Exit 0 ok, 1 refused or unbuildable |
| `unpack <file> <dir>` | the folder form back (textures decoded to PNG) |
| `preview <dir or file> -o shot.png [--grid]` | a render; `--grid` is the 3x3 body grid (weight -0.5/0/+0.5 by height -0.5/0/+0.5). |
| `id --template <id>` | a fresh id only |

Templates are read from a folder of avatar files (`--dir`, else `$SONA_ITEM_DIR` or `$SONA_CORPUS`). The creator
key is a PKCS#8 PEM ed25519 key: `--key`, else `$SONA_CREATOR_KEY`, else `~/.sona/creator.key`, made on the first
signed pack.

**Pack then unpack then pack gives the same bytes.** `unpack` stores each texture's record in
a private PNG chunk, `soBC`. `pack` reuses that record only when it decodes to exactly the
PNG's pixels, so an untouched texture keeps its blocks and a repainted one is encoded fresh.
Ed25519 signatures are deterministic, so the signed file repeats too.

**Pack checks, beyond the loader's rules:** PNG sizes are powers of two and inside the limits;
colour has no transparent pixels (it is flattened onto white, with a warning);
a texture smaller than the template's is a warning. The encoder is integer-only BC1/BC3
(J.M.P. van Waveren's real-time DXT method), so the JS and C packers write the same bytes.

The encoder, exactly (every packer must match it bit for bit):

- Blocks run left to right, top to bottom; a texel past the image edge repeats the last
  row or column. Blocks are written little-endian, then `write.js` swaps every 16-bit word
  for the record.
- Colour (BC1, and the colour half of BC3): per channel min and max over the 16 texels.
  Candidate A is the box inset by `(max - min) >> 4` per channel (max minus it, min plus it);
  candidate B is the plain box. Each gives `c0 = 565(max)`, `c1 = 565(min)` with
  `565(r,g,b) = (r>>3)<<11 | (g>>2)<<5 | b>>3`. Its palette is the decoded endpoints
  (5 bits `x<<3|x>>2`, 6 bits `x<<2|x>>4`) and `(2*e0+e1+1)/3`, `(e0+2*e1+1)/3` per channel
  (integer division); when `c0 == c1` the palette is only `e0` and every index is 0. Each
  texel takes the entry with the least squared RGB distance, the lower index on a tie. B
  replaces A only when its summed squared error is strictly lower. `c0 >= c1` always, so a
  BC1 block is never in three-colour mode.
- Alpha (BC3): `a0` = max, `a1` = min, no inset. Equal: every index 0. Otherwise the eight
  entries are `a0`, `a1` and `(2*((7-i)*a0 + i*a1) + 7) / 14` for i = 1..6; nearest by
  absolute difference, lower index on a tie.
- Colour is flattened onto white first: `(c*a + 255*(255-a) + 127) / 255`.

**The Items page.** The SDK Explorer (`devsdk.html`, Tools, Items) makes an item in the browser with the web SDK, on
localhost only: pick a template, give it the PNGs, add colourways, "Pack and preview", "Save item". It also loads a
`.sonaitem` to look at.

**The live preview.** "Watch a folder..." on that page watches `color.png`, `regions.png`, `decal.png` and `uv.png`
(File System Access) and repacks in the browser when the paint program saves. The avatar rebuilds in place.
Controls: a turntable, the 3x3 body grid, the colourway picker, the other body beside it, and a UV overlay that
draws the guide onto the model.

---

## Loading

### How a manifest names a custom item

A manifest's worn slot is a 32-byte AssetRef: the GUID, a u16 mask (the low half of the
GUID's first group), two pad bytes and three colours. A custom id goes into the GUID like
any item id. The u16 mask is written the stock way. The three colours are the chosen
colourway. Nothing else changes, and `write(parse(x)) == x` still holds.

The template id is **not** in the manifest. A viewer needs the item file to draw it.

### What the loader does

Both renderers, the same steps:

1. `add` checks the file ([What a loader must reject](#what-a-loader-must-reject), rules 1 to 11) and keeps the bytes. Cheap; nothing is decoded.
2. When an avatar wearing the id builds, the library sees the custom marker and does **not**
   ask any source for that id. Custom ids never reach the bridge or the gate.
3. It loads the template through the normal path (`lib.asset(templateId)` /
   `sona_library_asset`), then makes the custom asset: the template's parts are shared
   untouched; the batch params are copied and rewritten ([textures](#textures)); the item's texture records
   are appended to a copy of the template's texture table; the colour table is built from
   the colourways.
4. Dependency lookups (fit, hair under hats) and clip and skeleton lookups use the
   template id ([Body and fit](#body-and-fit)). Everything else is the stock build.
5. Decoded textures and tint bakes are cached per (item revision, colourway), as the stock
   memo does (`buildMaterial`'s cache).

### Web SDK calls

Each scene has its own custom items, `scene.items`; an avatar wears one by id like any item. The declarations, with
every field, are in the web SDK reference's [custom items](../reference/web.md#custom-items) part.

| Call | What it does |
|---|---|
| `scene.items.add(file)` | Checks a `.sonaitem` and keeps it; avatars wearing its id rebuild. Resolves its `CustomItemInfo`; rejects with `SonaError` `item`, whose `fix` names the rule |
| `scene.items.remove(id)`, `get(id)`, `list()` | Forget one, read one, read them all |
| `scene.items.pack(spec)` | Makes a `.sonaitem` from pixels (`PackSpec`: the template, a picture per surface, the colourways) |
| `SonaRenderer.checkItem(file)` | The checks of rules 1 to 11, with no network: `{ ok, rule, why, info }` |
| `SonaRenderer.newItemId(templateId)`, `isCustomId(id)`, `pairOf(id)` | A fresh id for a template; is an id custom; the other body's id |
| `avatar.wear(id)`, `avatar.unwear(slot)`, `avatar.missingItems` | Wear or take off an item, stock or custom; the custom ids it wears that are not loaded |

`scene.glb()` and `scene.snapshot()` include custom items; the glb's credit lists each item's name and creator beside
"Powered by 360sona".

```js
const file = await (await fetch('night-sky-tee.sonaitem')).arrayBuffer();
const info = await sona.items.add(file);
await avatar.wear(info.id);
```

### Native calls

The calls are in `sona.h`; the declarations and every field of `sona_custom_item_info` and `sona_paint_spec` are in the
[C reference: custom items](../reference.md#custom-items).

| Call | What it does |
|---|---|
| `sona_custom_item_check` | The checks of rules 1 to 11, with no context and no network: `SONA_OK` and the item's info, or the result and the rule in `why` |
| `sona_custom_item_add` | Checks the file, copies it into the context and gives its id; avatars wearing the id rebuild |
| `sona_custom_item_remove`, `_count`, `_get`, `_find` | Forget one, count them, read one by index or by id |
| `sona_custom_item_new_id`, `sona_guid_is_custom`, `sona_guid_pair` | A fresh id for a template; is an id custom; the other body's id |
| `sona_custom_item_pack` | Pixels in (`sona_paint_spec`), a `.sonaitem` out: the same bytes as `scene.items.pack` for the same input |
| `sona_avatar_missing_items` | The custom ids an avatar wears that no file supplied |

Wearing needs nothing more: `sona_manifest_wear` routes by the id's slot. `sona_manifest_ready_for_xbox` returns 0
while a custom id is worn. The catalogue holds stock and DLC items only. `sona_item_preview_add` takes a custom id.

```c
sona_guid id;
sona_custom_item_info info;
char why[256];
if (sona_custom_item_check(bytes, len, &info, why, sizeof why) != SONA_OK)
  fprintf(stderr, "refused: %s\n", why);
else
  sona_custom_item_add(ctx, bytes, len, &id);   /* avatars wearing id rebuild */
```

### Threads, memory and errors

| Question | Answer |
|---|---|
| Which thread | The ctx's thread for `add`, `remove` and `pack`, as `sona_avatar_add`. `check`, `is_custom`, `pair` and `new_id` are pure and thread-safe |
| Blocking | `add` checks and copies only (well under a millisecond, even for the largest files). Decoding happens in the build budget |
| Lifetime | The caller's bytes may be freed when `add` returns. Info strings are copies |
| Memory | Item bytes count against `budget.assets`. Decoded textures share the asset cache and its eviction |
| An avatar wears an id that is not loaded | Required slots (shirt, trousers, shoes) show the body's default garment; other slots show nothing. The id stays in the manifest and appears in `missingItems`. When the item is added later, the avatar rebuilds by itself |
| The item is loaded but its template is missing or rule 12 fails | The same fallback, and the info has the `UNBUILDABLE` flag with the reason in the log |
| Removing an item worn by avatars | They rebuild with the fallback |
| Two scenes or two ctxs | Each has its own registry |
| Errors | Web: `SonaError('item')` with `fix`. Native: the result code, `why`, and `sona_last_error` |

---

## Your own mesh (format 1.1)

The creator starts from a template's `template.glb` (`sona-item template-glb`, [the template kit](#the-template-kit)), remodels or replaces
the garment in Blender keeping it skinned to the rig, paints its textures, and exports a glb with the textures
inside it. `sona-item mesh` (or `scene.items.packMesh`, or `sona_custom_item_pack_mesh`) checks it and packs it:
each primitive's base colour PNG becomes a BC1 `TEXR`, the glb is rewritten canonically into a `MESH` chunk.
This is format 1.1; what follows is what the three packers and both loaders do.

### What format 1.1 adds

```json
"mesh": {
  "chunk": 0,
  "rig": "sona-rig/1",
  "fit": "template",
  "primitives": [ { "batch": 0, "surface": 0 }, { "batch": 0, "surface": 1 } ]
}
```

| Key | Rule |
|---|---|
| `chunk` | always 0 (one `MESH` chunk) |
| `rig` | `sona-rig/1`: the 71-joint avatar rig, joints named as the glb export names them (`sona_joint_name`: the humanoid names, `shape_NN` for the rest, or `joint_NN`). `sona-prop/1`: a carryable's own skeleton, joints `prop_00` to `prop_71` by index. A carryable (mask 0x1000) is always on `sona-prop/1`, every other slot on `sona-rig/1` |
| `fit` | `"template"`: the template's body hiding, with the coverage check ([Body shapes and the coverage check](#body-shapes-and-the-coverage-check)). `"none"`: hide nothing; the template is left out of the dependency lookups, so the whole body draws |
| `primitives` | one entry per glb primitive, in order: `batch` is the template batch (0 to 31) that lends it its shader family, constants and wrap; `surface` the surface whose textures it draws with |

Every surface of a format 1.1 item has `"layout": "template"`: the glb's own `TEXCOORD_0` is the layout. The template is
still required: it gives the slot, the body, the fit, the shader params and, for props, the skeleton and clip. The
packers take `batch` from the template's first batch with a colour texture (the SDK packer can name one per
primitive). Textures stay in `TEXR` chunks; the `MESH` glb holds no images.

`MESH` and `mesh` are known chunk and key from 1.1 on, so a 1.0 loader still refuses the file (rule 5); a 1.1
loader checks them under rule 13, after the signatures. The minor version in the header is not a gate (a format 1.1 file
whose header says minor 0 is read; the packers write 1).

### The glb profile

| Thing | Rule |
|---|---|
| Container | glTF 2.0 binary: the JSON chunk, then the BIN chunk, nothing else; JSON with a limit of 256 KiB (*limit*), valid UTF-8, strict (a duplicate key, nesting past 32: refused); `MESH` with a limit of 2 MiB (*limit*) |
| Not allowed | `extensionsRequired`, animations, cameras, images, textures (a packer's input may hold images and textures), morph targets and weights, a node camera |
| Buffers | exactly one, the BIN chunk (no `uri`), `byteLength` at most the chunk |
| Mesh and skin | one mesh of 1 to 16 primitives (*limit* over 16), as many as item.json lists; exactly one node holds it, skinned with skin 0; one skin, 1 to 71 joints (a prop's 72), each a distinct node whose name is a joint of the item's rig, no rig joint twice; `inverseBindMatrices` a float MAT4 per joint |
| Per primitive | triangles (`mode` 4 or none); attributes exactly from `POSITION` float VEC3, `NORMAL` float VEC3, `TEXCOORD_0` float VEC2, `JOINTS_0` u8 or u16 VEC4, `WEIGHTS_0` float or normalized u8/u16 VEC4 (all five required), `COLOR_0` float or normalized u8/u16 VEC3/VEC4 (optional: greyscale baked occlusion, white when absent); `indices` u8, u16 or u32; every accessor in its bufferView, the bufferView in the buffer, `byteStride` 4 to 252 and a multiple of 4; one accessor never used as two types; all attributes as long as `POSITION`; whole triangles |
| Size | at most 32,768 vertices a primitive, 16,000 vertices (distinct `POSITION` accessors) and 24,000 triangles in all (*limit*) |
| Data | every index inside its primitive; positions, normals, uvs, colours and inverse binds finite; weights not negative, summing to 1 within 0.01; every joint index inside the skin |
| Against the rig | each joint's inverse bind within 1e-4 of the rig's (the avatar rig's from `avatar-rig.json`, a carryable's own skeleton's), in glTF's space: refused at pack with "parent it to the rig from the template kit". The pure checker cannot see the rig; the packers check it |

Families: everything is *corrupt* but the size limits (*limit*) and a `rig` this SDK does not know (*unsupported*).
The web and native readers run the same checks in the same order and give the same verdict, rule and family.

**The canonical glb.** The packers rewrite the creator's glb (`glb.js canonicalGlb`, `mesh_item.c canonical_glb`):
every node with its name, children and transforms, the one mesh and skin, and one tightly packed bufferView per
accessor used, in first-use order; images, materials, samplers, extras and extensions dropped. Floats in the JSON
(node transforms, `POSITION` min and max) are copied as their source text, so the two packers write the same bytes
without printing a float. The canonical glb of a canonical glb is itself.

### Body shapes and the coverage check

- **Weight to the joints the template uses.** Body shapes are joint scales, so a vertex weighted only to a spine
  joint misses the belly scaling the template's vertices get. The SDK and CLI packers warn when the mesh is
  weighted to joints the template never uses, or skips ones it does.
- **The coverage check** (fit `"template"`). The body triangles the template hides are the ones its fit collapses.
  A ray from each one's centre along its outward normal (the mean of its vertex normals) must meet the item's mesh,
  between a fixed 2 cm inside the skin and a limit of 50 cm out; misses are holes you could see through, and the pack
  fails with their count ("pack with fit none" is the way out). Every stock template passes its own check, and each
  template's mesh cut to its upper half is refused, by both packers.
- What a format 1.1 item draws on bodies of every shape is the stock build's: the mesh is skinned to the same palette.

### How a mesh item loads

The mesh replaces the template's parts, one part per primitive :
positions and normals back in the editor's space (z negated, the winding turned back: the exact inverse of
the glTF export), only the vertices each primitive's triangles use, in first-use order; joints as rig (or prop
skeleton) indices; weights as bytes summing to 255 (each `floor(w * 255 / sum + 0.5)`, the remainder on the
largest); the vertex colour as bytes; the one uv set in all three runtime layers. Each part takes its template
batch's id and params: the colour binding to the item's texture on uv layer 0 with the batch's own wrap, regions
and decal to the item's or dropped, the template's other bindings (the reflective families' environment map) and
constants kept. The fit comes from the template (or none). Everything else is the format 1.0 path: the item's texture
records after the template's, keyed by the revision; rule 12 when a primitive names a batch the template does not
have or one with no colour texture.

### The mesh calls

- Web: `scene.items.packMesh({ template, glb, name, id?, version?, description?, creator?, created?, licence?, fit? })`
  resolves to the file's bytes; `scene.items.add` takes it like any item; `CustomItemInfo.mesh` is
  `{ fit, primitives }` (null for paint items). `SonaError('item')` with rule 13's fix when the glb is refused.
- Native: `sona_custom_item_pack_mesh(ctx, &spec, &out, &len, why, cap)` (`sona_mesh_item_spec`:
  `sona_mesh_item_spec_defaults`, then `template_id`, `glb`, `glb_len`, `name` and the optional texts). It reads
  the template, the rig (or the prop's skeleton) and the coverage check's assets through the ctx's sources:
  `SONA_PENDING` until they have arrived, then call again after `sona_update`. `SONA_E_ARGUMENT` with the reason in
  `why` when the glb is refused. `spec.flags = SONA_MESH_ITEM_FIT_NONE` packs fit `"none"` (no coverage check), the
  same bytes as the web's `fit: 'none'`; other flag bits are refused. A format 1.1 file sets
  `SONA_CUSTOM_ITEM_MESH | SONA_CUSTOM_ITEM_OWN_MESH` in `sona_custom_item_info.flags`.
- CLI: `sona-item template-glb <template> <out.glb> --dir "<asset folder>"`, `sona-item mesh <file.glb> --template <id>
  --name <text> --dir "<asset folder>" [--fit none] [-o file]`, and `pack`/`unpack` of a format 1.1 folder (`item.json` whose `mesh`
  names `mesh.glb`; unpack then pack gives the same bytes). The native `sona item` commands read format 1.0 files only.

---

## Award items from your own game

A developer defines award items for their app; their game unlocks one
for a player signed in with 360sona, and it joins that player's wardrobe on 360sona.com. An award gives a stock
avatar award (an id whose third group's second digit is 1) or the developer's own custom item (format 1.0 or format 1.1), whose
`.sonaitem` the accounts server checks with the SDKs' own checker and keeps. Players keep what they earned when an
award is retired or the app is deleted. The routes are on the developer site (360sona.com).

| Route | Auth | Does |
|---|---|---|
| `PUT /sona/v1/apps/{app}/awards/{key}` | app key | Defines or changes one: `{ title, description?, item, file? }`. `key` is 1 to 64 of a-z, 0-9, `_` and `-`; `title` 1 to 48 characters, `description` up to 280; a custom item needs `file` (base64 `.sonaitem`, a limit of 4 MiB) the first time; 200 awards an app. Once a player has unlocked it, its item and file stay as they are (400; the title and description can change), and a retired one cannot be defined again (400) |
| `GET /sona/v1/apps/{app}/awards` | app key | The app's awards |
| `DELETE /sona/v1/apps/{app}/awards/{key}` | app key | Retires one: nobody new can unlock it |
| `POST /sona/v1/awards/unlock` | `awards` scope | `{ key }`: the signed-in player gets it (the app is the token's). Twice is fine (`unlocked: false`); an unknown or retired key is 404 |
| `GET /sona/v1/awards` | `awards` scope | What this player has earned in this app |
| `GET /sona/v1/awards/{app}/{key}/item` | `awards` scope, or app key | A custom award's `.sonaitem`: for a player whose token is for that app and who unlocked it, or with the app's own key. 401 without either, 404 for an award the player has not earned: an award nobody earned stays the developer's |
| `GET /sona/awards` | the site's session | The wardrobe's awards: everything the account earned, in every app, with each app's name; a custom one's `file` is the site's own `/sona/awards/{app}/{key}/item` |
| `GET /sona/awards/{app}/{key}/item` | the site's session | That file, for an award this account unlocked (so the page fetches nothing from another origin) |
| `POST /sona/v1/items/check` | none | `{ file }`: the checker's verdict on a `.sonaitem` |

The `awards` scope ("Add items you earn in this app to your wardrobe") is granted without review, like the read
scopes: it only adds items the app defined to the signed-in player's own wardrobe. The server checks every file
with the same checker the SDKs use.

**The site wardrobe.** Signed in, 360sona.com's Wardrobe screen lists "From your games": one button per award. A custom award's file is fetched, checked and put in the
library's custom-item registry (`withItems`), so the button wears it like any item and a saved avatar wearing it
draws it on the next visit.

**The calls.**
- Native: `sona_award_define(ctx, &def, &ticket)` (with the app's developer key; tools only, never in a shipped
  game; a custom item travels with its file from the ctx's registry, so `sona_custom_item_add` it first),
  `sona_award_unlock(ctx, player_token, key, &ticket)`, then `sona_award_poll(ctx, ticket)` after `sona_update`:
  `SONA_PENDING`, then once its result: `SONA_OK`, `SONA_E_NOT_FOUND` (no such award), `SONA_E_APP` (a wrong key or
  token, or the scope not granted), `SONA_E_ARGUMENT` (refused: the reason is in `sona_last_error`), `SONA_E_LIMIT`,
  `SONA_E_GATE` (the server failed) or `SONA_E_IO` (unreachable). The host is `config.check_host` (the devs site by
  default); https, or plain http to this machine for local testing. The app is the ctx's.
- Web: `SonaRenderer.defineAward({ app, key, title, description, item, file, developerKey, host })`,
  `SonaRenderer.unlockAward({ key, playerToken, host })`, `SonaRenderer.playerAwards({ playerToken, host })` and
  `SonaRenderer.awardFile({ award, playerToken, host })` (a custom award's `.sonaitem` for the player who earned it,
  for `scene.items.add`), each in the [web SDK reference](../reference/web.md#sonarenderer-defineaward); errors are
  `SonaError` with `code` `item`, `app`, `not_found`, `limit` or `gate`.

```js
const { unlocked, award } = await SonaRenderer.unlockAward({ key: 'first-win', playerToken });
if (unlocked) showToast(`${award.title} is in your 360sona wardrobe`);
```

