# Web SDK reference

The web SDK, `sona-renderer.js` 1.1.0, is one ES module: `SonaRenderer` draws live avatars in your own canvas with
WebGPU, or WebGL2 where WebGPU is missing. This reference is generated from the declarations that ship with it,
`sona-renderer.d.ts`, and the packages' `index.d.ts`. Where an example draws something, the web SDK draws it on the
page beside the code, with the same values.

| Part | What it covers |
|---|---|
| [SonaRenderer](#sonarenderer) | `SonaRenderer` is what the module exports: it makes scenes on your canvas, connections for engines that draw for themselves, and headless renderers, and holds the custom-item helpers. |
| [SonaScene](#sonascene) | A scene is many avatars in one canvas and one WebGPU or WebGL2 context, from `SonaRenderer.create()`. |
| [SonaAvatar](#sonaavatar) | One avatar in a scene, from `scene.add()`. |
| [SonaCamera](#sonacamera) | The scene's camera, `scene.camera`: the console's framings, an orbit, a free camera, eased moves and pointer controls. |
| [Options and results](#options-and-results) | The options `create()` and `add()` take, and what the scene reports. |
| [Errors](#errors) | Every error the SDK raises is a `SonaError`: `code` says what went wrong, `fix` what to do. |
| [Custom items](#custom-items) | Items of your own (`.sonaitem` files, [custom items](../guides/custom-items.md)), per scene as `scene.items`, worn by id with `avatar.wear()`. |
| [Connection and headless](#connection-and-headless) | `SonaRenderer.connect()` gives avatars as .glb files with their clips, for engines that draw them themselves; `SonaRenderer.headless()` makes pictures with no canvas on the page. |
| [The avatar editor element](#the-avatar-editor-element) | `<sona-avatar-editor>`, the player-facing avatar creator as one element. |
| [Face tracking](#face-tracking) | `SonaTrack`: webcam face tracking, MediaPipe's face landmarker in, an avatar's face and head out. |
| [Packages](#packages) | `@360sona/three`, `@360sona/babylon` and `@360sona/react`, on the same connection and scenes. |

## SonaRenderer

`SonaRenderer` is what the module exports: it makes scenes on your canvas, connections for engines that draw for themselves, and headless renderers, and holds the custom-item helpers. `defineAvatarEditor` and `SonaTrack` are exported beside it.

### SonaRendererStatic properties

| Field | Type | Meaning |
|---|---|---|
| `VERSION` | `string` | The SDK's version. Read only. |

### SonaRenderer.create()

```ts
interface SonaRendererStatic {
  create(opts: CreateOptions): Promise<SonaScene>;
}
```

Check the page's origin, open the asset bridge and start a scene on your canvas.

| Parameter | Type | Meaning |
|---|---|---|
| `opts` | [`CreateOptions`](#createoptions) | Your canvas and the scene's settings. |

Returns `Promise<SonaScene>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const sona = await SonaRenderer.create({
  canvas: document.querySelector('canvas'),
  credit: 'bottom-left',
});
const avatar = sona.add(manifestBase64, { clip: 'GenericWave' });
await avatar.ready;
```
### SonaRenderer.supported()

```ts
interface SonaRendererStatic {
  supported(): boolean;
}
```

True when this browser has WebGPU or WebGL2.

Returns `boolean`.

```js
import { SonaRenderer } from './sona-renderer.js';

if (!SonaRenderer.supported()) {
  document.body.append('This browser has neither WebGPU nor WebGL2.');
}
```

### SonaRenderer.connect()

```ts
interface SonaRendererStatic {
  connect(
    opts?: { appId?: string; host?: string },
  ): Promise<SonaConnection>;
}
```

A connection with no canvas, for engines that draw avatars themselves (the packages for three.js and Babylon.js).

| Parameter | Type | Meaning |
|---|---|---|
| `opts.appId` (optional) | `string` | The app id. Default: the one this copy was built for. |
| `opts.host` (optional) | `string` | Where assets come from. Default: the 360sona developer site. |

Returns `Promise<SonaConnection>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const connection = await SonaRenderer.connect();
const glb = await connection.glb(manifestBase64, {
  clips: ['GenericWave'],
});
```

### SonaRenderer.headless()

```ts
interface SonaRendererStatic {
  headless(
    opts?: {
      appId?: string;
      host?: string;
      renderer?: 'auto' | 'webgpu' | 'webgl2';
      antialias?: boolean | 'auto';
      faceSize?: 128 | 256 | 512;
    },
  ): Promise<SonaHeadless>;
}
```

Pictures with no canvas on the page: gamerpics, cards and frames at any size (the web half of sona_headless_*).

| Parameter | Type | Meaning |
|---|---|---|
| `opts.appId` (optional) | `string` | The app id. Default: the one this copy was built for. |
| `opts.host` (optional) | `string` | Where assets come from. Default: the 360sona developer site. |
| `opts.renderer` (optional) | `'auto' \| 'webgpu' \| 'webgl2'` | As create(): "auto", "webgpu" or "webgl2". Default "auto". |
| `opts.antialias` (optional) | `boolean \| 'auto'` | As create(). Default "auto". |
| `opts.faceSize` (optional) | `128 \| 256 \| 512` | The face sheet of each picture's avatar, in pixels. Default 512. |

Returns `Promise<SonaHeadless>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const headless = await SonaRenderer.headless();
const png = await headless.picture(manifestBase64, {
  width: 256, height: 256, preset: 'face',
});
headless.close();
save(png);   // your own: a download, an upload, an <img>
```

### SonaRenderer.checkItem()

```ts
interface SonaRendererStatic {
  checkItem(
    file: ArrayBuffer | Uint8Array,
  ): {
    ok: boolean;
    rule: number | null;
    why: string | null;
    info: CustomItemInfo | null;
  };
}
```

The shallow check of a .sonaitem (format rules 1 to 11), no network.

| Parameter | Type | Meaning |
|---|---|---|
| `file` | `ArrayBuffer \| Uint8Array` | The .sonaitem file's bytes. |

Returns `{ ok: boolean; rule: number | null; why: string | null; info: CustomItemInfo | null }`.

### SonaRenderer.newItemId()

```ts
interface SonaRendererStatic {
  newItemId(templateId: string): string;
}
```

A fresh custom id for a template: its slot and body, a custom marker, 90 random bits.

| Parameter | Type | Meaning |
|---|---|---|
| `templateId` | `string` | The stock item id of the template the custom item is drawn on. |

Returns `string`.

### SonaRenderer.isCustomId()

```ts
interface SonaRendererStatic {
  isCustomId(id: string): boolean;
}
```

True for a custom item id (the marker 8, 9, a or b at the start of the fourth group).

| Parameter | Type | Meaning |
|---|---|---|
| `id` | `string` | An item id. |

Returns `boolean`.

### SonaRenderer.pairOf()

```ts
interface SonaRendererStatic {
  pairOf(id: string): string | null;
}
```

The other body's id (man and woman swapped), or null for body 3 and for real ids.

| Parameter | Type | Meaning |
|---|---|---|
| `id` | `string` | A custom item id. |

Returns `string | null`.

### SonaRenderer.wear()

```ts
interface SonaRendererStatic {
  wear(
    manifestBase64: string,
    itemId: string,
    opts?: { colourway?: number },
  ): string;
}
```

The manifest with an item worn, by the editor's rules (a long-sleeved top takes off the watch). colourway needs the item loaded in a scene on this page. Returns a new manifest (base64).

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `itemId` | `string` | A stock or custom item id. |
| `opts.colourway` (optional) | `number` | An index into the item's colourways (scene.colourways()). Default: the item's own colours. |

Returns `string`.

### SonaRenderer.unwear()

```ts
interface SonaRendererStatic {
  unwear(manifestBase64: string, slot: string): string;
}
```

The manifest with a slot ("shirt", "headwear", ...) emptied. Returns a new manifest (base64).

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `slot` | `string` | A wardrobe slot, as scene.wardrobe() names its sections: "shirt", "trousers", "shoes", "costume", "headwear", "glasses", "gloves", "wristwear", "ring", "earrings" or "carryable". |

Returns `string`.

### SonaRenderer.defineAward()

```ts
interface SonaRendererStatic {
  defineAward(
    opts: {
      app: string;
      key: string;
      title: string;
      description?: string;
      item: string;
      file?: ArrayBuffer | Uint8Array | Blob;
      developerKey: string;
      host?: string;
    },
  ): Promise<Award>;
}
```

Defines an award item for your app, or changes one, with the app's developer key: for your own tools, never a shipped game. Rejects with SonaError "item" (a refused field or file), "app" (a wrong key), "limit" or "gate".

| Parameter | Type | Meaning |
|---|---|---|
| `opts.app` | `string` | Your app id. |
| `opts.key` | `string` | The award's key, 1 to 64 of a-z, 0-9, _ and -. |
| `opts.title` | `string` | The award's name, as players see it. |
| `opts.description` (optional) | `string` | A line under the title. |
| `opts.item` | `string` | A stock avatar award's item id, or your custom item's id. |
| `opts.file` (optional) | `ArrayBuffer \| Uint8Array \| Blob` | The custom item's .sonaitem, when item is a custom id. |
| `opts.developerKey` | `string` | Your app's developer key. |
| `opts.host` (optional) | `string` | The accounts server. Default: the 360sona developer site. |

Returns `Promise<Award>`.

### SonaRenderer.unlockAward()

```ts
interface SonaRendererStatic {
  unlockAward(
    opts: { key: string; playerToken: string; host?: string },
  ): Promise<{ unlocked: boolean; award: Award }>;
}
```

Gives the signed-in player an award item, which joins their 360sona wardrobe. Unlocking it twice is fine. Rejects with SonaError "not_found" (no such award), "app" (the token lacks the awards scope), "limit" or "gate".

| Parameter | Type | Meaning |
|---|---|---|
| `opts.key` | `string` | The award's key. |
| `opts.playerToken` | `string` | The player's token, with the awards scope. |
| `opts.host` (optional) | `string` | The accounts server. Default: the 360sona developer site. |

Returns `Promise<{ unlocked: boolean; award: Award }>`.

### SonaRenderer.playerAwards()

```ts
interface SonaRendererStatic {
  playerAwards(
    opts: { playerToken: string; host?: string },
  ): Promise<Award[]>;
}
```

The award items the signed-in player has earned in your app.

| Parameter | Type | Meaning |
|---|---|---|
| `opts.playerToken` | `string` | The player's token, with the awards scope. |
| `opts.host` (optional) | `string` | The accounts server. Default: the 360sona developer site. |

Returns `Promise<Award[]>`.

### SonaRenderer.awardFile()

```ts
interface SonaRendererStatic {
  awardFile(
    opts: { award: Award; playerToken: string; host?: string },
  ): Promise<Uint8Array>;
}
```

A custom award's .sonaitem, for the player who earned it; give it to scene.items.add() to wear it. Rejects with SonaError "not_found" when the player has not earned it.

| Parameter | Type | Meaning |
|---|---|---|
| `opts.award` | [`Award`](#award) | An award from playerAwards() that has a file. |
| `opts.playerToken` | `string` | The player's token, or your app's developer key. |
| `opts.host` (optional) | `string` | The accounts server. Default: the 360sona developer site. |

Returns `Promise<Uint8Array>`.

### SonaRenderer.defineAvatarEditor()

```ts
interface SonaRendererStatic {
  defineAvatarEditor(name?: string): SonaAvatarEditorConstructor;
}
```

Registers the avatar editor element, by default as `<sona-avatar-editor>`. The same as the defineAvatarEditor export.

| Parameter | Type | Meaning |
|---|---|---|
| `name` (optional) | `string` | The element's tag name. Default "sona-avatar-editor". |

Returns `SonaAvatarEditorConstructor`.

### VERSION

```ts
declare const VERSION: string;
```

The SDK's version, for example "1.1.0".

## SonaScene

A scene is many avatars in one canvas and one WebGPU or WebGL2 context, from `SonaRenderer.create()`. The examples call it `sona`.

### SonaScene properties

| Field | Type | Meaning |
|---|---|---|
| `canvas` | `HTMLCanvasElement` | The canvas the scene draws into. Read only. |
| `appId` | `string` | The app id the scene runs under. Read only. |
| `camera` | `SonaCamera` | The camera. Read only. |
| `avatars` | `readonly SonaAvatar[]` | Every avatar in the scene, in the order they were added. Read only. |
| `running` | `boolean` | True while the auto loop runs. Read only. |
| `items` | `SonaItems` | Custom items loaded into this scene. Read only. |
| `renderer` | `'webgpu' \| 'webgl2'` | "webgpu" or "webgl2": what this scene draws with. Read only. |
| `background` | `[number, number, number, number]` | The clear colour, premultiplied RGBA 0 to 1. |

### scene.add()

```ts
interface SonaScene {
  add(manifestBase64: string, opts?: AddOptions): SonaAvatar;
}
```

Queue an avatar. Returns at once; it builds over the next frames and appears when ready. Throws SonaError("limit") past maxAvatars.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts` (optional) | [`AddOptions`](#addoptions) | Where it stands and what it plays. |

Returns `SonaAvatar`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const a = sona.add(manifestBase64, {
  position: [-0.5, 0, 0], turn: 15, clip: 'GenericClap',
});
const b = sona.add(otherManifest, {
  position: [0.5, 0, 0], turn: -15, clip: 'GenericWave',
});
sona.camera.preset('crowd');
```
### scene.remove()

```ts
interface SonaScene {
  remove(avatar: SonaAvatar): void;
}
```

Take an avatar out and free what only it used.

| Parameter | Type | Meaning |
|---|---|---|
| `avatar` | [`SonaAvatar`](#sonaavatar) | An avatar of this scene. |

### scene.clear()

```ts
interface SonaScene {
  clear(): void;
}
```

Remove every avatar.

### scene.frame()

```ts
interface SonaScene {
  frame(timeMs?: number): Promise<FrameStats>;
}
```

Draw one frame at timeMs (performance.now() if omitted). For loop: "manual".

| Parameter | Type | Meaning |
|---|---|---|
| `timeMs` (optional) | `number` | The frame's time in milliseconds, which clips and eases follow. Default performance.now(). |

Returns `Promise<FrameStats>`.

### scene.settle()

```ts
interface SonaScene {
  settle(
    avatars?: SonaAvatar | SonaAvatar[],
    opts?: { seconds?: number },
  ): Promise<SonaAvatar[]>;
}
```

Resolves when the avatars (default all) are ready or failed. Avatars build only while frames are drawn: with loop "manual" this draws frames while it waits, where awaiting `avatar.ready` alone would wait for ever. Rejects with code "not_ready" after `seconds` (default 120).

| Parameter | Type | Meaning |
|---|---|---|
| `avatars` (optional) | `SonaAvatar \| SonaAvatar[]` | The avatars to wait for. Default: every avatar in the scene. |
| `opts.seconds` (optional) | `number` | How long to wait before rejecting. Default 120. |

Returns `Promise<SonaAvatar[]>`.

### scene.start()

```ts
interface SonaScene {
  start(): void;
}
```

Turn the auto loop on.

### scene.stop()

```ts
interface SonaScene {
  stop(): void;
}
```

Turn the auto loop off.

### scene.resize()

```ts
interface SonaScene {
  resize(): void;
}
```

Re-measure the canvas. Also automatic through a ResizeObserver.

### scene.snapshot()

```ts
interface SonaScene {
  snapshot(
    opts?: {
      type?: 'image/png' | 'image/webp' | 'image/jpeg';
      quality?: number;
      credit?: boolean;
    },
  ): Promise<Blob>;
}
```

A picture of the next frame, drawn and read back in one task. The credit is written into the file's metadata; credit: true also draws it in the corner.

| Parameter | Type | Meaning |
|---|---|---|
| `opts.type` (optional) | `'image/png' \| 'image/webp' \| 'image/jpeg'` | The picture's format. Default "image/png". |
| `opts.quality` (optional) | `number` | 0 to 1, for WebP and JPEG. Default: the browser's own. |
| `opts.credit` (optional) | `boolean` | Draw the badge in the picture's corner too. Default false. |

Returns `Promise<Blob>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericWave' });
await avatar.ready;
const png = await sona.snapshot({ credit: true });
const img = new Image();
img.src = URL.createObjectURL(png);
```

### scene.glb()

```ts
interface SonaScene {
  glb(
    manifestBase64: string,
    opts?: { clips?: ClipKey[]; textures?: boolean },
  ): Promise<ArrayBuffer>;
}
```

The avatar as a .glb, the same file the 360sona runtime exports, with the same credit inside. Runs a full build at face size 512 on the calling thread. Custom items it draws are named, with their creators, in the file's copyright. The SDK Licence (S5) allows this file only for the person whose avatar it is, with the credit left in; it is not a way to collect items or animations.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts.clips` (optional) | `ClipKey[]` | The clips to put in the file. Default: every clip but "prop". |
| `opts.textures` (optional) | `boolean` | Embed the textures. Default true. |

Returns `Promise<ArrayBuffer>`.

### scene.clips()

```ts
interface SonaScene {
  clips(): ClipInfo[];
}
```

Every clip this SDK can play.

Returns `ClipInfo[]`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
for (const c of sona.clips()) console.log(c.key, c.caption);
```

### scene.samples()

```ts
interface SonaScene {
  samples(): Promise<{ title: string; manifest: string }[]>;
}
```

Sample avatars from 360sona, for demos and benchmarks.

Returns `Promise<{ title: string; manifest: string }[]>`.

### scene.wardrobe()

```ts
interface SonaScene {
  wardrobe(): Promise<readonly WardrobeItem[]>;
}
```

The wardrobe for pickers: every item that may be offered, named, with its editor section. Loaded once per scene, through the bridge.

Returns `Promise<readonly WardrobeItem[]>`.

### scene.colours()

```ts
interface SonaScene {
  colours(): Record<string, string[]>;
}
```

The swatches of each palette slot (skin, hair, mouth, eyes, eyebrows, eyeShadow, facialHair, facialFeature), as #rrggbb.

Returns `Record<string, string[]>`.

### scene.colourways()

```ts
interface SonaScene {
  colourways(itemId: string): string[][] | null;
}
```

An item's own colourways, each three #rrggbb, once the item is loaded (worn by an avatar here, or added with items); null before, or when it has none. Pass the index to avatar.wear(id, { colourway }).

| Parameter | Type | Meaning |
|---|---|---|
| `itemId` | `string` | A stock or custom item id. |

Returns `string[][] | null`.

### scene.thumbnails()

```ts
interface SonaScene {
  thumbnails(ids: string[]): Promise<(Uint8Array | null)[]>;
}
```

Item pictures: PNG, JPEG or WebP bytes in the order asked, null where an item has none. At most 6000 different ids per page.

| Parameter | Type | Meaning |
|---|---|---|
| `ids` | `string[]` | Item ids, at most 6000 different ones a page. |

Returns `Promise<(Uint8Array | null)[]>`.

### scene.benchmark()

```ts
interface SonaScene {
  benchmark(
    opts?: {
      counts?: number[];
      seconds?: number;
      distinct?: number;
      onStep?: (r: BenchStep) => void;
    },
  ): Promise<BenchStep[]>;
}
```

Run the benchmark: adds sample avatars at each count (replicating `distinct` samples, default 12), waits until they are ready, measures, removes them.

| Parameter | Type | Meaning |
|---|---|---|
| `opts.counts` (optional) | `number[]` | The avatar counts to measure, in order; a count over maxAvatars is skipped. Default [10, 25, 50, 100, 200]. |
| `opts.seconds` (optional) | `number` | Seconds measured at each count. Default 4. |
| `opts.distinct` (optional) | `number` | Different sample avatars, repeated to make up each count. Default 12. |
| `opts.onStep` (optional) | `(r: BenchStep) => void` | Called with each row as it is measured. |

Returns `Promise<BenchStep[]>`.

### scene.stats()

```ts
interface SonaScene {
  stats(): SceneStats;
}
```

Rolling numbers over the last two seconds.

Returns `SceneStats`.

### scene.on()

```ts
interface SonaScene {
  on(event: 'ready', fn: (a: SonaAvatar) => void): () => void;
  on(
    event: 'error',
    fn: (e: SonaError, a?: SonaAvatar) => void,
  ): () => void;
  on(event: 'frame', fn: (s: FrameStats) => void): () => void;
}
```

- `'ready'`: An avatar appeared. Returns a function that removes the listener.
- `'error'`: Something failed. Returns a function that removes the listener.
- `'frame'`: A frame was drawn. Returns a function that removes the listener.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
sona.on('ready', (a) => console.log('drawn', a.id));
sona.on('error', (e) => console.log(e.code, e.fix));
sona.add(manifestBase64);
```

### scene.destroy()

```ts
interface SonaScene {
  destroy(): void;
}
```

Free everything: GPU objects, the bridge frame, the badge, listeners.

## SonaAvatar

One avatar in a scene, from `scene.add()`. It is built over the next frames and shows when `ready` resolves.

### SonaAvatar properties

| Field | Type | Meaning |
|---|---|---|
| `id` | `number` | A number unique on this page. Read only. |
| `manifest` | `string` | The manifest it wears (base64): the one it was added with, as changed by wear and unwear. Read only. |
| `state` | `'queued' \| 'loading' \| 'ready' \| 'failed' \| 'removed'` | Where it is in its life. Read only. |
| `ready` | `Promise<SonaAvatar>` | Resolves when it is on screen; rejects with a SonaError if it cannot be built. Read only. |
| `position` | `Vec3` | Its position. Read only. |
| `turn` | `number` | Its turn in degrees. Read only. |
| `scale` | `number` | Its scale. Read only. |
| `clip` | `ClipKey \| null` | What it was last asked to play. Read only. |
| `missingItems` | `readonly string[]` | Custom ids this avatar wears that are not loaded (or cannot be built), as last built. Required slots show the body's default garment meanwhile. Read only. |

### avatar.play()

```ts
interface SonaAvatar {
  play(
    clip: ClipKey,
    opts?: { loop?: boolean; speed?: number; from?: number },
  ): Promise<void>;
}
```

Play a clip. Called before ready, it is remembered and applied when the avatar appears.

| Parameter | Type | Meaning |
|---|---|---|
| `clip` | `ClipKey` | A key from scene.clips(), a raw clip id, "prop", "idle" or "still". |
| `opts.loop` (optional) | `boolean` | Loop the clip. Default true ("idle" always loops). |
| `opts.speed` (optional) | `number` | Playback speed, 0 or more; 1 is the clip's own. Default 1. |
| `opts.from` (optional) | `number` | Seconds into the clip to start from, up to its length. Default 0. |

Returns `Promise<void>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericStand5' });
await avatar.ready;
await avatar.play('GenericCelebration', { loop: false });
```
### avatar.stop()

```ts
interface SonaAvatar {
  stop(): void;
}
```

Hold the current pose.

### avatar.move()

```ts
interface SonaAvatar {
  move(to: Placement, opts?: { over?: number }): void;
}
```

Move, turn or scale.

| Parameter | Type | Meaning |
|---|---|---|
| `to` | [`Placement`](#placement) | Where to go: position (metres), turn (degrees about Y) and scale. What it leaves out stays as it is. |
| `opts.over` (optional) | `number` | Seconds to ease there. Default 0 (at once). |

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64);
await avatar.ready;
avatar.move({ turn: 60 }, { over: 1 });
```
### avatar.setVisible()

```ts
interface SonaAvatar {
  setVisible(visible: boolean): void;
}
```

Show or hide it.

| Parameter | Type | Meaning |
|---|---|---|
| `visible` | `boolean` | false hides it; it keeps its place and its clip. |

### avatar.bounds()

```ts
interface SonaAvatar {
  bounds(): { center: Vec3; radius: number };
}
```

Its bounding sphere in world space.

Returns `{ center: Vec3; radius: number }`.

### avatar.remove()

```ts
interface SonaAvatar {
  remove(): void;
}
```

Take it out of its scene.

### avatar.wear()

```ts
interface SonaAvatar {
  wear(itemId: string, opts?: { colourway?: number }): Promise<void>;
}
```

Wears an item (stock or custom) and rebuilds. The old look stays on screen until the new one is ready. colourway: an index into the item's colourways.

| Parameter | Type | Meaning |
|---|---|---|
| `itemId` | `string` | A stock or custom item id; a custom one is loaded first with scene.items.add(). |
| `opts.colourway` (optional) | `number` | An index into the item's colourways (scene.colourways()). Default: the item's own colours. |

Returns `Promise<void>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64);
await avatar.ready;
await avatar.wear('00001000-c6f4-2253-caa5-9f694d5309cf');
avatar.play('prop');
// room for the prop: its clip swings it above the head
sona.camera.orbit({
  yaw: 0, pitch: 5, distance: 4.5, target: [0, 0.95, 0],
});
```
### avatar.unwear()

```ts
interface SonaAvatar {
  unwear(slot: string): Promise<void>;
}
```

Empties a slot ("shirt", "headwear", ...) and rebuilds.

| Parameter | Type | Meaning |
|---|---|---|
| `slot` | `string` | A wardrobe slot, as scene.wardrobe() names its sections: "shirt", "trousers", "shoes", "costume", "headwear", "glasses", "gloves", "wristwear", "ring", "earrings" or "carryable". |

Returns `Promise<void>`.

### avatar.update()

```ts
interface SonaAvatar {
  update(manifestBase64: string): Promise<void>;
}
```

Changes to another manifest and rebuilds. The old look stays on screen until the new one is ready.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The new manifest, base64. |

Returns `Promise<void>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericStand5' });
await avatar.ready;
await avatar.update(otherManifest);
```
## SonaCamera

The scene's camera, `scene.camera`: the console's framings, an orbit, a free camera, eased moves and pointer controls.

### SonaCamera properties

| Field | Type | Meaning |
|---|---|---|
| `fov` | `number` | Vertical field of view in degrees. Default 28.65 (0.5 rad, the console's). |
| `near` | `number` | Near plane in metres. Default 0.05. |
| `far` | `number` | Far plane in metres. Default 200. |
| `eye` | `Vec3` | Where the camera is. Read only. |
| `target` | `Vec3` | What it looks at. Read only. |

### camera.preset()

```ts
interface SonaCamera {
  preset(name: PresetName, on?: SonaAvatar, opts?: { over?: number }): void;
}
```

One of the console's framings on one avatar, or "crowd" to fit every avatar.

| Parameter | Type | Meaning |
|---|---|---|
| `name` | `PresetName` | A framing: "full", "upper", "bust" or "face", or "crowd" to fit every avatar. |
| `on` (optional) | [`SonaAvatar`](#sonaavatar) | The avatar to frame. Default: the first ready one. "crowd" frames them all. |
| `opts.over` (optional) | `number` | Seconds to ease there. Default 0 (at once). |

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericStand5' });
await avatar.ready;
// 'full', 'upper', 'bust' or 'face'
sona.camera.preset('bust', avatar, { over: 0.5 });
```
### camera.orbit()

```ts
interface SonaCamera {
  orbit(
    o: { yaw?: number; pitch?: number; distance?: number; target?: Vec3 },
    opts?: { over?: number },
  ): void;
}
```

Orbit around a target. yaw and pitch in degrees, distance in metres.

| Parameter | Type | Meaning |
|---|---|---|
| `o.yaw` (optional) | `number` | Degrees round the target. Default: as now. |
| `o.pitch` (optional) | `number` | Degrees up, -89 to 89. Default: as now. |
| `o.distance` (optional) | `number` | Metres from the target. Default: as now. |
| `o.target` (optional) | `Vec3` | The point to orbit, in metres. Default: as now. |
| `opts.over` (optional) | `number` | Seconds to ease there. Default 0 (at once). |

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericStand5' });
await avatar.ready;
sona.camera.orbit({
  yaw: 35, pitch: 10, distance: 4.4, target: [0, 0.9, 0],
});
```
### camera.lookAt()

```ts
interface SonaCamera {
  lookAt(eye: Vec3, target: Vec3, opts?: { over?: number }): void;
}
```

A free camera.

| Parameter | Type | Meaning |
|---|---|---|
| `eye` | `Vec3` | Where the camera goes, in metres. |
| `target` | `Vec3` | The point it looks at, in metres. |
| `opts.over` (optional) | `number` | Seconds to ease there. Default 0 (at once). |

### camera.controls()

```ts
interface SonaCamera {
  controls(
    on: boolean | { drag?: boolean; zoom?: boolean; pitch?: boolean },
  ): void;
}
```

Pointer controls on the canvas.

| Parameter | Type | Meaning |
|---|---|---|
| `on` | `boolean \| { drag?: boolean; zoom?: boolean; pitch?: boolean }` | true: drag turns and the wheel zooms. false: none. Or each one: drag turns, zoom scrolls, pitch tilts with an up and down drag. |

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
sona.add(manifestBase64);
sona.camera.controls({ drag: true, zoom: true });
```

### PresetName

```ts
type PresetName = 'full' | 'upper' | 'bust' | 'face' | 'crowd';
```

The console's framings, and "crowd" to fit every avatar.

## Options and results

The options `create()` and `add()` take, and what the scene reports.

### CreateOptions

Options for SonaRenderer.create().

| Field | Type | Meaning |
|---|---|---|
| `canvas` | `HTMLCanvasElement` | Your canvas. The SDK owns its WebGPU or WebGL2 context. |
| `renderer` (optional) | `'auto' \| 'webgpu' \| 'webgl2'` | "auto": WebGPU on a hardware adapter, else WebGL2. "webgpu" or "webgl2" asks for one (SonaError "unsupported" when WebGPU is missing). The two draw the same pixels. Default "auto". |
| `appId` (optional) | `string` | Defaults to the app id this copy was built for. |
| `host` (optional) | `string` | Where assets come from. Default: the 360sona developer site (https://360sona.com). |
| `loop` (optional) | `'auto' \| 'manual'` | "auto": the SDK runs requestAnimationFrame. "manual": you call frame() from your loop; avatars build only inside frame(), so await scene.settle() (it draws frames) rather than avatar.ready alone. Default "auto". |
| `pixelRatio` (optional) | `number` | Device pixels per CSS pixel. Default min(2, devicePixelRatio). |
| `supersample` (optional) | `number` | Supersampling, 1 to 2. Default 1. Capped at 5.2 million pixels. |
| `antialias` (optional) | `boolean \| 'auto'` | 4x multisampled edges. "auto" turns it off on software rasterisers (SwiftShader, llvmpipe), where each sample costs a full shade. Default "auto". |
| `faceSize` (optional) | `128 \| 256 \| 512 \| 'auto'` | Face sheet size per avatar. "auto": 512 for 1 to 4 avatars, 256 up to 32, 128 beyond. Default "auto". |
| `faces` (optional) | `'animated' \| 'still'` | "animated": faces follow each clip's expression track. "still": one face per avatar. Default "animated". |
| `shadow` (optional) | `boolean` | The key light shadow. Tuned for one figure near the origin. Default false. |
| `background` (optional) | `[number, number, number, number]` | Clear colour, premultiplied RGBA 0 to 1. Default [0, 0, 0, 0] (transparent). |
| `credit` (optional) | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left' \| false` | Where the credit badge sits. A small "Powered by 360sona" link, shown once an avatar is on screen. false hides it: then put the line in your credits, about page, footer or store page (Licence S2). Default "bottom-right". |
| `buildBudgetMs` (optional) | `number` | Milliseconds of avatar building allowed per frame. Default 6. |
| `maxAvatars` (optional) | `number` | Most avatars at once. Default 256, at most 1024. |
| `pauseWhenHidden` (optional) | `boolean` | Stop drawing while the canvas is off screen or the tab is hidden (auto loop only). Default true. |
| `controls` (optional) | `boolean \| { drag?: boolean; zoom?: boolean; pitch?: boolean }` | Drag to turn the camera, and optionally scroll to zoom and drag up and down to tilt. Default false. |

### Placement

Where an avatar stands.

| Field | Type | Meaning |
|---|---|---|
| `position` (optional) | `Vec3` | World position in metres. Y is up. Default [0, 0, 0]. |
| `turn` (optional) | `number` | Degrees about Y. 0 faces the default camera (towards -Z). Default 0. |
| `scale` (optional) | `number` | Uniform scale. Default 1. |

### AddOptions

Options for scene.add().

| Field | Type | Meaning |
|---|---|---|
| `clip` (optional) | `ClipKey \| null` | What to play once ready. Default "idle". |
| `loop` (optional) | `boolean` | Loop the clip. Default true. |
| `speed` (optional) | `number` | Playback speed. Default 1. |
| `startAt` (optional) | `number \| 'random'` | Seconds into the clip, or "random" to desynchronise a crowd. Default 0. |
| `visible` (optional) | `boolean` | Draw it. Default true. |
| `priority` (optional) | `number` | Higher builds sooner. Default 0. |

### Vec3

```ts
type Vec3 = [number, number, number];
```

A point or direction in metres. Y is up; an avatar is about 1.8 tall.

### ClipKey

```ts
type ClipKey = string;
```

A clip key from scene.clips() (for example "GenericWave" or "Stand0"), a raw clip id, "prop" (the held prop's own clip), "idle" (a quiet playlist) or "still" (hold the pose).

### ClipInfo

One playable clip.

| Field | Type | Meaning |
|---|---|---|
| `key` | `string` | The name to play it by, for example "GenericWave". |
| `id` | `string \| null` | Its clip id, or null for "prop" (each prop has its own). |
| `seconds` | `number \| null` | Its length in seconds where known; null in this release, which reads a clip's length only when it decodes it. |
| `prop` | `boolean` | True for "prop", the held prop's own clip. |
| `caption` | `string \| null` | Its name in plain words where the clip table has one, else null. |

### FrameStats

What one frame did.

| Field | Type | Meaning |
|---|---|---|
| `ms` | `number` | Wall time since the previous frame. |
| `cpuMs` | `number` | Time spent inside frame(). |
| `drawn` | `number` | Avatars drawn. |
| `culled` | `number` | Avatars outside the view. |
| `drawCalls` | `number` | Draw calls in the main pass. |
| `built` | `number` | Build steps run this frame. |

### SceneStats

Rolling scene numbers.

| Field | Type | Meaning |
|---|---|---|
| `fps` | `number` | Frames a second over the last two seconds. |
| `msPerFrame` | `number` | Milliseconds between frames, the mean over the last two seconds. |
| `p95Ms` | `number` | Milliseconds between frames that 95 of 100 frames beat, over the last two seconds. |
| `cpuMsPerFrame` | `number` | Milliseconds a frame spends inside frame(), the mean over the last two seconds. |
| `avatars` | `number` | Avatars in the scene, ready or not. |
| `ready` | `number` | Avatars built and shown. |
| `queued` | `number` | Avatars waiting to be built or loading. |
| `drawn` | `number` | Avatars drawn in the last frame. |
| `drawCalls` | `number` | Draw calls in the last frame's main pass. |
| `geometries` | `number` | Meshes held on the GPU. |
| `textures` | `number` | Textures held on the GPU. |
| `gpuMB` | `number` | MiB of GPU memory the scene's meshes and textures hold. |
| `cpuMB` | `number` | MiB of item files and decoded assets held in memory. |
| `buildMsAvg` | `number` | Milliseconds of a build step, the mean over the last 200. |
| `buildMsMax` | `number` | Milliseconds of the longest build step since the scene was made. |
| `longFrames` | `number` | Frames over the threshold of 33 ms in the last two seconds. |

### BenchStep

One row of the benchmark.

| Field | Type | Meaning |
|---|---|---|
| `avatars` | `number` | Avatars in this step. |
| `fps` | `number` | Frames a second while they all played. |
| `msPerFrame` | `number` | Milliseconds between frames, the mean. |
| `p95Ms` | `number` | Milliseconds between frames that 95 of 100 frames beat. |
| `cpuMsPerFrame` | `number` | Milliseconds a frame spent inside frame(), the mean. |
| `drawCalls` | `number` | Draw calls in the last frame's main pass. |
| `gpuMB` | `number` | MiB of GPU memory the scene held. |
| `ready` | `number` | How many of the step's avatars were ready. |
| `readyMs` | `number` | Milliseconds from adding the step's avatars to the last one ready (at most 180,000). |
| `buildMsMax` | `number` | Milliseconds of the longest build step so far. |

### WardrobeItem

One wardrobe item, as scene.wardrobe() and the editor offer it.

| Field | Type | Meaning |
|---|---|---|
| `id` | `string` | The item id. |
| `name` | `string` | Its name. |
| `section` | `string` | The editor section: shirt, trousers, shoes, costume (outfits), headwear, glasses, gloves, wristwear, ring, earrings, carryable (props), hair, eyes, eyebrows, mouth, facialHair, eyeShadow, facialFeature (face paint), chin, nose, ears, shape (a garment's body shape, listed only while worn, so it can be taken off) or animation. The editor's search of every item finds all of them; shape and animation items cannot be put on. |
| `mask` | `number` | The item type bits. 0x1000000 alone is a garment's body shape, offered only while worn. |
| `kind` | `number` | 1 a garment (body-specific), 2 a face texture, 3 a shape. |
| `gender` | `number \| null` | For garments: 1 male body, 2 female body, 3 either, null not body-specific. |
| `hidden` | `boolean` | A duplicate of another item; offered only while worn. |
| `stock` | `boolean` | Part of the built-in wardrobe. |
| `awarded` | `boolean` | An award item. |
| `game` | `string \| null` | The game an award or item came with, where known. |
| `colours` | `number` | How many colourways the item carries (scene.colourways gives them once it is loaded); 0 or 1 when it has no choice. |
| `sub` | `string \| null` | The catalogue's subcategory name, where it has one; searched with the name. |
| `slots` | `readonly string[]` | The slots the item fills ("shirt", "trousers", ...). |

## Errors

Every error the SDK raises is a `SonaError`: `code` says what went wrong, `fix` what to do. `create()` and `ready` reject with one; `add()` throws one only past `maxAvatars`.

### SonaError

The error class. Its `message` and `fix` are plain words for a person; `code` is one of the values below.

| Field | Type | Meaning |
|---|---|---|
| `code` | `'unsupported' \| 'not_ready' \| 'origin' \| 'licence' \| 'app' \| 'gate' \| 'manifest' \| 'context' \| 'readback' \| 'limit' \| 'destroyed' \| 'item' \| 'not_found'` | unsupported: no WebGPU or WebGL2 (or no WebGPU when renderer "webgpu" was asked for). not_ready: a headless picture's avatar was not ready in time. origin: this page's origin is not registered for the app. licence: the app has not accepted the SDK Licence. app: no such app, or it was turned off. gate: 360sona could not be reached. manifest: that avatar could not be read or built. context: the graphics context failed. readback: a picture could not be read. limit: too many avatars or requests. destroyed: the scene or avatar is gone. item: a custom item file was refused (the message names the rule). not_found: no such award, or none this player has earned (the award calls). Read only. |
| `fix` (optional) | `string` | What to do about it, in plain words. Read only. |

## Custom items

Items of your own (`.sonaitem` files, [custom items](../guides/custom-items.md)), per scene as `scene.items`, worn by id with `avatar.wear()`.

### scene.items.add()

```ts
interface SonaItems {
  add(file: ArrayBuffer | Uint8Array | Blob): Promise<CustomItemInfo>;
}
```

Checks the file and keeps it. Avatars wearing its id rebuild. Rejects with SonaError("item"), whose message names the rule and whose fix says what to do. A higher version of a loaded id replaces it; the same version with other bytes is refused.

| Parameter | Type | Meaning |
|---|---|---|
| `file` | `ArrayBuffer \| Uint8Array \| Blob` | The .sonaitem file: its bytes or a Blob. |

Returns `Promise<CustomItemInfo>`.

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const bytes = await (await fetch('night-sky.sonaitem')).arrayBuffer();
const info = await sona.items.add(bytes);
const avatar = sona.add(SonaRenderer.wear(manifestBase64, info.id));
```

### scene.items.remove()

```ts
interface SonaItems {
  remove(id: string): boolean;
}
```

Forgets it. Avatars wearing it rebuild with the slot's fallback (see SonaAvatar.missingItems).

| Parameter | Type | Meaning |
|---|---|---|
| `id` | `string` | A custom item id. |

Returns `boolean`.

### scene.items.get()

```ts
interface SonaItems {
  get(id: string): CustomItemInfo | null;
}
```

A loaded item, or null.

| Parameter | Type | Meaning |
|---|---|---|
| `id` | `string` | A custom item id. |

Returns `CustomItemInfo | null`.

### scene.items.list()

```ts
interface SonaItems {
  list(): CustomItemInfo[];
}
```

Every loaded item.

Returns `CustomItemInfo[]`.

### scene.items.pack()

```ts
interface SonaItems {
  pack(spec: PackSpec): Promise<Uint8Array>;
}
```

Makes a .sonaitem from pixels. Reads the template through 360sona to check its surfaces and take its hash. Unsigned.

| Parameter | Type | Meaning |
|---|---|---|
| `spec` | [`PackSpec`](#packspec) | The template, the pictures and the item's details. |

Returns `Promise<Uint8Array>`.

### CustomItemInfo

What a custom item file holds, as checked.

| Field | Type | Meaning |
|---|---|---|
| `id` | `string` | The item's id, which avatars wear it by. |
| `slot` | `string` | The wardrobe slot its id names: "shirt", "headwear", "carryable" and the rest. |
| `mask` | `number` | The item type bits its id carries. |
| `body` | `'man' \| 'woman' \| 'both'` | The body it fits, read from its id. |
| `name` | `string` | Its name, 1 to 48 characters. |
| `creator` | `string \| null` | The creator's display name, or null when the file names none. Not an account. |
| `version` | `number` | Its version, 1 or more; a higher version of a loaded id replaces it. |
| `sha256` | `string` | SHA-256 of the file's hashed part, 64 lowercase hex digits. |
| `template` | `{ id: string; sha256: string }` | The stock template it was painted on: its item id and the SHA-256 of the template's bytes. |
| `surfaces` | `{ color: [number, number]; regions: [number, number] \| null; decal: [number, number] \| null }[]` | Each surface's texture sizes, [width, height]. |
| `colourways` | `[string, string, string][]` | Its colourways, each three "#rrggbb" colours; empty when it has none. |
| `signed` | `{ creator: boolean; site: boolean }` | Whether the file carries the creator's signature and 360sona's. |
| `bytes` | `number` | The file's size in bytes. |
| `warnings` | `string[]` | What the check let through but noted, in plain words (an ignored lower version, an unknown key). |

### PackSpec

The input to scene.items.pack. Images are RGBA; colour sides 64 to 512, regions and decal 32 to 512, powers of two.

| Field | Type | Meaning |
|---|---|---|
| `id` (optional) | `string` | Default: a fresh id for the template. |
| `template` | `string` | The stock template's item id, whose surfaces the pictures paint. |
| `name` | `string` | The item's name, 1 to 48 characters. |
| `version` (optional) | `number` | 1 or more, up by one each time you change the item. Default 1. |
| `description` (optional) | `string` | Up to 280 characters. Default: none. |
| `creator` (optional) | `string` | Your display name, up to 48 characters. Default: none. |
| `created` (optional) | `string` | The day it was made, "YYYY-MM-DD". Default: none. |
| `licence` (optional) | `string` | Up to 64 characters. Default "wear": anyone may wear, show and share it; nobody may sell it. |
| `surfaces` | `{ color: ImageData; regions?: ImageData; decal?: ImageData; layout?: 'split' \| 'template' }[]` | One per template surface. layout defaults to "template" (the template's own colour layout). |
| `colourways` (optional) | `[string, string, string][]` | Up to 32 triples of "#rrggbb". Needed when any surface has regions. |

### Award

An award item of your app, as the award calls give it.

| Field | Type | Meaning |
|---|---|---|
| `key` | `string` | Its key, unique in your app. |
| `title` | `string` | Its name, as players see it. |
| `description` | `string \| null` | The line under its title, or null. |
| `item` | `string` | The item id it gives: a stock avatar award or your custom item. |
| `file` | `string \| null` | Where its .sonaitem is (awardFile() reads it), or null for a stock item. |
| `made` | `number` | When it was defined (Unix milliseconds). |
| `at` | `number` | When it last changed (Unix milliseconds). |
| `retired` (optional) | `number` | When it was retired (Unix milliseconds); absent while it is offered. |
| `unlocked` (optional) | `number` | In playerAwards(): when the player unlocked it (Unix milliseconds). |

## Connection and headless

`SonaRenderer.connect()` gives avatars as .glb files with their clips, for engines that draw them themselves; `SonaRenderer.headless()` makes pictures with no canvas on the page.

### SonaConnection properties

| Field | Type | Meaning |
|---|---|---|
| `appId` | `string` | The app id the connection was opened for. Read only. |

### connection.glb()

```ts
interface SonaConnection {
  glb(
    manifestBase64: string,
    opts?: { clips?: ClipKey[] | null; textures?: boolean },
  ): Promise<ArrayBuffer>;
}
```

An avatar as a .glb with the clips asked for (all by default), the renderer's light baked into unlit materials.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts.clips` (optional) | `ClipKey[] \| null` | The clips to include. Default null: every clip but "prop". |
| `opts.textures` (optional) | `boolean` | Embed the textures. Default true. |

Returns `Promise<ArrayBuffer>`.

### connection.clips()

```ts
interface SonaConnection {
  clips(): ClipInfo[];
}
```

Every clip a glb() can take.

Returns `ClipInfo[]`.

### connection.samples()

```ts
interface SonaConnection {
  samples(): Promise<{ title: string; manifest: string }[]>;
}
```

The sample avatars: a title and a base64 manifest each.

Returns `Promise<{ title: string; manifest: string }[]>`.

### connection.wardrobe()

```ts
interface SonaConnection {
  wardrobe(): Promise<readonly WardrobeItem[]>;
}
```

Every item an avatar can wear, as the editor offers them.

Returns `Promise<readonly WardrobeItem[]>`.

### connection.colours()

```ts
interface SonaConnection {
  colours(): Record<string, string[]>;
}
```

The colour choices of each colourable part (skin, hair, eyes and the rest), each "#rrggbb".

Returns `Record<string, string[]>`.

### connection.credit()

```ts
interface SonaConnection {
  credit(
    canvas: HTMLCanvasElement,
    corner?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left',
  ): { dispose(): void };
}
```

"Powered by 360sona" on a canvas you draw avatars into.

| Parameter | Type | Meaning |
|---|---|---|
| `canvas` | `HTMLCanvasElement` | The canvas you draw avatars into. |
| `corner` (optional) | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | Where the badge sits. Default "bottom-right". |

Returns `{ dispose(): void }`.

### connection.release()

```ts
interface SonaConnection {
  release(): void;
}
```

Close the connection's bridge.

### SonaHeadless properties

| Field | Type | Meaning |
|---|---|---|
| `renderer` | `'webgpu' \| 'webgl2'` | The backend it draws with. Read only. |

### headless.render()

```ts
interface SonaHeadless {
  render(
    manifestBase64: string,
    opts?: HeadlessOptions,
  ): Promise<HeadlessPicture>;
}
```

One picture as RGBA pixels.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts` (optional) | [`HeadlessOptions`](#headlessoptions) | The picture's size, framing, clip and colour. |

Returns `Promise<HeadlessPicture>`.

### headless.picture()

```ts
interface SonaHeadless {
  picture(manifestBase64: string, opts?: HeadlessOptions): Promise<Blob>;
}
```

One picture as an image file.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts` (optional) | [`HeadlessOptions`](#headlessoptions) | The picture's size, framing, clip, colour and format. |

Returns `Promise<Blob>`.

### headless.batch()

```ts
interface SonaHeadless {
  batch(
    manifests: string[],
    opts: HeadlessOptions,
    fn: (
      index: number,
      result: HeadlessPicture | { error: SonaError },
    ) => void,
    flight?: { inFlight?: number },
  ): Promise<void>;
}
```

A picture of each avatar, built a few at a time.

| Parameter | Type | Meaning |
|---|---|---|
| `manifests` | `string[]` | The avatars, each base64. |
| `opts` | [`HeadlessOptions`](#headlessoptions) | One set of options for every picture. |
| `fn` | `(index: number, result: HeadlessPicture \| { error: SonaError }) => void` | Called once a manifest, in order, with its index and its picture or its error. |
| `flight.inFlight` (optional) | `number` | Avatars built ahead while one is drawn. Default 4. |

Returns `Promise<void>`.

### headless.sequence()

```ts
interface SonaHeadless {
  sequence(
    manifestBase64: string,
    opts: HeadlessOptions,
    seq: { frames?: number; fps?: number; sweep?: number },
    fn: (index: number, frame: HeadlessPicture) => void,
  ): Promise<number>;
}
```

Frame i holds the clip at time + i / fps and turns the avatar by turn + sweep * i / frames. Resolves with the frame count.

| Parameter | Type | Meaning |
|---|---|---|
| `manifestBase64` | `string` | The avatar's 1,000-byte manifest, base64. |
| `opts` | [`HeadlessOptions`](#headlessoptions) | The pictures' size, framing, clip and colour; time is where the first frame holds the clip. |
| `seq.frames` (optional) | `number` | How many frames. Default: the clip's length at fps, or 36 for a sweep with no clip, else 1. |
| `seq.fps` (optional) | `number` | Frames a second of clip time. Default 30. |
| `seq.sweep` (optional) | `number` | Degrees the avatar turns over the frames. Default 0. |
| `fn` | `(index: number, frame: HeadlessPicture) => void` | Called with each frame's index and pixels. |

Returns `Promise<number>`.

### headless.close()

```ts
interface SonaHeadless {
  close(): void;
}
```

Frees its scene and its GPU context.

### HeadlessOptions

The options of one headless picture, as sona_render_options.

| Field | Type | Meaning |
|---|---|---|
| `width` (optional) | `number` | Pixels wide, 1 to 8192. Default 256. |
| `height` (optional) | `number` | Pixels high, 1 to 8192. Default 256. |
| `preset` (optional) | `'full' \| 'upper' \| 'bust' \| 'face'` | The framing. Default "full". |
| `yaw` (optional) | `number` | Degrees the camera moves round the preset's target. Default 0. |
| `pitch` (optional) | `number` | Degrees the camera moves up round the preset's target. Default 0. |
| `zoom` (optional) | `number` | The preset's distance is divided by this: 2 is twice as close. 0.05 or more. Default 1. |
| `turn` (optional) | `number` | Degrees the avatar turns about its feet. |
| `clip` (optional) | `ClipKey \| null` | A clip key, held at `time` seconds. Default: standing still. |
| `time` (optional) | `number` | Seconds into the clip to hold. Default 0. |
| `clear` (optional) | `[number, number, number, number]` | Premultiplied RGBA 0 to 1. Default transparent. |
| `credit` (optional) | `boolean` | "Powered by 360sona" in the corner. Default true; the licence still asks for the line somewhere when it is off. |
| `type` (optional) | `'image/png' \| 'image/webp' \| 'image/jpeg'` | The file's format, picture() only. Default "image/png". |
| `quality` (optional) | `number` | 0 to 1, for WebP and JPEG, picture() only. Default: the browser's own. |
| `waitSeconds` (optional) | `number` | How long to wait for the avatar. Default 120. |

### HeadlessPicture

| Field | Type | Meaning |
|---|---|---|
| `width` | `number` | Pixels wide. |
| `height` | `number` | Pixels high. |
| `rgba` | `Uint8Array` | The pixels, four bytes each (red, green, blue, alpha, not premultiplied), rows from the top. |

## The avatar editor element

`<sona-avatar-editor>`, the player-facing avatar creator as one element ([guide](../guides/web-editor.md)). `defineAvatarEditor()` registers it; the page opens it, the player makes or changes an avatar, and `open()` resolves with the manifest.

```js
import { defineAvatarEditor } from './sona-renderer.js';

defineAvatarEditor();   // registers <sona-avatar-editor>
const editor = document.createElement('sona-avatar-editor');
document.body.append(editor);
editor.sceneOptions = { appId: 'your-app' };
const manifest = await editor.open({ mode: 'quick' });
if (manifest) save(manifest);   // null when the player cancelled
```

### SonaAvatarEditor properties

| Field | Type | Meaning |
|---|---|---|
| `mode` | `AvatarEditorMode` | The screen. |
| `manifest` | `string \| null` | The manifest being edited (base64), or the attribute while closed. |
| `isOpen` | `boolean` | True while open. Read only. |
| `changed` | `boolean` | True when the avatar differs from the one it opened on. Read only. |
| `scene` | `SonaScene \| null` | The editor's scene while open (the SDK scene it draws in), or null. Read only. |
| `sceneOptions` | `Partial<CreateOptions>` | Options passed to SonaRenderer.create for the editor's scene (appId, host, pixelRatio, ...). Set before open. |
| `gamepad` | `boolean` | Read the standard gamepad while open. Default true. |
| `startScreen` | `'body' \| 'appearance' \| 'wardrobe'` | The full creator's first screen: "body" (default), "appearance" or "wardrobe". Set before open. |
| `itemFilter` | `((row: WardrobeItem) => boolean) \| null` | (row) => false leaves an item out of every list and every generated look. Set before open. |

### editor.open()

```ts
interface SonaAvatarEditor {
  open(
    opts?: { mode?: AvatarEditorMode; manifest?: string },
  ): Promise<string | null>;
}
```

Opens the editor. Resolves with the finished manifest on Done, or null on Cancel.

| Parameter | Type | Meaning |
|---|---|---|
| `opts.mode` (optional) | `AvatarEditorMode` | The screen. Default: the mode attribute, else "full". |
| `opts.manifest` (optional) | `string` | The manifest to start from. Default: the manifest attribute; none starts a new avatar. |

Returns `Promise<string | null>`.

### editor.done()

```ts
interface SonaAvatarEditor {
  done(): void;
}
```

Done: fires done with the manifest and closes.

### editor.cancel()

```ts
interface SonaAvatarEditor {
  cancel(): void;
}
```

Cancel: fires cancel and closes.

### editor.close()

```ts
interface SonaAvatarEditor {
  close(): void;
}
```

Closes without an event (the open promise gives null).

### editor.undo()

```ts
interface SonaAvatarEditor {
  undo(): void;
}
```

Undo the last edit.

### editor.redo()

```ts
interface SonaAvatarEditor {
  redo(): void;
}
```

Redo.

### editor.addEventListener()

```ts
interface SonaAvatarEditor {
  addEventListener<K extends keyof AvatarEditorEventMap>(
    type: K,
    fn: (e: AvatarEditorEventMap[K]) => void,
    opts?: boolean | AddEventListenerOptions,
  ): void;
  addEventListener(
    type: string,
    fn: EventListenerOrEventListenerObject,
    opts?: boolean | AddEventListenerOptions,
  ): void;
}
```

- `K`: Listens for one of the editor's events, its detail typed by AvatarEditorEventMap.
- `string`: Any other event, as on any element.

### defineAvatarEditor

```ts
declare const defineAvatarEditor: (
  name?: string,
) => SonaAvatarEditorConstructor;
```

Registers the avatar editor element, by default as `<sona-avatar-editor>`, and returns its class. Call once per page; a second call returns the same class.

### AvatarEditorMode

```ts
type AvatarEditorMode = 'full' | 'quick' | 'wardrobe';
```

The three screens: the whole creator, the quick creator (eight generated looks, then one tweak) and the wardrobe picker.

### AvatarEditorEventMap

The detail of the editor's events.

| Field | Type | Meaning |
|---|---|---|
| `open` | `CustomEvent<{ mode: AvatarEditorMode }>` | The editor opened (it then loads). |
| `change` | `CustomEvent<{ manifest: string; change: { op: string; [k: string]: unknown } }>` | An edit, an undo, a redo or a chosen look. `manifest` is the avatar now (base64). |
| `done` | `CustomEvent<{ manifest: string }>` | Done: the finished manifest. The editor closes. |
| `cancel` | `CustomEvent<Record<string, never>>` | Cancelled. The editor closes. |
| `error` | `CustomEvent<{ error: unknown; code: string \| null; message: string }>` | The scene or the catalogue could not be loaded, or the preview failed. |

## Face tracking

`SonaTrack`: webcam face tracking, MediaPipe's face landmarker in, an avatar's face and head out ([guide](../guides/face-tracking.md)).

### FaceTracker properties

| Field | Type | Meaning |
|---|---|---|
| `options` | `Record<string, unknown>` | The settings in use: the defaults with the ones createFaceTracker() was given. A copy. Read only. |

### tracker.feed()

```ts
interface FaceTracker {
  feed(frame: FaceFrame): void;
}
```

Takes one frame.

| Parameter | Type | Meaning |
|---|---|---|
| `frame` | [`FaceFrame`](#faceframe) | One frame of blendshape weights and head rotation; frameFromLandmarker() makes one. |

### tracker.state()

```ts
interface FaceTracker {
  state(): FaceTrackerState;
}
```

What the tracker makes of the frames so far.

Returns `FaceTrackerState`.

### tracker.reset()

```ts
interface FaceTracker {
  reset(): void;
}
```

Forgets every frame and hands the face back to the clip; a calibration is kept.

### tracker.calibrateBegin()

```ts
interface FaceTracker {
  calibrateBegin(): void;
}
```

The frames from calibrateBegin to calibrateEnd are the neutral face.

### tracker.calibrateEnd()

```ts
interface FaceTracker {
  calibrateEnd(): {
    frames: number;
    neutral: number[];
    head: number[];
  } | null;
}
```

Ends the calibration and uses it: the neutral face's 52 weights and the head's rest rotation [x, y, z, w]. Returns null when no frame came in.

Returns `{ frames: number; neutral: number[]; head: number[] } | null`.

### tracker.setCalibration()

```ts
interface FaceTracker {
  setCalibration(
    c: { frames: number; neutral: number[]; head: number[] } | null,
  ): void;
}
```

Uses a calibration saved earlier.

| Parameter | Type | Meaning |
|---|---|---|
| `c` | `{ frames: number; neutral: number[]; head: number[] } \| null` | A calibration calibrateEnd() returned, or null to drop it. |

### SonaTrack

Webcam face tracking: the page brings MediaPipe's face landmarker and a `<video>` with the camera; nothing leaves the browser.

| Field | Type | Meaning |
|---|---|---|
| `createFaceTracker` | `createFaceTracker(options?: Record<string, unknown>): FaceTracker` | options: mirror, noHead, noFace, noGaze; faceMinCutoff, faceBeta, headMinCutoff, headBeta, headGain, headLimitDeg, neckShare, sensitivity, lostSeconds, returnSeconds. |
| `startFaceTracking` | `startFaceTracking(opts: { video: HTMLVideoElement; landmarker: unknown; tracker: FaceTracker; avatar?: SonaAvatar \| null; calibrateSeconds?: number; onFrame?: (state: FaceTrackerState, frame: FaceFrame) => void }): () => void` | Runs the landmarker on each new video frame, feeds the tracker and, with an avatar, drives its face and head. Returns stop(). |
| `driveAvatar` | `driveAvatar(avatar: SonaAvatar, tracker: FaceTracker): () => void` | Puts the tracker's face and head on an avatar until the returned function is called; the avatar poses every frame meanwhile. |
| `frameFromLandmarker` | `frameFromLandmarker(result: unknown, timeSeconds: number): FaceFrame` | One FaceLandmarker result (detectForVideo) as a tracker frame. |

### FaceFrame

One frame for a face tracker: MediaPipe's 52 blendshapes (or ARKit's) and the head's rotation.

| Field | Type | Meaning |
|---|---|---|
| `time` | `number` | The frame's time in seconds, rising from frame to frame. |
| `found` | `boolean` | Whether a face was found in it; false lets the face go back to the clip after a moment. |
| `weights` (optional) | `number[] \| { categoryName: string; score: number }[]` | The 52 blendshape weights, 0 to 1, in the order layout names; or MediaPipe's categories, in any order. Needed when found. |
| `layout` (optional) | `number` | The order of a list of 52 numbers: 0 ARKit's, 1 MediaPipe's. Default 0. |
| `headRotation` (optional) | `[number, number, number, number]` | The head's rotation as a quaternion [x, y, z, w], in the camera's space. Default: none (the head keeps its rest turn). |

### FaceTrackerState

What a face tracker makes of the frames so far.

| Field | Type | Meaning |
|---|---|---|
| `tracking` | `boolean` | True once a face has been found, until it has been lost long enough to hand back to the clip. |
| `time` | `number` | The time of the last frame fed, in seconds. |
| `weight` | `number` | How much the tracked face and head show over the clip, 0 to 1: it eases in when a face is found and out when it is lost. |
| `expression` | `number[]` | Five shape indices: mouth, left brow, right brow, left eye, right eye. 255 leaves that part to the clip. |
| `mood` | `number` | The mood read from the face: 0 neutral, 1 sad, 2 angry, 3 confused, 4 laughing, 5 shocked, 6 happy. |
| `head` | `[number, number, number, number]` | The head's turn as a quaternion [x, y, z, w] in the body's space, smoothed and limited. |
| `weights` | `number[]` | The 52 blendshape weights after smoothing and calibration, 0 to 1, in ARKit's order. |

## Packages

Three packages put the same avatars in other libraries. Each is a thin layer over `SonaRenderer.connect()`
or a scene ([guide](../guides/web-wrappers.md)).

### @360sona/three

For three.js. Its declarations:

```ts
declare const VERSION: string;
declare class SonaAvatar extends Group {
  static load(
    connection: SonaConnection,
    manifest: string,
    opts?: { clips?: string[] | null; textures?: boolean },
  ): Promise<SonaAvatar>;
  readonly manifest: string;
  readonly model: Object3D;
  readonly mixer: AnimationMixer;
  animations: AnimationClip[];
  readonly clips: string[];
  current: string | null;
  play(
    key: string,
    opts?: { loop?: boolean; fade?: number; speed?: number },
  ): Promise<void>;
  stop(opts?: { fade?: number }): void;
  update(dt: number): void;
  dispose(): void;
}
declare function credit(
  connection: SonaConnection,
  renderer: WebGLRenderer | HTMLCanvasElement,
  corner?: string,
): { dispose(): void };
```

### @360sona/babylon

For Babylon.js. Its declarations:

```ts
declare const VERSION: string;
declare class SonaAvatar {
  static load(
    BABYLON: any,
    scene: any,
    connection: SonaConnection,
    manifest: string,
    opts?: { clips?: string[] | null; textures?: boolean },
  ): Promise<SonaAvatar>;
  readonly root: any;
  readonly meshes: any[];
  readonly animationGroups: any[];
  readonly manifest: string;
  readonly clips: string[];
  current: string | null;
  play(
    key: string,
    opts?: { loop?: boolean; speed?: number },
  ): Promise<void>;
  stop(): void;
  dispose(): void;
}
declare function credit(
  connection: SonaConnection,
  engine: any,
  corner?: string,
): { dispose(): void };
```

`SonaAvatar`: `BABYLON` is the Babylon namespace (`import * as BABYLON from '@babylonjs/core'`, or the global).

### @360sona/react

For React. Its declarations:

```ts
declare const VERSION: string;
declare function useSonaScene(): any | null;
declare function SonaCanvas(
  props: {
    sdk: any;
    appId?: string;
    host?: string;
    options?: Record<string, unknown> | null;
    onReady?: (scene: any) => void;
    onError?: (e: Error) => void;
    style?: CSSProperties;
    className?: string;
    children?: ReactNode;
  },
): ReactElement;
declare function SonaAvatar(
  props: {
    manifest: string;
    clip?: string;
    position?: [number, number, number] | null;
    turn?: number;
    scale?: number;
    camera?: 'full' | 'upper' | 'bust' | 'face' | null;
    onReady?: (avatar: any) => void;
  },
): null;
declare function SonaAvatarEditor(
  props: {
    sdk: any;
    open?: boolean;
    mode?: 'full' | 'quick' | 'wardrobe';
    manifest?: string | null;
    appId?: string;
    host?: string;
    sceneOptions?: Record<string, unknown> | null;
    onDone?: (manifest: string) => void;
    onCancel?: () => void;
    onChange?: (detail: unknown) => void;
    style?: CSSProperties;
    className?: string;
  },
): ReactElement;
```
