# Wireface SDK: free characters on the device

The SDK rigs photos into characters and animates them on the device. It is free for personal and commercial use, such as your own website; putting it into a product, app or service you sell or charge for, such as a SaaS product, needs a Developer or Enterprise Licence (see Licences below). Character creation, expressions, rendering and audio-driven lip-sync are free and need no account, key or network. Only drawn and stylised faces, which need AI to find, can use the optional detection API, which is free too. Canvas, 2D and three.js integrations live in one `@wireface/sdk` package.

Start with [Get the SDK](https://wireface.dev/docs/sdk/) for the download, installation and a complete first page. Download the installable SDK and the separate runnable examples from [your account](https://wireface.dev/account/#sdk). The SDK is distributed as compiled archives; access to a private GitHub repository is not required. Node 18 or later is needed for the example server; rendering and local creation run in a browser with WebGL2.

## Your first face

Give the canvas a size with CSS, then create a face. A wireframe needs no assets or key:

```html
<canvas id="face" style="width:320px;height:400px"></canvas>
```

```js
import { createFace } from '@wireface/sdk';
const face = createFace(document.querySelector('#face'));
face.express('happy', 3);
// When the component is removed:
// face.destroy();
```

This JavaScript belongs in a module script or a bundler entry point. Serve the page over HTTP or HTTPS. To wear a bundled portrait, configure the assets as described below, then call `await face.useCharacter('sarah')`. `useCharacter` accepts a catalogue id or a loaded character object; use `loadCharacter(url)` first for a saved file URL. The default transition is half a second; `{ transition: 0 }` switches immediately.

## Bundlers and assets

After installing the SDK into your app, copy its assets using the included command. It works on Windows, macOS and Linux:

```sh
npx --no-install wireface-assets public/wireface
```

Set the asset folder explicitly for each renderer. The 3D face uses the root; the 2D face uses its `2d/` subfolder:

```js
const face = createFace(canvas, { assets: '/wireface/' });
const picture = createFace2d(otherCanvas, { assets: '/wireface/2d/' });
```

Local creation needs the MediaPipe paths separately. Pass these paths to `createCharacter` as `mediapipe`, or directly as the second argument to `skinFromPhoto`:

```js
const mediapipe = {
  bundle: '/wireface/mediapipe/vision_bundle.mjs',
  wasm: '/wireface/mediapipe/wasm',
  model: '/wireface/mediapipe/face_landmarker.task',
};
const character = await createCharacter(photoFile, { mediapipe });
```

For Vite, keep the SDK out of dependency pre-bundling so the renderer's teeth and microphone files retain their package paths. Add this to `vite.config.js` (or `vite.config.mjs`):

```js
import { defineConfig } from 'vite';
export default defineConfig({
  optimizeDeps: { exclude: ['@wireface/sdk'] },
});
```

The SDK preserves the Vite annotation on its dynamic MediaPipe imports. Serve `.wasm` as `application/wasm` and `.mjs` as JavaScript. If your app is hosted under a subpath, prefix the example asset URLs with that subpath. Copy the assets again after upgrading the SDK. Install `three` separately for the optional three.js integration. See the [2D guide](https://wireface.dev/docs/2d/) and [three.js guide](https://wireface.dev/docs/three/) for their complete APIs.

With no bundler, unpack the SDK and serve `dist/` and `assets/` side by side. Import `./wireface/dist/wireface.js` in a module script; its default asset paths then work. An npm archive has a top-level `package/` directory; the runnable examples archive unpacks directly into your chosen directory. The [download guide](https://wireface.dev/docs/sdk/#examples) describes how to start it.

## Create characters on the device

```js
import { createFace, exportCharacter } from '@wireface/sdk';
import { createFace2d } from '@wireface/sdk/2d';
import { createCharacter } from '@wireface/sdk/create';
const portrait = await createCharacter(photoFile);              // 3D: the mesh is fitted to the face
await createFace(canvas).useCharacter(portrait);
const picture = await createCharacter(photoFile, { kind: '2d' }); // 2D: the picture itself moves
await createFace2d(otherCanvas).useCharacter(picture);
const saved = await exportCharacter(portrait);                   // save as portrait.wireface.json
```

MediaPipe finds the face's 468 landmarks in the browser. For 3D, the SDK fits the mesh's shape to them (jaw, face widths and heights, eyes, brows, nose, mouth) and builds the expression rig on the fitted shape. For 2D, it prepares the picture so the rig's movements carry onto it, sealing the lips and pinning the outline. No image is uploaded. The result is the same portable character the detection API returns, and it plays in `createFace`, `createFace2d` and three.js's `FaceMesh`. Pass `landmarks` to skip detection, or `mediapipe` to load MediaPipe from your own paths (see below).

MediaPipe reads photos, and realistic paintings and 3D renders of faces. It can't find most drawn, anime, pixel-art or creature faces. Those need Gemini's detection, which runs only on wireface.dev with your key. Pass a rigging client and `createCharacter` sends a 2D picture there when MediaPipe finds no face:

```js
import { createRiggingClient } from '@wireface/sdk/rigging';
const rigging = createRiggingClient({ getToken });               // see the detection API section
const character = await createCharacter(drawingFile, { kind: '2d', rigging });
```

`detector: 'local'` never leaves the device; `detector: 'hosted'` always uses the service, for a drawing MediaPipe might only half recognise. Without a client, a picture with no detectable face throws a `WirefaceError` with the code `face_not_found`. A 3D character always needs a clear, front-facing face MediaPipe can read.

## Fixed-mesh photo mapping

```js
import { createFace, skinFromPhoto } from '@wireface/sdk';
const face = createFace(canvas);
await face.useSkin(await skinFromPhoto(photoFile));
face.express('happy');
```

This detects landmarks on the device and maps the photo onto a baked, fixed mesh. It does not change facial geometry; `createCharacter` does. No image is uploaded and no account or key is needed once installed. MediaPipe JavaScript, CPU WASM and the detection model are bundled in `assets/mediapipe`; no CDN is needed. Serve the package's `dist/` and `assets/` folders together over local HTTP. With a bundler, copy `assets/` into your public directory, pass `{ assets: '/wireface-assets/' }` to the renderer and call `skinFromPhoto(file, { bundle: '/wireface-assets/mediapipe/vision_bundle.mjs', wasm: '/wireface-assets/mediapipe/wasm', model: '/wireface-assets/mediapipe/face_landmarker.task' })`. Serve `.wasm` as `application/wasm`. The first installation requires downloading the package; thereafter creation, mapping and playback work with external networking blocked. `createCharacter(file, { mediapipe: { ... } })` takes the same paths.

## The detection API (optional)

The detection API is for faces that need AI to find. It's free and optional, and it needs an API key from your Wireface account; nothing else in the SDK uses the key. It runs Gemini's detection on wireface.dev, then the same fitting the SDK does locally, and returns the character to you: Wireface doesn't host it. `createCharacter` calls it for you when you pass a client, as above, or call it directly:

```js
import { createRiggingClient } from '@wireface/sdk/rigging';
import { createFace2d } from '@wireface/sdk/2d';
import { FaceMesh } from '@wireface/sdk/three';
const rigging = createRiggingClient({
  getToken: async () => {
    const response = await fetch('/api/wireface-token', { method: 'POST' });
    if (!response.ok) throw new Error('Could not authorise rigging');
    return (await response.json()).token;
  },
});
const face = createFace2d(canvas);
await face.useCharacter(await rigging.rig2d(pictureFile));
face.express('happy');
const mesh = new FaceMesh();
await mesh.useCharacter(await rigging.rig3d(portraitFile));
scene.add(mesh);
```

Install `three` separately for the optional three.js integration. Use `examples/hosted/backend.mjs`: set `WIREFACE_SDK_KEY` in its environment, then `npm start`. It runs on localhost and issues five-minute tokens for only `rig:2d` and `rig:3d`, scoped to that browser origin. Production backends must authenticate their own users before issuing tokens. Never put permanent keys in browser bundles. The client rejects permanent keys in browser contexts.

```js
// Backend only, after authorising the application's user:
const rigging = createRiggingClient({ apiKey: process.env.WIREFACE_SDK_KEY });
const { token, expiresAt } = await rigging.createToken({
  scope: ['rig:2d'], origin: 'https://your-app.example',
});
```

`rig2d` and `rig3d` accept a File, Blob or image URL. URL images are fetched by the SDK and uploaded as bytes; the service does not fetch arbitrary URLs. Use JPEG, PNG or still WebP, at most 12 MB and 40 megapixels, with one clear face. 3D needs a front-facing portrait with visible facial detail; `createCharacter` makes the same 3D character on the device. 2D supports drawings and stylised characters. Unusable images are rejected; no manual or canonical fallback silently replaces your character.

```js
const abort = new AbortController();
const character = await rigging.rig3d(file, {
  signal: abort.signal,
  idempotencyKey: crypto.randomUUID(), // retain for a retry of the same submission
  onProgress: ({ stage, requestId }) => console.log(stage, requestId),
});
```

The client retries each failed HTTP operation for network failures and 429/502/503/504 responses at most twice by default, with bounded backoff. It has a three-minute overall timeout, configurable up to ten minutes. Cancelling stops polling and makes a best-effort server cancellation. `WirefaceError` exposes `code`, `status`, `requestId` and `retryable`. A submission interrupted before its job ID arrives can be retrieved by retrying with the same idempotency key and input. Reusing a key with different input returns `idempotency_conflict`. Completed results expire after 24 hours; metadata is retained for 90 days.

Common codes include `invalid_image`, `face_count`, `low_confidence`, `poor_anchors`, `anchor_disagreement`, `dense_face_missing`, `key_revoked`, `token_expired`, `scope_denied`, `busy`, `result_expired`, `provider_unavailable` and `processing_timeout`. Request a new browser token when it expires. Rotating/revoking a permanent key invalidates its outstanding browser tokens. Credentials do not affect saved-character playback.

## Whole 3D heads

`@wireface/sdk/heads` puts a whole 3D head on the face: ears, neck, shoulders in a top and hair, a head that turns all the way round and behaves like a person sitting there, in a room of your choice. Eight stock heads ship in `assets/heads/`.

```js
import { createFace } from '@wireface/sdk';
import { attachHead, loadStockHead } from '@wireface/sdk/heads';
const face = createFace(canvas, { assets: '/wireface/' });
const head = attachHead(face, await loadStockHead('sarah'), { look: { background: { kind: 'office' } } });
```

See the [heads guide](https://wireface.dev/docs/heads/).

## Export and offline playback

```js
import { loadCharacter, exportCharacter } from '@wireface/sdk';
const saved = await exportCharacter(character); // Blob; save as character.wireface.json
const restored = await loadCharacter(saved);    // also accepts URL or ArrayBuffer
await face.useCharacter(restored);
```

The versioned JSON contains an embedded raster texture, baked mesh and expression channels, jaw, eyes, mouth, render metadata and prepared 2D transfer data. It contains no credentials, expiring asset URLs or executable code. Loading validates and copies it before renderer replacement. File-based loading never invokes fitting or contacts Wireface. Fetching a character URL uses the network only to obtain that file. Legacy `.wface` version-1 documents remain loadable.

Feed any TTS provider's audio into `face.listenTo(audioContext, source)` or the clip/stream interfaces below. Lip-sync analysis and animation run locally. Cloud TTS has its own connectivity, account and charges. The optional Gemini Live conversation examples use a separate `GEMINI_API_KEY` in the backend environment; `GEMINI_LIVE_MODEL` can select a supported live model. The runnable examples include local creation (`examples/create/`), saved-character playback (`examples/playback/`), fixed-mesh mapping (`examples/3d/photo.html`) and hosted detection (`examples/hosted/`). The Node command `node examples/hosted/build-character.mjs photo.jpg character.wireface.json 3d` uses the hosted API and requires `WIREFACE_SDK_KEY`; `createCharacter` itself uses browser image APIs for local creation.

## Expressions, audio and cleanup

`express(name, seconds = 4)` sets a temporary expression; `mood(name)` sets the continuing mood. Names include `neutral`, `happy`, `excited`, `amused`, `surprised`, `curious`, `thinking`, `concerned`, `sad`, `afraid`, `frustrated`, `calm`, `content`, `bored` and `glum`. Unknown names throw. `state(name)` changes posture (`idle`, `thinking`, `busy`, `error`, `muted` or `asleep`). `set(patch)` applies validated config, such as `{ preset: 'cyan' }` or `{ skin_amount: 0.5 }`; invalid settings throw `ConfigError`.

Start audio on a user interaction so browser autoplay rules permit it. Connect an AudioNode to the speakers yourself; `listenTo` analyzes it and returns a detach function:

```js
const audioContext = new AudioContext();
playButton.onclick = async () => {
  await audioContext.resume();
  const bytes = await (await fetch('/voice.wav')).arrayBuffer();
  const source = audioContext.createBufferSource();
  source.buffer = await audioContext.decodeAudioData(bytes);
  source.connect(audioContext.destination);
  const detach = face.listenTo(audioContext, source);
  source.onended = detach;
  source.start();
};
```

`listenTo` also accepts an HTMLMediaElement or MediaStream. Stop microphone tracks yourself when you finish. Use `await face.say(await face.clip('sarah'), { audioContext })` for the included recorded speech, or `StreamVoice` for streaming PCM. `face.hush()` stops recorded speech. Listen to caption and speaking events with `face.on(callback)`; it returns an unsubscribe function. Call `face.destroy()` on component unmount and close AudioContexts your app owns. For React, create the renderer in an effect and destroy it in the effect's cleanup; create a fresh renderer when the effect runs again.

## Troubleshooting

- A blank canvas: give it a CSS width and height, check WebGL2 support and inspect the browser console. Rendering runs in the browser, not during server rendering.
- A character or voice request returns HTML: the asset URL points at your application's fallback page. Run `wireface-assets` and pass the correct `assets` folder, including the trailing slash.
- MediaPipe fails to import in Vite development: use SDK 0.3.1 or later, the Vite settings above and the explicit `mediapipe` paths.
- No face found: use a clear front-facing portrait, or use the optional hosted detector for a drawn 2D face. A blank image is rejected.
- No sound: create or resume the AudioContext inside a click, and connect your AudioNode to `audioContext.destination`.
- The hosted example cannot authorize: set `WIREFACE_SDK_KEY` in the example server's environment and restart it. A Gemini key is a separate credential for conversation examples.
- The example server's port is in use: set the `PORT` environment variable, restart the server and use the printed address.
- TypeScript: declarations ship with every entry; use a resolver that understands package exports, such as `moduleResolution: 'Bundler'` or `'NodeNext'`.

## Licences

Wireface has three licences. The Personal Licence is free for personal and commercial use, such as your own website: the SDK, character creation on the device, the characters you make and the detection API cost nothing. To put Wireface into a product, app or service you sell or charge for, such as a SaaS product, freelancers, indie developers and companies with fewer than 10 employees need a Developer Licence, which covers one named product or service for a year; companies with 10 or more employees need an Enterprise Licence (contact sales@compsmart.co.uk). See https://wireface.dev/license/ for prices. Renewal is manual, and end users need no account. The SDK never checks a licence: characters never contact a licence server or stop working.

The Developer Licence lets you put the compiled SDK into your product; it does not include source code. Only the Enterprise Licence can include the full SDK and integration source, including local creation (shape fitting, rig construction and 2D preparation). The detection API's code stays private and is excluded from every licence. Historical licences and third-party notices are preserved. Desktop and Chat have separate free offerings and licences.

## API contracts

The package includes `openapi.json` (OpenAPI 3.1), request/response schemas under `schemas/`, and TypeScript declarations for every entry. The optional rigging entry has no effect on playback dependencies. HTTP endpoints are `POST /api/rigging/v1/2d`, `POST /api/rigging/v1/3d`, `GET /api/rigging/v1/jobs/{id}`, `DELETE /api/rigging/v1/jobs/{id}`, and `POST /api/rigging/v1/tokens`.

The detection API uses structured Gemini observations, independent anatomical checks, dense server-side MediaPipe for 3D portraits, and the same fitter `@wireface/sdk/create` runs locally. Gemini does not generate rigging code. See [Gemini structured output](https://ai.google.dev/gemini-api/docs/structured-output) and [MediaPipe Python](https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker/python).

## Animate images already on a page

Use `animateImages()` from `@wireface/sdk/images` (also exported from the main SDK) to discover and animate all images, or pass `{ selector: ".portraits" }` to select images or containers. Silent expressions, blinks, pointer tracking and idle eye movements are free on your own website, a business one included, with no account, key or upload. Dynamic images and carousel visibility are handled automatically. A one-tag browser script is also available.

[Live gallery and carousel](https://wireface.dev/images/) | [Full configuration and lifecycle reference](https://wireface.dev/docs/images/) | [Downloadable examples](https://github.com/wireface/wireface-images)
