# Hosting scenes

> `@typegpu/kit` 0.1.0. If it is installed, read `node_modules/@typegpu/kit/docs/` instead.

Run a scene file on a web or React Native canvas, with its root, surface, loop, errors and teardown handled in order.

> `import * as hosting from '@typegpu/kit/hosting'`: `hosting.local(create, options?) → Owned`, `hosting.stage(root, surface, createScene, options, hosting) → Promise<Staged>`, `hosting.watch(device, onError)`. Provides shared hosting code without importing React Native. **kind** platform. **owns** a stage's frames and their animation, what its `attach` returned, and the scene, which it destroys. **lifecycle** `destroy()`, `[Symbol.dispose]`. **types** `Callback`, `Scene`, `CreateScene`, `Stage`, `Hosted`, `Detach`, `Pausing`, `CanvasOptions`, `HostOptions`. `src/hosting.ts`.
>
> `OwnOptions`, taken by `local`:
> - `onError?: Callback<[unknown]>` Receives errors from `create`, sent closures and calls that worklets cannot schedule. Default `console.error` on the runtime that owns the value.
>
> `StageOptions`, taken by `stage`:
> - `schedule?: Schedule | false` Supplies animation frames to `animate`. Default `requestAnimationFrame`.
> - `onError: (error: unknown) => void` Receives the first scene error once, after the frames stop: from a frame, `onFrame`, a rejected `ready`, the watched device or `staged.fail`.
> - `watch?: GPUDevice` Watches the device from scene creation until `destroy`, and fails the stage on its first uncaptured error or unexpected loss. Default none.
> - `onFrame?: (stage: Stage<S, Canvas>, frame: Frame) => void` Runs after the scene's `frame` in every frame, with the stage. Default none.
> - `attach?: (stage: Stage<S, Canvas>) => Detach | void` Runs with the stage once it is up; `destroy` frees what it returns before the scene. Default none.
> - `release?: () => void` Releases host resources, such as the surface and the root, at the end of `destroy`, also when a cleanup throws. Default none.
>
> `Owned`, from `local`:
> - `send(fn, ...args)` Runs `fn` with the value on its runtime, after earlier sent calls.
> - `run(fn, ...args)` Runs `fn` from React Native or the page, as `send` does, and copies its result back as `post` does.
> - `destroy()` Calls `destroy` on the value's runtime after earlier sent calls, then releases the value without waiting for their promises.
>
> `Staged`, from `stage`:
> - `fail(error)` Stops the frames and reports `error` to `onError`, unless the stage has failed or been destroyed.
> - `destroy()` Stops the frames, frees what `attach` returned, destroys the loop and the scene, then runs `release`.
> - `scene: S` Holds the scene the host created.
> - `root: TgpuRoot` Holds the root the scene was created on.
> - `surface: Canvas` Holds the canvas surface the scene draws into.
> - `loop: Frames` Holds the frame loop that records the scene.
> - `ready: boolean` Reports whether the scene's `ready` promise has resolved.

A scene is the `createScene(root, surface, options)` function that a scene file exports. It returns an object with the scene's `frame` and an optional `destroy`. Hosting a scene takes a device, error listeners, a surface and a scheduled frame loop. The host frees what it owns, in order. `web.host` does all of this on the web and `useScene` on React Native, with the same scene file.

On the web, `web.host(createScene, options, hosting)` runs a scene on a canvas. `createScene` receives `options` as its third argument. `hosting` holds the canvas and the host's own options, such as the page's `onFrame` and `onError`:

```ts
import * as web from '@typegpu/kit/web';

const hosted = web.host(
  createScene,
  { board: 1 },
  {
    canvas,
    maxPixelRatio: 1.5,
    optionalFeatures: ['timestamp-query', 'indirect-first-instance'],
    onFrame: ({ scene }) => (hud.textContent = `${scene.score}`),
    onError: (error) => (hud.textContent = String(error)),
  },
);

canvas.addEventListener('pointerdown', ({ offsetX, offsetY }) =>
  hosted.send(({ scene }) => scene.point(offsetX, offsetY)),
);
window.addEventListener('pagehide', () => hosted.destroy(), { once: true });
```

