# Zappar for PlayCanvas

This library lets you use [Zappar](https://www.zappar.com/)'s best-in-class AR technology with content built in **PlayCanvas**. It supports image, face, world and instant world tracking.

It provides high performance tracking in the browsers already installed on your users' mobile phones, and it targets the modern PlayCanvas stack: **engine v2** and the **ESM scripting system**. The legacy `pc.createScript` global-scope scripts and engine v1 are **not** supported.

> **Migrating from version 1?** This is a breaking release. Scripts are now ES modules, attribute names have changed, and the graphics device must be WebGL2. There are no longer templates to drag in or a project to fork. See [Getting Started](#getting-started) and [CHANGELOG.md](CHANGELOG.md).

You may also be interested in:

- Zappar for ThreeJS ([website](https://zap.works/universal-ar/threejs/), [NPM](https://www.npmjs.com/package/@zappar/zappar-threejs))
- Zappar for A-Frame ([website](https://zap.works/universal-ar/aframe/), [NPM](https://www.npmjs.com/package/@zappar/zappar-aframe))
- Zappar for React+three.js ([website](https://zap.works/universal-ar/react/), [NPM](https://www.npmjs.com/package/@zappar/zappar-react-three-fiber))
- Zappar for Unity ([website](https://zap.works/universal-ar/unity/))
- Zappar for JavaScript ([website](https://zap.works/universal-ar/), [NPM](https://www.npmjs.com/package/@zappar/zappar)), if you'd like to build content with a different 3D rendering platform
- Mattercraft ([website](https://zap.works/mattercraft/)), a full 3D development environment built for AR, VR and MR

## Table Of Contents

<details>
<summary>Click to expand table of contents</summary>

<!--ts-->

- [Zappar for PlayCanvas](#zappar-for-playcanvas)
  - [Table Of Contents](#table-of-contents)
  - [Getting Started](#getting-started)
    - [PlayCanvas Editor](#playcanvas-editor)
      - [1. Import the library](#1-import-the-library)
      - [2. Enable WebGL 2](#2-enable-webgl-2)
      - [3. Add the Zappar camera](#3-add-the-zappar-camera)
      - [4. Add a tracker](#4-add-a-tracker)
    - [NPM Package](#npm-package)
  - [Overview](#overview)
  - [Local Preview and Testing](#local-preview-and-testing)
  - [Compatibility and Browser Support](#compatibility-and-browser-support)
    - [Detecting Browser Compatibility](#detecting-browser-compatibility)
  - [Hosting and Publishing Content](#hosting-and-publishing-content)
    - [Licensing](#licensing)
    - [ZapWorks Hosting](#zapworks-hosting)
    - [Self-hosting](#self-hosting)
    - [How the Library Finds Its Asset Files](#how-the-library-finds-its-asset-files)
  - [The Camera](#the-camera)
    - [Camera Attributes](#camera-attributes)
    - [Mirroring the Camera](#mirroring-the-camera)
    - [Camera Pose](#camera-pose)
    - [Switching Between Front and Rear Cameras](#switching-between-front-and-rear-cameras)
    - [Camera Events](#camera-events)
  - [Tracking](#tracking)
    - [Image Tracking](#image-tracking)
      - [Target File](#target-file)
      - [Setting Up an Image Tracker](#setting-up-an-image-tracker)
      - [Image Tracker Attributes](#image-tracker-attributes)
      - [Image Tracker Events](#image-tracker-events)
      - [Image Target Preview Mesh](#image-target-preview-mesh)
    - [Face Tracking](#face-tracking)
      - [Setting Up a Face Tracker](#setting-up-a-face-tracker)
      - [Face Tracker Attributes](#face-tracker-attributes)
      - [Face Tracker Events](#face-tracker-events)
    - [Face Landmarks](#face-landmarks)
      - [Setting Up a Face Landmark](#setting-up-a-face-landmark)
    - [Face Mesh](#face-mesh)
      - [Setting Up a Face Mesh](#setting-up-a-face-mesh)
      - [Face Mesh Attributes](#face-mesh-attributes)
      - [Head Masking](#head-masking)
    - [World Tracking](#world-tracking)
      - [Setting Up a World Tracker](#setting-up-a-world-tracker)
      - [Tracking Quality](#tracking-quality)
    - [Instant World Tracking](#instant-world-tracking)
      - [Setting Up an Instant Tracker](#setting-up-an-instant-tracker)
      - [Placement Mode](#placement-mode)
  - [Realtime Camera-based Reflections](#realtime-camera-based-reflections)
    - [Environment Map](#environment-map)
    - [Probe Sphere](#probe-sphere)
  - [Snapshots and Social Sharing](#snapshots-and-social-sharing)
  - [Scripting Against the Library](#scripting-against-the-library)
    - [Reaching the Underlying Zappar Objects](#reaching-the-underlying-zappar-objects)
    - [Waiting for the Camera](#waiting-for-the-camera)
    - [Positioning Your Own Content From an Anchor](#positioning-your-own-content-from-an-anchor)
  - [Script Reference](#script-reference)
  - [Event Reference](#event-reference)
  - [Development](#development)
  - [Links and Resources](#links-and-resources)

<!-- Created by https://github.com/ekalinin/github-markdown-toc -->

<!--te-->

</details>

## Getting Started

There are two ways to use this library, depending on how you build your project:

- **[PlayCanvas Editor](#playcanvas-editor)**: download a zip, drag the files into your project, and attach scripts to entities in the inspector. No build tooling required.
- **[NPM Package](#npm-package)**: install from npm and attach the scripts in code. For engine-only projects with your own bundler.

### PlayCanvas Editor

#### 1. Import the library

Download the bundle from:
<https://libs.zappar.com/zappar-playcanvas/2.0.0-beta.2/zappar-playcanvas.zip>

Unzip it, then drag **every file** into your project's `ASSETS` panel. A single folder is fine. You'll be importing three kinds of file:

| Files | What they are |
| --- | --- |
| `zappar-camera.mjs`, `zappar-image-tracker.mjs`, … | The scripts you attach to entities. |
| `zappar-lib.mjs`, `zappar-rolldown-runtime.mjs` | Shared code the scripts import. Not attached to anything. |
| `zappar-cv.wasm`, `zappar-worker.mjs`, `zappar-ceres-worker.mjs`, `zappar-*.zbin` | The computer vision runtime and face models, loaded on demand at runtime. |

Three things to be aware of:

- **Keep the filenames exactly as they are.** At runtime the camera looks the CV files up by name in the PlayCanvas asset registry, because the Editor serves every upload from its own content-hashed URL. Renaming `zappar-cv.wasm`, or any other `zappar-*` file, will break loading. The `zappar-` prefix is there so these can't collide with your project's own assets.
- **Keep them all in one folder.** The scripts import the shared chunks by relative path.
- You don't need to mark any of them as *preload*. The wasm and face models are fetched on demand, which keeps your initial load small.

The Editor picks up the `.mjs` files as ESM script assets automatically and reads each script's attributes, so they'll appear in the inspector when you attach one.

#### 2. Enable WebGL 2

Zappar's computer vision library runs on WebGL2 and **cannot run on WebGPU**. Open your project's `SETTINGS` and expand the `RENDERING` section:

- **Enable WebGL 2**: on
- **Enable WebGPU**: off

PlayCanvas prefers WebGPU when it's enabled and the device supports it, so leaving it on will give you a WebGPU device and `zapparCamera` will refuse to start.

#### 3. Add the Zappar camera

Every scene needs exactly one Zappar camera. It draws the camera feed behind your content and takes over the camera's projection so your 3D content lines up with the real world.

1. Select the entity that has your `camera` component, or create one via `Add Component` > `Camera`.
2. `Add Component` > `Script`.
3. In the script component, add `zapparCamera`.

Remove or disable any other cameras in the scene, or make sure the Zappar camera is the active one.

You don't need to do anything about the skybox. The camera removes the `Skybox` layer from its own layer list so it can't cover the feed.

It's also worth attaching `zapparBrowserUtil` to any entity in the scene. See [Detecting Browser Compatibility](#detecting-browser-compatibility).

#### 4. Add a tracker

A tracker is a script on an entity. Whatever you parent under that entity gets tracked. Pick your tracking type and follow the setup steps:

- [Image Tracking](#setting-up-an-image-tracker) attaches content to a photo, poster, business card or product label
- [Face Tracking](#setting-up-a-face-tracker) attaches content to a user's face
- [World Tracking](#setting-up-a-world-tracker) attaches content to a SLAM-tracked map of the user's environment
- [Instant World Tracking](#setting-up-an-instant-tracker) attaches content to a point on a surface in front of the user

### NPM Package

Install the library alongside PlayCanvas:

```bash
npm install --save @zappar/zappar-playcanvas playcanvas
```

Then register the scripts with your app and attach them by name, exactly as the Editor does. Attributes go in `properties`, which the script component assigns onto the instance for you:

```ts
import { Application, Color, DEVICETYPE_WEBGL2, Entity } from 'playcanvas';
import { registerZapparScripts } from '@zappar/zappar-playcanvas';

const app = new Application(canvas, {
  // Zappar's computer vision requires WebGL2.
  graphicsDeviceOptions: { deviceTypes: [DEVICETYPE_WEBGL2] },
});

// Makes every Zappar script attachable by name.
registerZapparScripts(app);

// The Zappar camera draws the camera feed and drives the scene projection.
const camera = new Entity('camera');
camera.addComponent('camera', { clearColor: new Color(0, 0, 0, 1) });
camera.addComponent('script');
camera.script?.create('zapparCamera');
app.root.addChild(camera);

// An image tracker, with its attributes set at creation.
const tracker = new Entity('image-tracker');
tracker.addComponent('script');
tracker.script?.create('zapparImageTracker', {
  properties: { targetFile: myZptAsset },
});
app.root.addChild(tracker);

// Anything parented here is tracked to the image.
tracker.addChild(myContent);

app.start();
```

You can also import the classes directly (`ZapparCamera`, `ZapparImageTracker`, and so on) and pass them to `create()` by reference instead of registering them by name.

If you need a typed handle on a script later, for example to read tracking data each frame, note that the engine declares `create()` and `get()` as `ScriptType | null`, so narrow the result yourself:

```ts
import type { ZapparImageTracker } from '@zappar/zappar-playcanvas';

const imageTracker = tracker.script?.get('zapparImageTracker') as ZapparImageTracker;
```

This library ships as ESM with TypeScript types. `playcanvas` is a peer dependency and `@zappar/zappar` a regular one, so both dedupe against your own install.

Your bundler needs to support `new URL(..., import.meta.url)` asset references, which is how the CV library locates its wasm and face models. **Webpack 5+**, Vite and Rollup all handle this. If you use `zapparBrowserUtil`, its QR-code dependency has a Node-only code path that never runs in the browser; with Webpack you may need to stub it:

```js
resolve: { fallback: { fs: false } }
```

The npm package contains the library only. The Editor scripts in `dist/` are a build artifact, so see [Development](#development) if you want to build them yourself rather than downloading the zip.

## Overview

Everything in this library is a PlayCanvas script, and there are two kinds:

- **`zapparCamera`** goes on your camera entity. It owns the Zappar *pipeline*, the object that pulls in camera frames, runs the computer vision, and hands out tracking results. It draws the camera feed on its own background layer and overrides the camera's projection matrix to match the physical camera's optics.
- **Trackers** go on content entities. Each frame, a tracker asks the pipeline where its target is and moves its own entity there. Your 3D content is parented underneath, so it comes along.

A typical hierarchy looks like this:

```
Root
├── Camera                  <- camera component + zapparCamera
├── Light
└── Image Tracker           <- zapparImageTracker
    └── My Model            <- your content
```

Trackers find the scene's `zapparCamera` on their own, so in the common single-camera case you don't need to wire anything together. Set a tracker's **Camera** attribute only if you have more than one Zappar camera. With several, the automatic lookup resolves to whichever initialized most recently.

The scripts talk to each other, and to you, over PlayCanvas app events (`app.fire` and `app.on`). That's how you find out that a target became visible, and how you trigger things like flipping the camera or taking a snapshot. See the [Event Reference](#event-reference).

## Local Preview and Testing

Due to browser restrictions surrounding use of the camera, you must use HTTPS to view or preview your site, even if doing so locally from your computer.

The Editor's `LAUNCH` button already serves over HTTPS, so previewing an Editor project works out of the box. Open the launch URL on your phone.

For engine-only projects, the [ZapWorks command-line tool](https://www.npmjs.com/package/@zappar/zapworks-cli) can serve a folder over HTTPS:

```bash
zapworks serve .
```

The command also lets you serve the folder for access by other devices on your local network, like this:

```bash
zapworks serve . --lan
```

## Compatibility and Browser Support

This library works well on the browsers that enjoy the vast majority of mobile market-share. That said, there are a number of web browsers available across the mobile and desktop device landscape.

_Best support:_

- Safari for iOS (version 11.3 and later)
- Chrome for Android (versions from at least the last year)

_Functional but not our primary support target (support quality):_

- Most Webkit/Blink-based web browsers for Android, including Brave (good)
- Most third-party web browsers for iOS from iOS 14.3 and later (good)
- iOS in-app web views implemented with SFSafariViewController (good)
- iOS in-app web views implemented with WKWebView from iOS 14.3 (good)
- Firefox for Android (good, however performance may be lower than other browsers)
- Chrome for Mac/Windows (\*)
- Firefox for Mac/Windows (\*)
- Safari for Mac (\*)

_Known to not work:_

- iOS in-app web views implemented with WKWebView prior to iOS 14.3 - this iOS technology does not support camera access at all and thus we're unable to support it. Apple rectified this issue in iOS 14.3.
- iOS in-app web views implemented with the deprecated UIWebView component - this iOS technology does not support camera access at all and thus we're unable to support it.
- Non-Safari web browsers on iOS, including Chrome, Firefox and Brave, before iOS 14.3 - these browsers use WKWebView due to App Store restrictions and thus do not support camera access.
- Any browser where PlayCanvas resolves to a WebGPU graphics device. See [Enable WebGL 2](#2-enable-webgl-2).

\* Browsers without motion sensor access (e.g. desktop browsers) don't support instant world tracking or attitude-based camera poses.

### Detecting Browser Compatibility

Attach the `zapparBrowserUtil` script to any entity in your scene to check the browser on startup. It has two attributes:

| Attribute | Default | Description |
| --- | --- | --- |
| **Compatibility Check** | `true` | Shows Zappar's built-in full-page dialog when the browser is unsupported, and stops rendering. The dialog provides a button to 'copy' the current page URL so the user can 'paste' it into a compatible browser. |
| **Mobile Only** | `false` | Shows a QR-code overlay on desktop, so the user can scan through to the experience on their phone. |

If you'd rather build your own UI, the underlying checks are available from `@zappar/zappar`:

```ts
import { browserIncompatible, browserIncompatibleUI } from '@zappar/zappar';

if (browserIncompatible()) {
  browserIncompatibleUI();
  throw new Error('Unsupported browser');
}
```

## Hosting and Publishing Content

Once you've built your experience, you have a number of options for hosting it:

- Using ZapWorks' integrated hosting
- Publishing from the PlayCanvas Editor
- Self-hosting on servers and a domain that you manage

### Licensing

This wrapper library is MIT licensed (see [LICENSE](LICENSE)), but relies on our proprietary computer vision library, `@zappar/zappar-cv`, for which you must maintain an active subscription at [ZapWorks](https://zap.works).

If you are self-hosting your experience, you will have to register the full domain name with ZapWorks in order for the license check to complete successfully. See the [Universal AR licensing docs](https://docs.zap.works/universal-ar/general/licensing/) for how to add a license and register a domain.

You do **not** need to register a domain name if you're hosting your experience:

- with ZapWorks (a `*.zappar.io` domain name); or,
- locally for testing (with one of the following hostnames: `0.0.0.0`, `127.*`); or,
- on your local network (with one of the following hostnames: `192.*`, `10.*`); or,
- using [ngrok](https://ngrok.com/) (a `*.ngrok.io` domain name).

### ZapWorks Hosting

ZapWorks provides an easy-to-use and robust hosting solution for your AR experiences as part of your subscription. To get started, head over to [zap.works](https://zap.works).

Once you've logged in, you can create a new 'Universal AR' project using the + button. Head over to the "Experience" tab where you can either upload a ZIP of your website directly, or find instructions for using the [ZapWorks command-line tool](https://www.npmjs.com/package/@zappar/zapworks-cli) to complete the upload.

To get a ZIP out of the PlayCanvas Editor, use `PUBLISH` > `DOWNLOAD .ZIP`.

For more information, head over to our [Publishing and Hosting](https://docs.zap.works/universal-ar/publishing-and-hosting/) docs article.

### Self-hosting

If you'd like to self-host your content, there are a number of recommendations we make to ensure the best experience for end-users:

- You need to register your domain name with ZapWorks so that it passes the license check. See the [Universal AR licensing docs](https://docs.zap.works/universal-ar/general/licensing/).
- You must serve the content over HTTPS (due to browser restrictions surrounding the camera)
- Files ending with the `.wasm` file extension should be served with the `application/wasm` mime-type
- Several files compress well using `Content-Encoding: gzip`. In particular you should serve files with the following extensions with gzip content-encoding: `.wasm`, `.js`, `.mjs`, `.zbin`, `.zpt`

### How the Library Finds Its Asset Files

The CV runtime needs a WebAssembly binary (`zappar-cv.wasm`), two module workers, and face model files (`.zbin`) at runtime. How they're located depends on how you're building:

- **In the Editor**, the camera resolves them by name from the PlayCanvas asset registry. This is why the filenames matter and why they're all namespaced `zappar-`. It happens automatically, so you just have to have uploaded the files.
- **Via npm**, your bundler emits them next to your JavaScript and the library finds them there.

If you need to serve them from somewhere else, such as a CDN, register a file locator before the camera initializes:

```ts
import { setFileLocator } from '@zappar/zappar';

setFileLocator((filename) => `https://my-cdn.example.com/zappar/${filename}`);
```

The locator is called once for each asset with its filename; return the URL to load it from, or a falsy value to keep the default.

## The Camera

`zapparCamera` goes on an entity with a `camera` component. It:

- sets the camera's projection matrix from the physical camera's parameters (e.g. focal length) every frame, so virtual content matches the real world;
- draws the camera feed as a fullscreen background on its own layer, inserted before every other layer so tracked content composites on top;
- positions and rotates the camera entity according to the chosen [camera pose](#camera-pose);
- excludes the `Skybox` layer from itself, so a scene skybox can't cover the feed.

### Camera Attributes

| Attribute | Default | Description |
| --- | --- | --- |
| **Front Facing Camera** | `false` | Use the front-facing ('selfie') camera instead of the rear camera. Useful for face filters. |
| **Mirror Mode** | `none` | How the scene and camera feed are mirrored: `none`, `poses` or `css`. See [Mirroring the Camera](#mirroring-the-camera). |
| **Pose Mode** | `default` | How the camera moves around the scene: `default`, `attitude` or `anchor`. See [Camera Pose](#camera-pose). |
| **Near Clip** | `0.01` | Near clipping plane. |
| **Far Clip** | `100` | Far clipping plane. |

### Mirroring the Camera

For an experience featuring the user-facing camera to feel natural, the view must be mirrored. **Mirror Mode** offers two ways to do it:

- **`poses`** mirrors the background camera texture and flips the X axis of anchor poses, so content still appears correctly tracked. Your content itself isn't flipped, so text in your tracked content doesn't appear mirrored. This is usually what you want with the selfie camera.
- **`css`** applies a `scaleX(-1)` CSS transform to the whole canvas. Both the camera feed and your content appear mirrored, including any text.
- **`none`** performs no mirroring. This is the right choice for the rear-facing camera.

### Camera Pose

**Pose Mode** controls where the origin of your scene is, and therefore how the camera and anchors move relative to each other:

- **`default`**: the camera stays at the origin of the scene, pointing down the negative Z axis. Tracked anchors move around in your scene as the user moves the device or the tracked object.
- **`attitude`**: the camera stays at the origin but rotates as the user rotates the physical device. When the library initializes, the negative Z axis of world space points forward in front of the user.
- **`anchor`**: the origin of the scene becomes the anchor being tracked, and the camera moves and rotates around it. The tracker on the entity provides that anchor automatically.

The right choice depends on your content:

- To have a light that always shines down from above the user, regardless of the angle of the device or anchors, use `attitude` and point a light down the negative Y axis of world space.
- In a physics simulation of stacked blocks with gravity pointing down the negative Y axis, `anchor` mode would let the blocks rest on a tracked image regardless of how the user holds it, while `attitude` would let the user tip the blocks off the image by tilting it.

### Switching Between Front and Rear Cameras

Fire an event, typically from a button handler:

```ts
// Explicitly choose the front-facing camera
this.app.fire('zappar:camera', { message: 'flip', userFacing: true });

// Or omit userFacing to toggle
this.app.fire('zappar:camera', { message: 'flip' });
```

You can also call `flip()` on the script directly if you have a reference to it.

Remember to update **Mirror Mode** to suit, since users expect a mirrored view of the selfie camera.

### Camera Events

```ts
this.app.on('zappar:camera', (ev) => {
  if (ev.message === 'permission_granted') {
    // ev.granted is true if the user allowed camera access
  }
});
```

The camera also fires `zappar:camera:ready` with itself as the payload once its pipeline exists. Use this if your own script needs the pipeline, or better, use [`onZapparCameraReady`](#waiting-for-the-camera), which also handles the case where the camera is already up.

## Tracking

The library offers four types of tracking for you to build augmented reality experiences with:

- **Image Tracking** can detect and track a flat or curved image in 3D space. This is great for building content that's augmented onto business cards, posters, magazine pages, bottles, etc.
- **Face Tracking** detects and tracks the user's face. You can attach 3D objects to the face itself, or render a 3D mesh that's fit to (and deforms with) the face as the user moves and changes their expression. You could build face-filter experiences to allow users to try on different virtual sunglasses, for example, or to simulate face paint.
- **World Tracking** builds a map of the environment around the user and lets you place 3D content into that space. With this tracking type you could build a 3D model viewer that lets users walk around to view the model from different angles, or an experience that places an animated character in their room.
- **Instant World Tracking**, like world tracking, attaches content to a point in the room or immediate environment around the user. It doesn't require as much initialization and user movement as world tracking, but doesn't provide as stable an anchor in space.

### Image Tracking

#### Target File

Image trackers use a special 'target file' that's been generated from the source image you'd like to track. You can generate one using the ZapWorks command-line utility like this:

```bash
zapworks train myImage.png
```

For more information on generating target files, including how to build them for curved or cylindrical surfaces, check out the [ZapWorks CLI documentation](https://docs.zap.works/universal-ar/useful-packages/zapworks-cli/).

#### Setting Up an Image Tracker

1. Drag your `.zpt` file into the Editor's `ASSETS` panel. It imports as a **binary** asset.
2. Create a new entity for your tracked content, e.g. `Image Tracker`.
3. `Add Component` > `Script`, and add `zapparImageTracker`.
4. Set the **Target File** attribute to your `.zpt` asset.
5. Parent your 3D content under the tracker entity.

```
Root
├── Camera                  <- camera component + zapparCamera
└── Image Tracker           <- zapparImageTracker, Target File = myImage.zpt
    └── My Model            <- your content
```

The tracker entity's transform is overwritten every frame, so put any authoring offsets on your content, not on the tracker.

The coordinate system has its origin at the centre of the image, with the positive X axis to the right, the positive Y axis towards the top and the positive Z axis coming up out of the plane of the image. For curved targets, the origin is at the centre of the cylinder defined by the curve. If the physical size of the image was included when the target file was generated (using the `input-width`, `input-height` or `dpi` parameters), the units are metres. Otherwise the scale is such that a Y value of +1 is the top of the image and -1 the bottom, so the X positions of the left and right edges depend on the image's aspect ratio.

#### Image Tracker Attributes

| Attribute | Default | Description |
| --- | --- | --- |
| **Target File** | none | The `.zpt` target file, as a binary asset. Required. |
| **Target Upright** | `true` | Rotates content 90° about X, so content authored Y-up stands up out of a target lying flat. Turn this off to use the target's own coordinate system, with +Z out of the image plane. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

#### Image Tracker Events

Events are fired on `this.app` and carry a `message` property:

```ts
this.app.on('zappar:image_tracker', (ev) => {
  switch (ev.message) {
    // The target file has finished loading.
    case 'target_loaded':
      break;

    // A new anchor was created by the tracker.
    case 'new_anchor':
      console.log(ev.anchor);
      break;

    // An anchor became visible in a camera frame.
    case 'anchor_visible':
      console.log(ev.anchor);
      break;

    // An anchor was visible in the previous frame but isn't in this one.
    case 'anchor_not_visible':
      console.log(ev.anchor);
      break;
  }
});
```

`ev.anchor` is the underlying `Zappar.ImageAnchor`. Note that an image tracker tracks one image in view at a time.

#### Image Target Preview Mesh

While authoring, it's useful to see the target image in the scene so you can line your content up against it. The `zapparImageTargetPreviewMesh` script builds a flat mesh from the preview image embedded in the target file.

1. Create a child entity of your image tracker.
2. `Add Component` > `Script`, and add `zapparImageTargetPreviewMesh`.
3. Set **Image Tracker Entity** to the tracker entity.

| Attribute | Default | Description |
| --- | --- | --- |
| **Image Tracker Entity** | blank | The entity holding the `zapparImageTracker` that owns the target. Required. |
| **Target Index** | `0` | Which target in the file to preview. |

The script adds a `render` component to its own entity, so give it a dedicated entity. Disable it before you ship.

### Face Tracking

#### Setting Up a Face Tracker

1. Create a new entity for your tracked content, e.g. `Face Tracker`.
2. `Add Component` > `Script`, and add `zapparFaceTracker`.
3. Parent your 3D content under the tracker entity.
4. On your `zapparCamera`, turn on **Front Facing Camera** and set **Mirror Mode** to `poses`.

```
Root
├── Camera                  <- zapparCamera (Front Facing Camera on, Mirror Mode = poses)
└── Face Tracker            <- zapparFaceTracker
    └── Sunglasses          <- your content
```

The coordinate system has its origin at the centre of the head, with the positive X axis to the right, the positive Y axis towards the top and the positive Z axis coming forward out of the user's face.

The face tracking model file loads automatically. Listen for `model_loaded` if you want to show a loading screen while it downloads.

#### Face Tracker Attributes

| Attribute | Default | Description |
| --- | --- | --- |
| **Max Faces** | `1` | How many faces to look for, 1 to 4. Values above 1 may reduce framerate, so stick with 1 unless you need more. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

> With **Max Faces** above 1, this script still moves a single entity, following the last visible anchor. To place content on several faces at once, listen for `new_anchor` and drive your own entities from the anchors. See [Positioning Your Own Content From an Anchor](#positioning-your-own-content-from-an-anchor).

#### Face Tracker Events

```ts
this.app.on('zappar:face_tracker', (ev) => {
  switch (ev.message) {
    // The face tracking model has finished loading.
    case 'model_loaded':
      break;

    case 'new_anchor':
      console.log(ev.anchor);
      break;

    case 'anchor_visible':
      console.log(ev.anchor);
      break;

    case 'anchor_not_visible':
      console.log(ev.anchor);
      break;
  }
});
```

`ev.anchor` is the underlying `Zappar.FaceAnchor`.

### Face Landmarks

In addition to the centre of the head, you can attach content to known points on the face. Landmarks stay accurate even as the user's expression changes.

The following landmarks are available: `EYE_LEFT`, `EYE_RIGHT`, `EAR_LEFT`, `EAR_RIGHT`, `NOSE_BRIDGE`, `NOSE_TIP`, `NOSE_BASE`, `LIP_TOP`, `LIP_BOTTOM`, `MOUTH_CENTER`, `CHIN`, `EYEBROW_LEFT` and `EYEBROW_RIGHT`. Note that 'left' and 'right' here are from the user's perspective.

#### Setting Up a Face Landmark

1. Set up a face tracker as above.
2. Create a new entity at the scene root, **not** a child of the face tracker. The landmark script sets its entity's world transform directly, including the head pose.
3. `Add Component` > `Script`, and add `zapparFaceLandmark`.
4. Set **Face Tracker Entity** to your face tracker entity.
5. Set **Landmark** to the feature you want.
6. Parent your content under the landmark entity.

```
Root
├── Camera                  <- zapparCamera
├── Face Tracker            <- zapparFaceTracker
└── Nose Landmark           <- zapparFaceLandmark (Face Tracker Entity = Face Tracker, Landmark = NOSE_TIP)
    └── Clown Nose          <- your content
```

| Attribute | Default | Description |
| --- | --- | --- |
| **Face Tracker Entity** | blank | The entity holding the `zapparFaceTracker` to read anchors from. Required. |
| **Landmark** | `NOSE_TIP` | Which face feature to track. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

Add one entity per landmark you want to track.

### Face Mesh

The library provides meshes that fit the face and deform as the user's expression changes. Use them to apply a texture to the user's skin, much like face paint, or to mask out the back of 3D models so the user's head isn't occluded where it shouldn't be.

Two meshes are included:

- The **default face** mesh covers the face, from the chin at the bottom to the forehead, and from the sideburns on each side.
- The **full head simplified** mesh covers the whole head, including some neck. It's ideal for [head masking](#head-masking).

#### Setting Up a Face Mesh

1. Set up a face tracker as above.
2. Create a new entity as a **child of the face tracker**, so it inherits the tracked pose.
3. `Add Component` > `Script`, and add `zapparFaceMesh`.
4. Set **Face Tracker Entity** to the face tracker entity.
5. Optionally assign a **Material**. Leave it blank for a plain default.

```
Root
├── Camera                  <- zapparCamera
└── Face Tracker            <- zapparFaceTracker
    └── Face Mesh           <- zapparFaceMesh (Face Tracker Entity = Face Tracker)
```

The script creates and updates a `render` component on its own entity, replacing any existing one, so give the mesh a dedicated entity.

#### Face Mesh Attributes

| Attribute | Default | Description |
| --- | --- | --- |
| **Face Tracker Entity** | blank | The entity holding the `zapparFaceTracker` to read anchors from. Required. |
| **Full Head** | `false` | Use the full-head simplified mesh instead of the face mesh. |
| **Mask** | `false` | Render as an occluder. See [Head Masking](#head-masking). |
| **Fill Mouth** | `false` | Fill the mouth cavity. |
| **Fill Eye Left** | `false` | Fill the left eye. |
| **Fill Eye Right** | `false` | Fill the right eye. |
| **Material** | blank | Material for the mesh. A default is created when blank. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

The mesh fires an event once it's ready:

```ts
this.app.on('zappar:face_mesh', (ev) => {
  if (ev.message === 'mesh_loaded') {
    // The mesh has loaded and is being rendered.
  }
});
```

#### Head Masking

If you're placing a 3D model around the user's head, such as a helmet, you need to make sure the camera view of the user's real face isn't hidden by the back of the model.

Set up a second `zapparFaceMesh` with both **Full Head** and **Mask** turned on. In mask mode the mesh writes to the depth buffer but not the colour buffer, so the camera feed shows through wherever the user's head is, and geometry behind it is hidden.

```
Root
└── Face Tracker            <- zapparFaceTracker
    ├── Head Mask           <- zapparFaceMesh (Full Head on, Mask on)
    └── Helmet              <- your content
```

If you assign a **Material** to a masking mesh, the script clones it before changing its render state, so the same material stays usable elsewhere in your scene.

### World Tracking

World tracking builds a map of the user's environment so content can sit in it. It needs the user to move their device around for a few seconds after startup before the map is usable.

#### Setting Up a World Tracker

1. Create a new entity, e.g. `World Tracker`.
2. `Add Component` > `Script`, and add `zapparWorldTracker`.
3. Choose an **Anchor Type**.
4. Parent your 3D content under the tracker entity.

```
Root
├── Camera                  <- zapparCamera
└── World Tracker           <- zapparWorldTracker (Anchor Type = ground)
    └── My Model            <- your content
```

| Attribute | Default | Description |
| --- | --- | --- |
| **Anchor Type** | `world` | `world` anchors to the point where the camera was when tracking initialized. `ground` tracks the system's best estimate of the floor beneath the user, initially 1.5 m below the world anchor, then refined to the lowest detected horizontal plane. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

#### Tracking Quality

Use the quality events to show and hide your own "move your device around" prompt:

```ts
this.app.on('zappar:world_tracker', (ev) => {
  switch (ev.message) {
    // The system understands the environment; the anchor is meaningful.
    case 'quality_good':
      break;

    // Tracking was lost, perhaps because the environment changed a lot, or the
    // user came back to the page later. Prompt them to move the device again.
    case 'quality_limited':
      break;
  }
});
```

Note that desktop browsers without motion sensors don't support world tracking.

### Instant World Tracking

Instant world tracking attaches content to a point on a surface in front of the user, without a tracking image and without the initialization world tracking needs.

#### Setting Up an Instant Tracker

1. Create a new entity, e.g. `Instant Tracker`.
2. `Add Component` > `Script`, and add `zapparInstantTracker`.
3. Parent your 3D content under the tracker entity.
4. Optionally wire up a placement button, as described below.

```
Root
├── Camera                  <- zapparCamera
├── Instant Tracker         <- zapparInstantTracker
│   └── My Model            <- your content
└── 2D Screen
    └── Tap To Place        <- element component, Use Input on
```

| Attribute | Default | Description |
| --- | --- | --- |
| **Anchor Camera Offset** | `0, 0, -5` | The camera-space point the anchor tracks from before placement. |
| **Placement Button** | blank | An entity with an `element` component. Tapping it toggles placement. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

The coordinate system has its origin at the chosen point, with the positive Y axis pointing up out of the surface and X and Z in the plane of the surface. How far the point is from the camera, which is to say how negative Z is in **Anchor Camera Offset**, determines the scale of that coordinate system.

#### Placement Mode

Until content is placed, the anchor tracks the point given by **Anchor Camera Offset** each frame, so the content follows the camera around. Once placed, the anchor stays put and the user can walk around it.

There are two ways to place content.

**A button entity.** Set **Placement Button** to an entity with an `element` component; tapping it toggles between placing and un-placing. Make sure **Use Input** is enabled on that element, or it won't receive input events.

**An app event.** Fire this from your own code, typically in a button handler:

```ts
// true  -> back to placement mode; content follows the camera
// false -> lock the content in place
this.app.fire('zappar:instant_tracker', { message: 'placement_mode', placementMode: false });
```

## Realtime Camera-based Reflections

### Environment Map

`zapparCubemapRenderer` renders your scene, including the live camera feed, into a cubemap and assigns it to the `cubeMap` property of every material tagged `reflective`. That gives reflective materials an approximate environment of the user's real surroundings to reflect.

1. Create a new entity and `Add Component` > `Camera`. The script only reads render settings off this camera, such as layers, clear flags and clip planes, and disables it for direct rendering.
2. `Add Component` > `Script`, and add `zapparCubemapRenderer`.
3. Tag any material you want it applied to with `reflective`:

<img src="images/camera-reflective-tag.png" width="640">

| Attribute | Default | Description |
| --- | --- | --- |
| **Resolution** | `512` | Resolution of one cubemap face, clamped to the device maximum. Use a power of two for mipmaps. |
| **Mipmaps** | `true` | Allocate and generate mipmaps. |
| **Depth** | `true` | Allocate a depth buffer. |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

The camera feed is drawn as a fullscreen quad, so every cubemap face receives the same
image. Reflections are therefore an approximation of the environment rather than a
directionally accurate one, which is usually what you want for this effect.

A `StandardMaterial` needs configuring before it shows reflections. Use whichever
workflow suits your content:

- **Metalness** (`useMetalness` on): set `metalness` to `1` and pick a light `diffuse`.
  Reflections are tinted by the albedo, so a dark diffuse darkens them.
- **Specular** (`useMetalness` off): set `specular` towards white and `reflectivity` to
  `1`. Specular is black by default, which suppresses reflections.

In both cases `gloss` sets the sharpness: `1` gives a mirror, lower values blur the
reflection.

### Probe Sphere

For the simpler case of showing the live camera feed on a surface, `zapparProbeSphere` applies the camera-feed texture to its entity's mesh as an emissive map.

1. Create an entity with a `render` component. A sphere works well.
2. `Add Component` > `Script`, and add `zapparProbeSphere`.

| Attribute | Default | Description |
| --- | --- | --- |
| **Camera** | blank | The Zappar camera entity. Leave blank unless you have more than one. |

This replaces the entity's material with an unlit one showing the feed, so use a dedicated entity.

## Snapshots and Social Sharing

`zapparScreenshot` captures the canvas and presents Zappar's built-in save/share UI. It can save the image to the device and, where the browser supports the Web Share API, share it to other installed apps.

Attach the script to any entity, then trigger a capture:

```ts
this.app.fire('zappar:capture_snapshot');
```

The capture happens at the end of the current frame, so the camera feed and your content are both included.

| Attribute | Description |
| --- | --- |
| **Download** | `fileName` (default `ZapparPlaycanvas`) and `imageFormat` (default `image/png`) used when saving. |
| **Share** | `showButton`, `title`, `text` and `url` for the share sheet. |
| **Localisation** | Strings for the UI: `save`, `share`, `nowOpenFilesAppToShare`, `tapAndHoldToSave`. |

The script reports back on what the user did:

```ts
this.app.on('zappar:snapshot', (ev) => {
  switch (ev.message) {
    case 'snapshot_saved':
      break;
    case 'snapshot_shared':
      break;
    case 'snapshot_closed':
      break;
  }
});
```

## Scripting Against the Library

The scripts cover the common cases, but everything underneath is available if you need to go further. This library is a thin wrapper over [`@zappar/zappar`](https://www.npmjs.com/package/@zappar/zappar), whose documentation covers the full computer vision API.

### Reaching the Underlying Zappar Objects

Each tracker script exposes the Zappar object it wraps, so you can read anchors, poses and identity/expression data directly:

| Script | Property | Type |
| --- | --- | --- |
| `zapparCamera` | `pipeline` | `Zappar.Pipeline` |
| `zapparCamera` | `cameraPoseMatrix` | `pc.Mat4`, the current camera pose |
| `zapparCamera` | `backgroundTexture` | `pc.Texture` of the live feed |
| `zapparCamera` | `mirror` | `boolean`, whether poses are mirrored |
| `zapparCamera` | `poseAnchorOrigin` | the anchor used as world origin in `anchor` pose mode |
| `zapparImageTracker` | `imageTracker` | `Zappar.ImageTracker` |
| `zapparFaceTracker` | `faceTracker` | `Zappar.FaceTracker` |
| `zapparWorldTracker` | `worldTracker` | `Zappar.WorldTracker` |
| `zapparInstantTracker` | `instantTracker` | `Zappar.InstantWorldTracker` |
| `zapparInstantTracker` | `hasPlaced` | `boolean` |
| `zapparCubemapRenderer` | `cubeMap` | `pc.Texture` |

```ts
const tracker = myTrackerEntity.script?.get('zapparFaceTracker') as ZapparFaceTracker;
for (const anchor of tracker.faceTracker.visible) {
  console.log(anchor.id, anchor.identity, anchor.expression);
}
```

### Waiting for the Camera

The camera builds its pipeline asynchronously, so it isn't ready the moment its script is created. Rather than depending on script execution order, use `onZapparCameraReady`. It calls back immediately if the camera is already up, and otherwise once it is:

```ts
import { onZapparCameraReady } from '@zappar/zappar-playcanvas';

onZapparCameraReady(this.app, null, (camera) => {
  // camera.pipeline is now available
});
```

Pass an entity instead of `null` to wait for the camera on that specific entity. You can also check `camera.ready`, or listen for the `zappar:camera:ready` app event.

### Positioning Your Own Content From an Anchor

If you're driving entities yourself, for example one per face when tracking several, `applyAnchorPose` does the matrix work:

```ts
import { applyAnchorPose } from '@zappar/zappar-playcanvas';

// In your script's update(), for each anchor you care about:
const { cameraPoseMatrix, mirror } = zapparCamera;
applyAnchorPose(myEntity, anchor.pose(cameraPoseMatrix.data, mirror));
```

The optional third argument is an extra X rotation in degrees, which is how `zapparImageTracker` implements **Target Upright**.

## Script Reference

| Script | Attach to | Attributes |
| --- | --- | --- |
| `zapparCamera` | camera entity | `frontFacingCamera`, `mirrorMode`, `poseMode`, `nearClip`, `farClip` |
| `zapparImageTracker` | content entity | `targetFile`, `targetUpright`, `camera` |
| `zapparFaceTracker` | content entity | `maxFaces`, `camera` |
| `zapparWorldTracker` | content entity | `anchorType`, `camera` |
| `zapparInstantTracker` | content entity | `anchorCameraOffset`, `placementButton`, `camera` |
| `zapparFaceLandmark` | own entity at root | `faceTrackerEntity`, `landmark`, `camera` |
| `zapparFaceMesh` | child of face tracker | `faceTrackerEntity`, `fullHead`, `mask`, `fillMouth`, `fillEyeLeft`, `fillEyeRight`, `material`, `camera` |
| `zapparImageTargetPreviewMesh` | child of image tracker | `imageTrackerEntity`, `targetIndex` |
| `zapparBrowserUtil` | any entity | `compatibilityCheck`, `mobileOnly` |
| `zapparScreenshot` | any entity | `download`, `share`, `localisation` |
| `zapparProbeSphere` | mesh entity | `camera` |
| `zapparCubemapRenderer` | camera entity | `resolution`, `mipmaps`, `depth`, `camera` |

## Event Reference

All events are fired on and listened for on the `pc.AppBase` instance (`this.app`).

**Fired by the library, for you to listen to:**

| Event | `message` values | Extra payload |
| --- | --- | --- |
| `zappar:camera:ready` | none | the `ZapparCamera` instance |
| `zappar:camera` | `permission_granted` | `granted: boolean` |
| `zappar:image_tracker` | `target_loaded`, `new_anchor`, `anchor_visible`, `anchor_not_visible` | `anchor` on the anchor messages |
| `zappar:face_tracker` | `model_loaded`, `new_anchor`, `anchor_visible`, `anchor_not_visible` | `anchor` on the anchor messages |
| `zappar:world_tracker` | `quality_good`, `quality_limited` | none |
| `zappar:face_mesh` | `mesh_loaded` | none |
| `zappar:snapshot` | `snapshot_saved`, `snapshot_shared`, `snapshot_closed` | none |

**Listened for by the library, for you to fire:**

| Event | `message` values | Payload |
| --- | --- | --- |
| `zappar:camera` | `flip` | `userFacing?: boolean`, omit to toggle |
| `zappar:instant_tracker` | `placement_mode` | `placementMode: boolean` |
| `zappar:capture_snapshot` | none | none |

## Development

To work on this library, or to build the Editor scripts yourself instead of downloading the zip:

```bash
npm install
npm run build          # library (lib/) + editor scripts (dist/)
npm run build:module   # lib/, the npm package (tsdown)
npm run build:editor   # dist/, one .mjs per script + CV assets (vite)
npm run build:zip      # dist/ packaged as zappar-playcanvas.zip
npm run typecheck      # tsc --noEmit, across src, tests and scripts
npm run lint           # biome
```

Requires Node **>= 24**, since the repo's scripts rely on Node's native TypeScript stripping.

The test app is a real PlayCanvas v2 app served by webpack-dev-server (see `tests/`), with scenes selected by `?test=<group>/<name>`:

- **automated**: deterministic scenes fed a static target image, driven by Playwright screenshot-regression specs. Covers `camera`, `image-tracking`, `face-tracking` and `camera-probe`.
- **manual**: interactive scenes that use the **live device camera**, for a human to open in a browser. Covers `instant-tracking`, `world-tracking`, `face-mesh` and `face-landmark`.

```bash
npm test               # automated screenshot tests (Playwright)
npm run test:update    # update baselines in tests/__snapshots__/
npm start              # serve the test app at https://localhost:8081
```

For manual tests, run `npm start`, open `https://localhost:8081` on a device with a camera (accept the self-signed cert) and pick a scene from the **manual** section. Use your machine's LAN IP to reach it from a phone.

To add a scene, create `tests/scenes/<name>.ts` (or `tests/scenes/manual/<name>.ts`) exporting `initTest()`, register it in `tests/index.ts`, and for an automated scene add a `tests/<name>.test.ts` spec.

To push the Editor scripts straight into a PlayCanvas project with [`playcanvas-sync`](https://github.com/playcanvas/playcanvas-sync):

```bash
export PLAYCANVAS_API_KEY=…      # https://playcanvas.com/account
export PLAYCANVAS_PROJECT_ID=…
export PLAYCANVAS_BRANCH_ID=…
npm run deploy                   # builds dist/ then pushes the scripts + CV assets
```

All three variables are required by `playcanvas-sync`; it will also read them from a `~/.pcconfig`. File filters live in `pcconfig.json`.

Filenames in `dist/` are intentionally stable rather than content-hashed, so each deploy replaces the previous upload instead of orphaning it.

## Links and Resources

- [Web site](https://zap.works/universal-ar/)
- [Documentation](https://docs.zap.works/universal-ar/)
- [Licensing](https://docs.zap.works/universal-ar/general/licensing/)
- [Forum](https://forum.zap.works/)
- [Issue tracker](https://github.com/zappar-xr/zappar-playcanvas/issues)
- [Source code](https://github.com/zappar-xr/zappar-playcanvas)
- [Zappar for JavaScript](https://www.npmjs.com/package/@zappar/zappar), the underlying computer vision library