## On the web

- **Sending** `send(fn, ...args)` waits until the host has set up the stage. It calls `fn` with `{ scene, root, surface, loop, ready }` as its first argument, followed by `args`.
- **Page frames** `onFrame(stage, frame)` runs after the scene's `frame` in every frame, for page code such as a HUD.
- **Attaching** `attach` runs once the scene is up, with the stage. `attach` can return a cleanup function or an object with `destroy()`. The host frees it before destroying the scene. For example, `attach: ({ scene }) => web.orbitControls(scene.view, canvas)` ties the controls to the scene. The host also accepts `undefined` from `attach` and throws for any other return value.
- **Loading** `stage.ready` stays false while the scene's `ready` promise is pending. Keep the loading screen visible until it resolves. A rejection reports a scene error.
- **Synchronous** The scene's `frame` and `onFrame` are synchronous, since the host submits when they return. One that returns a promise, such as an `async` function, is a scene error, and its frame is never submitted. Load and compile in `createScene`, or behind `ready`.
- **Scene errors** Setup errors from `createScene` or `attach` go to `onError`. The first error from a frame, `onFrame`, a rejected `ready`, an uncaptured device error or an unexpected device loss stops the frame loop and goes to `onError` once.
- **Sent errors** A sent closure that throws goes to `onError` each time and leaves the frames running, as an event handler's error leaves `requestAnimationFrame` running.
- **The stage** To reach the stage directly from page code, take it once with `const stage = await hosted.run((s) => s)`.
- **Pausing** `pause()` and `resume()` wait until the scene is created, as `send` does.
- **Your device** `device` takes a device of your own, which the host leaves alive. A test passes a [recording root](testing.md)'s.
- **Profiling** To time each pass of the scene, install the [GPU debug panel](gpu-debug.md#profiling-from-the-address) before calling `host`.
- **Teardown** `destroy()` releases everything in order, even while the scene is starting. It does not wait for work still running, so a `run` still in flight can find its resources destroyed. Calls sent after `destroy` are dropped, and `run` rejects once the scene is gone. Call it on `pagehide`, and from Vite's `import.meta.hot.dispose`.
- **No options** Omit scene options when they are optional, as in `web.host(createScene, { canvas })`.

In a React component, start the host in an effect and destroy it in the effect's cleanup:

```ts
import * as web from '@typegpu/kit/web';
import { createScene } from './scene.ts';

// In a component that renders <canvas ref={canvasRef} />
useEffect(() => {
  const canvas = canvasRef.current!;
  const hosted = web.host(createScene, {
    canvas,
    attach: ({ scene }) => web.orbitControls(scene.view, canvas),
  });
  return () => hosted.destroy();
}, []);
```

### Scenes that share a root

By default each host makes its own device. A page with several canvases can share one root between its scenes instead. Pass a root you made as `root`, and the host leaves it alive. `schedule` replaces `requestAnimationFrame`. With `schedule: false` the host runs no frames, and the page runs them through each stage's `loop`, for example to draw only the canvases on screen:

```ts
const root = await tgpu.init();
const stages: web.Stage<ReturnType<typeof createScene>>[] = [];

for (const canvas of canvases) {
  web.host(createScene, {
    canvas,
    root,
    schedule: false,
    attach: (stage) => void stages.push(stage),
  });
}

requestAnimationFrame(function tick(now) {
  for (const { loop } of stages) loop.run(now / 1000);
  requestAnimationFrame(tick);
});
```

- Each host watches the device. WebGPU doesn't say which scene caused an error, so the first uncaptured error or unexpected device loss reaches every running scene's `onError`.
- Without a schedule, the first error still stops the frames. A `loop.run` that throws reports the error to `onError` and rethrows it to you. Every later `run` returns false.

## A host of your own

`@typegpu/kit/hosting` is what `web.host` and React Native's [`useScene`](#on-react-native) are built from. It imports nothing from React Native.

- **Staging** `stage(root, surface, createScene, options, { schedule?, onError, watch?, onFrame?, attach?, release? })` creates a scene and scheduled frame loop. `schedule: false` disables automatic frames. The first error from a frame, `onFrame`, `ready` or the `watch` device stops the frames and reaches `onError` once. A frame you `run` yourself also rethrows its error. The stage's `destroy()` calls `release` last, to free host resources. If one of its steps throws, the rest still run. `destroy` then rethrows that error, or, if several threw, an `AggregateError` of all of them with the first one's message.
- **Watching** `watch(device, onError)` calls `onError` once for the first uncaptured error or unexpected device loss. It ignores deliberate device destruction. Dispose the watch to stop listening early.
- **Local values** `local(create)` keeps a value on the calling thread and gives it `send` and `run`, the same handle `runtimes.own` gives on a worker. Use it in a test or on a web page.
- **Types** `Scene` has `frame`, an optional `destroy` and an optional `ready`. Hosts call `destroy` when the scene provides it. `CreateScene` creates it from `(root, surface, options)`, and `Stage` holds it with host resources. `HostOptions` describes the options `web.host` and the React Native `host` share.

A view that draws only when asked, such as a model viewer, stages its scene on a shared root without a schedule, and runs a frame when the view moves:

```ts
import { stage } from '@typegpu/kit/hosting';

const surface = web.surface(root, canvas, { alphaMode: 'premultiplied' });
const staged = await stage(
  root,
  surface,
  createScene,
  {},
  { schedule: false, watch: root.device, onError: show, release: () => surface.destroy() },
);

new ResizeObserver(() => staged.loop.run(0)).observe(canvas);

window.addEventListener('pagehide', () => staged.destroy());
```

## On React Native

> `import { host } from '@typegpu/kit/native/host'`: `host(createScene, options, hosting) → Hosted`. Hosts a scene on a React Native canvas on a worker, the UI runtime or the JS thread. **kind** platform. **owns** a root on the device it is given unless it was given a root, the canvas's configuration, a worker runtime unless it is given one, the scene's stage and what its `attach` returned. **lifecycle** `destroy()`, `[Symbol.dispose]`. **platform** native only. **types** `CreateScene`, `Scene`, `SceneRuntime`, `Stage`. `src/native/host.ts`.
>
> `HostOptions`, taken by `host`:
> - `on?: SceneRuntime` Selects the scene runtime. Default `'worker'`, a runtime named after `createScene` and paced by the display.
> - `context: GPUCanvasContext & { present(): void }` Supplies the canvas context.
> - `width: number` Sets the canvas layout width in points.
> - `height: number` Sets the canvas layout height in points.
> - `pixelRatio: number` Sets the display pixel ratio from `PixelRatio.get()`.
> - `maxPixelRatio?: number` Caps drawing-buffer pixels per point unless `size` is set. Default 2.
> - `size?: FixedSize` Fixes the drawing-buffer size, as in `native.surface`. Default the layout size multiplied by the capped pixel ratio.
> - `device?: GPUDevice` Supplies a device that the host keeps alive. Default a device that the web host requests and destroys with the scene.
> - `root?: TgpuRoot` Supplies a root that the host keeps alive, so scenes can share it. Default a root that the host creates on `device` and destroys with the scene.
> - `schedule?: Schedule | false` Supplies animation frames. Default `requestAnimationFrame`, or display vsync on a React Native worker.
> - `onFrame?: (stage: Stage<S, Canvas>, frame: Frame) => void` Runs after the scene's `frame` each frame, for page work such as a HUD that reads scene state. Default none.
> - `attach?: (stage: Stage<S, Canvas>) => Detach | void` Connects page code, such as orbit controls, to the stage after scene creation. Default none.
> - `onError?: Callback<[unknown]>` Receives the first scene error, from `createScene`, a frame, `onFrame`, `ready` or the device, which stops the frames. Default `console.error`.
> - `format?: GPUTextureFormat` Sets the canvas texture format. Default `navigator.gpu.getPreferredCanvasFormat()`.
> - `alphaMode?: GPUCanvasAlphaMode` Controls canvas transparency. Default `opaque`.
> - `usage?: GPUTextureUsageFlags` Sets the canvas texture usage flags. Default `GPUTextureUsage.RENDER_ATTACHMENT`.
> - `colorSpace?: PredefinedColorSpace` Sets the colour space of canvas values. Default `'srgb'`.
> - `toneMapping?: GPUCanvasToneMapping` Controls the range of canvas values for display. Default `{ mode: 'standard' }`.
>
> `Hosted`, from `host`:
> - `resize(width, height)` Updates the canvas layout size in points, as reported by `onLayout`.
> - `pause()` Stops frames and elapsed time for an app in the background, a canvas outside the viewport or a pause menu.
> - `resume()` Resumes the frames after `pause`.
> - `send(fn, ...args)` Runs `fn` with the value on its runtime, after earlier sent calls.
> - `run(fn, ...args)` Runs `fn` from React Native or the page, as `send` does, and copies its result back as `post` does.
> - `destroy()` Calls `destroy` on the value's runtime after earlier sent calls, then releases the value without waiting for their promises.

`host`, from `@typegpu/kit/native/host`, takes the same `createScene(root, surface, options)` function as [`web.host`](#on-the-web) and runs it on a React Native canvas. It runs on a worker by default. You can also use the UI runtime or the JS thread. The host owns the canvas configuration, the scene and any root or worker it creates. It schedules worker frames at display vsync by default. `@typegpu/kit/native/runtimes` provides the same runtime controls for code outside a kit scene. `useScene` wraps the host for a React Native canvas.

> `import { useScene } from '@typegpu/kit/native/react'`: `useScene(createScene, options, hosting?) → SceneHandle`. Hosts a scene on a react-native-webgpu `<Canvas>` through `useScene`. **kind** platform. **owns** what `host` owns, plus a requested device: releases them when the component unmounts. **platform** native only. **types** `CreateScene`, `Hosted`, `SceneRuntime`, `Scene`, `Stage`. `src/native/react.ts`.
>
> `UseSceneOptions`, taken by `useScene`:
> - `on?: SceneRuntime` Selects the scene runtime. Default `'worker'`, one per component named after `createScene`.
> - `paused?: boolean` Pauses frames while true, such as for a canvas outside the viewport. Default false.
> - `device?: GPUDevice` Supplies a device shared by scenes. Default the nearest `<GPUDeviceProvider>` device, or a device requested for this scene alone.
> - `optionalFeatures?: Iterable<GPUFeatureName>` Requests these features when the adapter supports them, such as `indirect-first-instance`. Default none.
> - `onFrame?: HostOptions<S>['onFrame']` Runs after the scene's `frame` each frame on the scene runtime, as `host`'s `onFrame` does, such as to count the frames drawn before a loading screen lifts. Default none.
> - `maxPixelRatio?: number` Caps drawing-buffer pixels per point. Default 2.
> - `alphaMode?: GPUCanvasAlphaMode` Controls canvas transparency. Default `opaque`.
>
> `SceneHandle`, from `useScene`:
> - `canvas: { readonly ref: RefObject<CanvasRef | null>; readonly onLayout: (event: LayoutChangeEvent) => void }` Provides props to spread onto react-native-webgpu's `<Canvas>`.
> - `scene: Hosted<S> | undefined` Provides the hosted scene after the canvas has a size and the device is ready.
> - `error: Error | undefined` Reports the first error: from the device, setup, a frame or a sent closure.

Call `useScene` in a component. Beyond what the host does, it obtains a device, sizes the surface, pauses with the app and reports errors.

```tsx title="Blockfall.tsx"
import { useScene, type Stage } from '@typegpu/kit/native/react';
import { useState } from 'react';
import { Text } from 'react-native';
import {
  GestureDetector,
  usePanGesture,
  useSimultaneousGestures,
  useTapGesture,
} from 'react-native-gesture-handler';
import { Canvas } from 'react-native-webgpu';
import type { Score } from './game.ts';
import { createScene } from './scene.ts';

type Blockfall = Awaited<ReturnType<typeof createScene>>;

const blockfall: typeof createScene = (root, surface, options) => {
  'worklet';
  return createScene(root, surface, options);
};

function drop({ scene }: Stage<Blockfall>) {
  'worklet';
  scene.game.drop();
}

function orbit({ scene }: Stage<Blockfall>, dx: number) {
  'worklet';
  scene.view.goal.yaw -= dx * 0.01;
}

export function BlockfallScreen() {
  const [score, setScore] = useState<Score>();
  const { canvas, scene, error } = useScene(blockfall, { onScore: setScore });
  const send = scene?.send;

  const tap = useTapGesture({
    onActivate: () => {
      'worklet';
      send?.(drop);
    },
  });
  const pan = usePanGesture({
    onUpdate: (e) => {
      'worklet';
      send?.(orbit, e.changeX);
    },
  });

  if (error) return <Text>{error.message}</Text>;
  return (
    <GestureDetector gesture={useSimultaneousGestures(tap, pan)}>
      <Canvas {...canvas} style={{ flex: 1 }} />
    </GestureDetector>
  );
}
```

Blockfall's `scene.ts` runs unchanged on the web and on React Native. The screen passes `blockfall`, a worklet that calls `createScene` through a named import. That import makes worklets load `scene.ts` on the scene's runtime, with its shaders and modules. A `'worklet'` line in `createScene` itself would copy the shaders it captures instead. If `createScene` isn't a worklet, the hook's `error` shows the line to write.

What the hook does for you:

- **Worker** A worker runs the scene by default, paced by `vsync`, with the [timer floor](#what-it-costs) set by `runtimes.worker`. Each component reuses one worker named after `createScene`, because worklets can't destroy runtimes.
- **Device** The hook uses the nearest `<GPUDeviceProvider>`'s device. Without a provider, it requests a device with the `optionalFeatures` the adapter has and destroys that device after releasing the scene.
- **Device errors** The hook listens for uncaptured errors and `device.lost` on the JS thread with [`hosting.watch`](#a-host-of-your-own). The first error or loss releases the scene and sets `error`. Deliberate device destruction doesn't count as loss. On a shared device, the error stops every scene because WebGPU doesn't identify its source scene.
- **Restarting** Remount the component with a different `key` to restart. A new `<Canvas>` under the same hook, such as one inside a remounted parent, restarts the scene on it. If a provider's device is lost, remount the provider too.
- **Resizing** Canvas layout changes resize the surface. `AppState` pauses and resumes it. Use `paused` to stop a canvas scrolled out of view. A paused scene on a worker asks the display for no frames.
- **Thrown errors** Scheduled work catches errors and the hook stores the first one in `error`. A scene error stops the frames. A sent closure or a failure to schedule it can report an error while the scene keeps running.
- **Callbacks** The hook wraps each plain function at the top level of the scene's options, so every call reaches the latest render's function. Off the JS thread, the host runs that wrapper on the JS thread through `post`. An inline arrow doesn't restart the scene.
- **Options** Initial options come from the render that starts the scene. Send changes from an effect, as in `useEffect(() => send?.(setWeather, weather), [send, weather])`. Restarting the scene creates another `send`, so the effect resends the value.
- **Frame callback** `onFrame` runs after each frame on the scene's runtime, as `host`'s does, such as to count the frames drawn before you remove a loading cover. Off the JS thread it must be a worklet. The hook reads it when the scene starts.
- **Teardown** Teardown runs on the scene's runtime after any frame in flight and unconfigures the canvas. The same component starts again only after it, on a StrictMode remount or a new canvas. A remount under a new `key` starts at once on its own canvas.

### Where it runs

The `on` option, in the hook's third argument, takes `'worker'`, `'ui'`, `'js'` or a runtime of your own. The card lists the other options there. The scene code is the same on every runtime:

```tsx
const { canvas, scene, error } = useScene(blockfall, { onScore: setScore }, { on: 'ui' });
```

- `'worker'` keeps scene work off the UI runtime. Pass a runtime as `on` to share one worker between components.
- `'ui'` shares the UI runtime with Reanimated. Long scene frames delay the app's UI. Use it when Reanimated must read shared values in the same frame.
- `'js'` runs at most 60 Hz and needs no worklet wrapper. React Native DevTools can debug this runtime. Use it to debug a scene that normally runs on a worker.

### Steering it

`send` runs a closure on the scene's runtime with the stage, which holds the scene, root, surface and loop. A closure reaches anything there, so the scene needs no message schema. `run` does the same and returns the result to React Native as a promise.

### Without React

Call `host` directly in an app with its own lifecycle. Pass the device, the canvas's context, its layout size and the pixel ratio, and call `resize`, `pause`, `resume` and `destroy` yourself.

- **Options** It accepts [`web.host`](#on-the-web)'s `schedule`, `onFrame`, `attach` and `onError` options. It also accepts canvas `format`, `alphaMode`, `usage`, `colorSpace`, `toneMapping` and a fixed `size`. Off the JS thread, `onFrame` and `attach` must be worklets. The host throws an error naming a callback that isn't one.
- **A root** Pass a `root` in place of a device only with `on: 'js'`, because a root must stay on the thread that created it.
- **Schedule** `schedule` replaces display vsync. With `false`, no frames run automatically. Call `run(({ loop }) => loop.run(seconds))` yourself. A frame's error reaches `onError` and rejects that promise. Running the frame through `send` instead would report the error to `onError` twice.
- **Device errors** The device's errors reach only the JS thread. With `on: 'js'` the host watches the device; elsewhere, listen with `hosting.watch(device, onError)`, as `useScene` does.

For a scene with two canvases or none, start it with the runtime pieces below.

## The runtime pieces

> `import * as runtimes from '@typegpu/kit/native/runtimes'`: `runtimes.worker(options?) → WorkerRuntime`, `runtimes.vsync(runtime) → Vsync`, `runtimes.own(runtime, create, options?) → Owned`, `runtimes.callable(fn) → Callback`, `runtimes.post`, `runtimes.cell`, `runtimes.camera`. Runs GPU work on React Native worklet runtimes. **stability** unstable: may change in any way in a minor release. **kind** platform. **lifecycle** `destroy()`, `[Symbol.dispose]`. **platform** native only. **types** `Callback`, `OwnOptions`, `Schedule`, `Runtime`, `Orientation`, `CameraFrame`. `src/native/runtimes.ts`.
>
> `WorkerOptions`, taken by `worker`:
> - `name?: string` Labels the runtime in errors and the debugger. Default `'TypeGPU Kit'`.
> - `timerFloor?: number` Sets the minimum delay of `setTimeout(0)`, in milliseconds. Default 2.
>
> `WorkerRuntime`, from `worker`:
> - `destroy()` Restores the runtime's own `setTimeout`.
>
> `Vsync`, from `vsync`:
> - `missed()` Returns the number of display frames skipped while the runtime was running the prior frame.
> - `destroy()` Stops the relay.
> - `request(callback)` Calls `callback` with the time in milliseconds at the next frame and returns the request's id.
> - `cancel(request)` Cancels the request with this id.
>
> `Owned`, from `own`:
> - `send(fn, ...args)` Runs `fn` with the value on its runtime, after earlier sent calls.
> - `run(fn, ...args)` Runs `fn` from React Native or the page, as `send` does, and copies its result back as `post` does.
> - `destroy()` Calls `destroy` on the value's runtime after earlier sent calls, then releases the value without waiting for their promises.
>
> `Cell`, from `cell`:
> - `read(into)` Copies the latest fields into `into` and returns it.
> - `write(values)` Writes the fields in `values` and keeps the others.
>
> `CameraSource`, from `camera`:
> - `write(frame)` Passes `frame` to the feed's runtime.
> - `destroy()` Releases held frames and ignores later ones.
> - `latest(device, seen?)` Imports the newest frame on `device`.

`@typegpu/kit/native/runtimes` provides runtime creation, scheduling and cross-runtime calls. Hosted code uses the kit's normal API on its own runtime.

| Piece                           | What it does                                                                                                                     |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `runtimes.worker()`             | A runtime with WebGPU, whose zero-delay timers wait 2 ms, so react-native-webgpu's pump can't spin it                            |
| `runtimes.vsync(runtime)`       | Frames for a worker at the display's vsync, relayed from the UI runtime; a worker's own `requestAnimationFrame` is a 16 ms timer |
| `runtimes.own(runtime, create)` | Keeps a value on its runtime, reached by closures that run there, and catches what they throw                                    |
| `runtimes.cell(fields)`         | Numbers and flags any runtime writes and reads without a lock or a wait for the UI thread                                        |
| `runtimes.post(fn)`             | Calls `fn` on React Native with its arguments copied first                                                                       |
| `runtimes.callable(fn)`         | Runs a worklet where it is called, and any other function through `post`                                                         |
| `hosting.local(create)`         | The same handle as `own` on the calling thread, without worklets: the JS thread, the web and tests                               |
| `runtimes.camera(runtime)`      | VisionCamera frames for a [video feed](video.md#sources) on `runtime`, handed over from the camera thread                     |

Start a scene on a worker using these runtime functions:

```ts title="blockfall-host.ts"
import { animate, create as createFrames } from '@typegpu/kit/frames';
import { surface as canvasSurface } from '@typegpu/kit/native';
import * as runtimes from '@typegpu/kit/native/runtimes';
import { tgpu } from 'typegpu';
import { createScene } from './scene.ts';

const worker = runtimes.worker();
const display = runtimes.vsync(worker);

export interface Start {
  readonly device: GPUDevice;
  readonly context: GPUCanvasContext & { present(): void };
  readonly size: { readonly width: number; readonly height: number };
  readonly pixelRatio: number;
  readonly onScore: (score: number) => void;
}

export function startBlockfall(start: Start) {
  const { device, context, size, pixelRatio } = start;
  const options = { onScore: runtimes.post(start.onScore) };

  return runtimes.own(
    worker,
    async () => {
      'worklet';
      const root = tgpu.initFromDevice({ device });
      const surface = canvasSurface(root, { getContext: () => context }, { pixelRatio });
      surface.resize(size.width, size.height);

      const scene = await createScene(root, surface, options);
      const loop = createFrames(root, (frame) => scene.frame(frame));
      const animation = animate(loop, { surface, schedule: display, onError: console.error });

      const destroy = () => {
        animation.destroy();
        loop.destroy();
        scene.destroy?.();
        surface.destroy();
        root.destroy();
      };
      return { scene, surface, destroy };
    },
    { onError: console.error },
  );
}
```

```ts title="App.tsx"
const blockfall = startBlockfall({
  device,
  context,
  size,
  pixelRatio: PixelRatio.get(),
  onScore: setScore,
});

blockfall.send(({ scene }) => {
  'worklet';
  scene.game.drop();
});
```

- **Any value** `own` keeps any value returned by `create`. The callback can use the same setup code as a web page.
- **Named imports** Named imports let worklets load `createScene`, `createFrames`, `animate` and `tgpu` on the worker, including their shaders. Namespace imports such as `import * as frames` copy the namespace instead. Its functions can't be called on that runtime, so the worklet above uses no namespace imports.
- **Early sends** Calls to `send` made while `create` runs wait for it. `send` is a worklet itself, so a Gesture Handler callback on the UI runtime sends straight to the worker.
- **Async closures** A promise can't cross runtimes, so `run` awaits an async closure on the value's runtime.
- **Cached copies** `send` reuses cached argument copies. If you mutate an object and resend it, the receiver gets its first copy. Send another object to transfer changed values.
- **Errors** Errors from `create`, sent closures or scheduling `send` reach `onError`.

### Frames on a worker

`vsync(worker)` relays the UI runtime's display link. A worker requests a frame and the next vsync schedules it there. If the previous frame is still running, the relay skips that vsync, which `missed()` counts. A relayed vsync runs only the request it was sent for. If you cancel or replace that request, the relayed frame is dropped and a replacement waits for a later vsync. `destroy` stops delivery. Once no frame is requested and the last one has run, the relay stops asking the display for frames. Pass the relay to `animate` as `schedule`, which defaults to `requestAnimationFrame`. A test passes a schedule it steps by hand.

### Values between runtimes

```ts
const pointer = runtimes.cell({ x: 0, y: 0, down: false });

// a gesture on the UI runtime
pointer.write({ x: event.x, y: event.y });

// the scene's frame, on the worker; `here` is an object the scene made once
pointer.read(here);
```

- A cell is one fixed-type synchronizable per field, so a read takes no lock and allocates nothing. Fields are read one at a time, so one read can return fields from two different writes.
- It holds the latest value only. Send events that mustn't be lost, like a tap or a key, through `send`, which queues them in order.
- `post(fn)` calls React Native code with copied arguments. A reused object arrives with its values at the time of each call.
- Worklet callbacks run on the calling runtime. Other callbacks run on React Native with copied arguments.

### With code you already have

- **A renderer of your own.** `own(worker, createRenderer)` holds it, and `vsync` paces it. Nothing needs `frames` or a TypeGPU Kit scene.
- **@typegpu/react.** The resources it transfers keep working; `runtimes` registers no serializer of its own.
- **Reanimated and Gesture Handler.** Gesture worklets write cells or call `send`. A shared value can go in a scene's options, but reading one on a worker waits for the UI thread.
- **A runtime someone else made.** `own` and `vsync` take any runtime.
- **Compiling off the frame's runtime.** `own(worker, warm)` compiles pipelines while the UI runtime draws. Dawn shares its pipeline cache across runtimes.

### Testing

In a test, a scene builds on `recordingRoot()` with no worklets. `local` gives the same `Owned` on the test's thread, and a hand-stepped schedule drives `animate`.

- `local`, `Owned` and the scene types live in [`@typegpu/kit/hosting`](#a-host-of-your-own), which imports nothing from React Native. A test or a web page needs no worklets mock.
- `native/runtimes` and `native/host` import react-native-worklets; only `native/react` imports React.
- `runtimes.cell` needs worklets, so in its test a scene that reads one takes any object with the same `read` and `write`:

```ts
const values = { x: 0, active: false };
const input = {
  read: (into: typeof values) => Object.assign(into, values),
  write: (next: Partial<typeof values>) => void Object.assign(values, next),
};
```

## Who does what

| Runtime             | Holds                                                                   |
| ------------------- | ----------------------------------------------------------------------- |
| JS thread           | the device, `device.lost`, React state, the hook, assets                |
| UI runtime          | the display link and its relay, Gesture Handler's callbacks, Reanimated |
| the scene's runtime | the root, the modules, recording, submit, present and readback maps     |

Use one runtime to record into a canvas and its encoders. Other runtimes may share the device with `implicit-device-synchronization`, which react-native-webgpu requests by default. They must not share that canvas or those encoders. A host that runs its scene off the JS thread checks for the feature before it starts the scene and throws for a device without it. `useScene` shows that error as its `error`.

## What it costs

- **Bundle Mode** Bundle Mode with `importForwarding` and worklets' patch to Metro. [Setting up a project](../getting-started.md#setting-up-a-project) has the configs.
- **A worklet** A one-line worklet that calls `createScene` off the JS thread, and named imports inside worklets.
- **The relay** The relay's callback on the UI runtime at every display frame while the scene animates. It stops asking the display for frames while the scene is paused.
- **Live runtimes** Worklets can't destroy runtimes. `destroy` releases the scene while its runtime stays alive.
- **Timer floor** A worker created by `runtimes.worker` delays zero-delay `setTimeout` calls by 2 ms. Set `worker({ timerFloor: 0 })` to disable this floor. The worker's `destroy()` gives the runtime back its own `setTimeout`. `host` and `useScene` destroy the workers they create once their scenes are released.
- **Your worklets** Your own scheduled worklets still abort a Release build when they throw. Code sent through `send` is guarded.

## Limits

- Only functions at the top level of a scene's options run on React Native by themselves. A callback nested deeper needs `runtimes.post` by hand.
- A cell has no version a reader can check, so a read can't tell that it mixed two writes. A cell suits pointers and sticks, not a value that must stay whole, such as a transform.
- No host runs a scene in a web worker.
